Policy 1707 Second commit
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / elk / client / PolicyElasticSearchController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
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 package org.openecomp.policy.pap.xacml.rest.elk.client;
21
22
23 import java.io.PrintWriter;
24 import java.security.KeyManagementException;
25 import java.security.NoSuchAlgorithmException;
26 import java.security.cert.X509Certificate;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31
32 import javax.net.ssl.HostnameVerifier;
33 import javax.net.ssl.HttpsURLConnection;
34 import javax.net.ssl.SSLContext;
35 import javax.net.ssl.SSLSession;
36 import javax.net.ssl.TrustManager;
37 import javax.net.ssl.X509TrustManager;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
40
41 import org.json.JSONObject;
42 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
43 import org.openecomp.policy.common.logging.flexlogger.Logger;
44 import org.openecomp.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType;
45 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
46 import org.openecomp.policy.rest.dao.CommonClassDao;
47 import org.openecomp.policy.rest.jpa.ActionPolicyDict;
48 import org.openecomp.policy.rest.jpa.Attribute;
49 import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
50 import org.openecomp.policy.rest.jpa.ClosedLoopD2Services;
51 import org.openecomp.policy.rest.jpa.ClosedLoopSite;
52 import org.openecomp.policy.rest.jpa.DCAEuuid;
53 import org.openecomp.policy.rest.jpa.DecisionSettings;
54 import org.openecomp.policy.rest.jpa.EcompName;
55 import org.openecomp.policy.rest.jpa.EnforcingType;
56 import org.openecomp.policy.rest.jpa.GroupPolicyScopeList;
57 import org.openecomp.policy.rest.jpa.MicroServiceLocation;
58 import org.openecomp.policy.rest.jpa.MicroServiceModels;
59 import org.openecomp.policy.rest.jpa.PEPOptions;
60 import org.openecomp.policy.rest.jpa.RiskType;
61 import org.openecomp.policy.rest.jpa.SafePolicyWarning;
62 import org.openecomp.policy.rest.jpa.TermList;
63 import org.openecomp.policy.rest.jpa.VNFType;
64 import org.openecomp.policy.rest.jpa.VSCLAction;
65 import org.openecomp.policy.rest.jpa.VarbindDictionary;
66 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
67 import org.springframework.stereotype.Controller;
68 import org.springframework.web.bind.annotation.RequestMapping;
69 import org.springframework.web.servlet.ModelAndView;
70
71 import com.fasterxml.jackson.databind.DeserializationFeature;
72 import com.fasterxml.jackson.databind.JsonNode;
73 import com.fasterxml.jackson.databind.ObjectMapper;
74
75 import io.searchbox.client.JestResult;
76
77 @Controller
78 @RequestMapping({"/"})
79 public class PolicyElasticSearchController{
80
81         private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class);
82         private List<JSONObject> policyNames = null;
83
84         enum Mode{
85                 attribute, ecompName, actionPolicy, brmsParam, pepOptions, clSite, clService, clVarbind, clVnf, clVSCL, decision, enforcer, fwTerm, msDCAEUUID, msConfigName, msLocation, msModels,
86                 psGroupPolicy, safeRisk, safePolicyWarning
87         }
88
89         public static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() {
90                 private static final long serialVersionUID = 1L;
91         };
92
93         public static CommonClassDao commonClassDao;
94
95         public PolicyElasticSearchController(CommonClassDao commonClassDao) {
96                 PolicyElasticSearchController.commonClassDao = commonClassDao;
97         }
98
99         public PolicyElasticSearchController() {}
100
101         public static void TurnOffCertsCheck() {
102
103                 // Create a trust manager that does not validate certificate chains
104                 TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
105                         public java.security.cert.X509Certificate[] getAcceptedIssuers() {
106                                 return null;
107                         }
108
109                         public void checkClientTrusted(X509Certificate[] certs,
110                                         String authType) {
111                         }
112
113                         public void checkServerTrusted(X509Certificate[] certs,
114                                         String authType) {
115                         }
116                 } };
117
118                 // Install all-trusting trust manager
119                 SSLContext ctx;
120                 try {
121                         ctx = SSLContext.getInstance("SSL");
122                         ctx.init(null, trustAllCerts, new java.security.SecureRandom());
123                         HttpsURLConnection.setDefaultSSLSocketFactory(ctx
124                                         .getSocketFactory());
125                 } catch (NoSuchAlgorithmException | KeyManagementException e) {
126                         LOGGER.error("SSL Security Error: " + e);
127                 }
128
129                 // Create all-trusting host name verifier
130                 HostnameVerifier allHostsValid = new HostnameVerifier() {
131                         public boolean verify(String hostname, SSLSession session) {
132                                 return true;
133                         }
134                 };
135
136                 // Install the all-trusting host verifier
137                 HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
138         }
139
140         protected void clSearchBody(String clPolicyType, String bodyField, String bodyValue,
141                         ArrayList<Pair<ArrayList<String>, ArrayList<String>>> filter_s) {
142                 if (LOGGER.isDebugEnabled())
143                         LOGGER.debug("ENTER: " + clPolicyType + ":" + bodyField + ":" + bodyValue);
144
145                 final ArrayList<String> clBodyField_s = new ArrayList<String>();
146                 final ArrayList<String> clBodyValue_s = new ArrayList<String>();
147
148                 if (clPolicyType == null || clPolicyType.isEmpty()) {
149                         clBodyField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + bodyField);
150                         clBodyField_s.add("Policy.Body."+ ElkConnector.PolicyType.Config_PM.name() + "_Body." + bodyField);
151                         clBodyValue_s.add(bodyValue);
152                 } else {
153                         clBodyField_s.add("Policy.Body." + clPolicyType + "_Body." + bodyField);
154                         clBodyValue_s.add(bodyValue);
155                 }
156                 filter_s.add(new Pair<ArrayList<String>, ArrayList<String>>(clBodyField_s, clBodyValue_s));
157         }
158
159         protected void clSearchFilter(String clType, String clField, String clValue, 
160                         ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s) {
161                 if (LOGGER.isDebugEnabled())
162                         LOGGER.debug("ENTER: " + clType + ":" + clField + ":" + clValue);
163
164                 ArrayList<String> clSearchField_s = new ArrayList<String>();
165                 clSearchField_s.add("Policy.Body." + clType + "_Body." + clField);
166
167                 ArrayList<String> clSearchValue_s = new ArrayList<String>();
168                 clSearchValue_s.add(clValue);
169
170                 filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchField_s, clSearchValue_s));
171         }
172
173         public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException {
174                 if (type == null || type.isEmpty())
175                         return PolicyIndexType.all;
176
177                 return PolicyIndexType.valueOf(type);
178         }
179
180         public boolean updateElk(PolicyRestAdapter policyData) {
181                 boolean success = true;
182                 try {
183                         success = ElkConnector.singleton.update(policyData);
184                         if (!success) {
185                                 if (LOGGER.isWarnEnabled()) {
186                                         LOGGER.warn("FAILURE to create ELK record created for " + policyData.getNewFileName());
187                                 }
188                         } else {
189                                 if (LOGGER.isInfoEnabled()) {
190                                         LOGGER.warn("SUCCESS creating ELK record created for " + policyData.getNewFileName());
191                                 }                                                                       
192                         }                                                                       
193                 } catch (Exception e) {
194                         LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
195                         success = false;
196                 }
197                 return success;
198         }
199
200         public boolean deleteElk(PolicyRestAdapter policyData) {
201                 boolean success = true;
202                 try {
203                         success = ElkConnector.singleton.delete(policyData);
204                         if (!success) {
205                                 if (LOGGER.isWarnEnabled()) {
206                                         LOGGER.warn("FAILURE to delete ELK record created for " + policyData.getNewFileName());
207                                 }
208                         } else {
209                                 if (LOGGER.isInfoEnabled()) {
210                                         LOGGER.warn("SUCCESS deleting ELK record created for " + policyData.getNewFileName());
211                                 }                                                                       
212                         }                                                                       
213                 } catch (Exception e) {
214                         LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
215                         success = false;
216                 }
217                 return success;
218         }
219
220         @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
221         public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
222                 try{
223                         ObjectMapper mapper = new ObjectMapper();
224                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
225                         JsonNode root = mapper.readTree(request.getReader());
226                         String dictionaryType = root.get("type").textValue();
227                         Mode mode = Mode.valueOf(dictionaryType);
228                         String value; 
229                         @SuppressWarnings("unused")
230                         String msg;
231                         switch (mode){
232                         case attribute :
233                                 Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class);
234                                 value = attributedata.getXacmlId();
235                                 msg = searchElkDatabase("pholder",value);
236                                 break;
237                         case ecompName :
238                                 EcompName ecompName = (EcompName)mapper.readValue(root.get("data").toString(), EcompName.class);
239                                 value = ecompName.getEcompName();
240                                 msg = searchElkDatabase("pholder",value);
241                                 break;
242                         case actionPolicy :
243                                 ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class);
244                                 value = actionPolicyDict.getAttributeName();
245                                 msg = searchElkDatabase("pholder",value);
246                                 break;
247                         case brmsParam :
248                                 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class);
249                                 value = bRMSParamTemplate.getRuleName();
250                                 msg = searchElkDatabase("BRMSParamTemplate AND " + value);
251                                 break;
252                         case pepOptions :
253                                 PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class);
254                                 value = pEPOptions.getPepName();
255                                 msg = searchElkDatabase("pepName",value);
256                                 break;
257                         case clSite :
258                                 ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class);
259                                 value = closedLoopSite.getSiteName();
260                                 msg = searchElkDatabase("siteNames",value);
261                                 break;
262                         case clService :
263                                 ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class);
264                                 value = closedLoopD2Services.getServiceName();
265                                 msg = searchElkDatabase("d2Services",value);
266                                 break;
267                         case clVarbind :
268                                 VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class);
269                                 value = varbindDictionary.getVarbindName();
270                                 msg = searchElkDatabase("triggerSignaturesUsedForUI.signatures",value);
271                                 break;
272                         case clVnf :
273                                 VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class);
274                                 value = vNFType.getVnftype();
275                                 msg = searchElkDatabase("vnfType",value);
276                                 break;
277                         case clVSCL :
278                                 VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class);
279                                 value = vsclAction.getVsclaction();
280                                 msg = searchElkDatabase("actions",value);
281                                 break;
282                         case decision :
283                                 DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class);
284                                 value = decisionSettings.getXacmlId();
285                                 msg = searchElkDatabase("pholder",value);
286                                 break;
287                         case enforcer :
288                                 EnforcingType enforcingType = (EnforcingType)mapper.readValue(root.get("data").toString(), EnforcingType.class);
289                                 value = enforcingType.getEnforcingType();
290                                 msg = searchElkDatabase("pholder",value);
291                                 break;                  
292                         case fwTerm :
293                                 TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class);
294                                 value = term.getTermName();
295                                 msg = searchElkDatabase("firewallRuleList.ruleName",value);
296                                 break;
297                         case msDCAEUUID :
298                                 DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class);
299                                 value = dcaeUUID.getName();
300                                 msg = searchElkDatabase("uuid",value);
301                                 break;
302                         case msLocation :
303                                 MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class);
304                                 value = mslocation.getName();
305                                 msg = searchElkDatabase("location",value);
306                                 break;
307                         case msModels :
308                                 MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class);
309                                 value = msModels.getModelName();
310                                 msg = searchElkDatabase("configName",value);
311                                 break;
312                         case psGroupPolicy :
313                                 GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class);
314                                 value = groupPoilicy.getGroupName();
315                                 msg = searchElkDatabase("PolicyScope",value);
316                                 break;
317                         case safeRisk :
318                                 RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class);
319                                 value = riskType.getRiskName();
320                                 msg = searchElkDatabase("Risk Type",value);
321                                 break;
322                         case safePolicyWarning :
323                                 SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class);
324                                 value = safePolicy.getName();
325                                 msg = searchElkDatabase("Safe Warning",value);
326                                 break;
327                         default:                
328                         }
329                         response.setCharacterEncoding("UTF-8");
330                         response.setContentType("application / json");
331                         request.setCharacterEncoding("UTF-8");
332
333                         PrintWriter out = response.getWriter();
334                         JSONObject j = new JSONObject("{result: " + policyNames + "}");
335                         out.write(j.toString());
336                         return null;
337                 }catch(Exception e){
338                         response.setCharacterEncoding("UTF-8");
339                         request.setCharacterEncoding("UTF-8");
340                         PrintWriter out = response.getWriter();
341                         out.write(e.getMessage());
342                 }
343                 return null;
344         }
345
346         //Search Elk database
347         public String searchElkDatabase(String value){
348                 String policyType = "";
349                 String searchText = value;
350                 JestResult locators;
351                 Map<String, String> filter_s = new HashMap<String, String>();
352                 try {
353                         locators = ElkConnector.singleton.search(toPolicyIndexType(policyType), searchText, filter_s);  
354                 } catch (Exception ise) {
355                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage());
356                         value = "$notSuccess%";
357                         return value;
358                 }
359                 policyNames = new ArrayList<JSONObject>();
360                 System.out.println(locators);
361                 return value;
362         }
363
364         //Search the Elk database
365         public String searchElkDatabase(String key, String value){
366                 String policyType = "";
367                 String searchText = key+":"+value;
368                 JestResult locators;
369                 Map<String, String> filter_s = new HashMap<String, String>();
370                 LOGGER.debug("Parameter value is"+value);
371
372                 String clSearchKey=null;
373                 clSearchKey=key;
374
375                 LOGGER.debug("Filter value is"+clSearchKey);
376
377
378
379                 String clSearchValue=null;
380                 clSearchValue=value;
381
382                 LOGGER.debug("Search value is"+clSearchValue);
383
384                 ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>();
385                 clSearchBoxFilterValue_s.add(clSearchValue);
386
387
388                 try {
389                         locators = ElkConnector.singleton.search(toPolicyIndexType(policyType), searchText, filter_s);  
390                         System.out.println(locators);
391                 } catch (Exception ise) {
392                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage());
393                         //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, ise, "AttributeDictionary", " Exception while searching Elk database ");
394                         LOGGER.debug("Exceptions");
395                         value = "$notSuccess%";
396                         return value;
397                 }
398                 return value;
399         }
400         
401         public JestResult search(PolicyIndexType type, String text, 
402             Map<String, String> searchKeyValue) {
403                  return ElkConnector.singleton.search(type, text, searchKeyValue);
404         }
405         
406 }
407
408 class SearchData{
409         private String query;
410         private String policyType;
411         private String descriptiveScope;
412         private String closedLooppolicyType;
413         private String ecompName;
414         private String d2Service;
415         private String vnfType;
416         private String policyStatus;
417         private String vproAction;
418         private String serviceType;
419         private String bindTextSearch;
420         public String getQuery() {
421                 return query;
422         }
423         public void setQuery(String query) {
424                 this.query = query;
425         }
426         public String getPolicyType() {
427                 return policyType;
428         }
429         public void setPolicyType(String policyType) {
430                 this.policyType = policyType;
431         }
432         public String getDescriptiveScope() {
433                 return descriptiveScope;
434         }
435         public void setDescriptiveScope(String descriptiveScope) {
436                 this.descriptiveScope = descriptiveScope;
437         }
438         public String getClosedLooppolicyType() {
439                 return closedLooppolicyType;
440         }
441         public void setClosedLooppolicyType(String closedLooppolicyType) {
442                 this.closedLooppolicyType = closedLooppolicyType;
443         }
444         public String getEcompName() {
445                 return ecompName;
446         }
447         public void setEcompName(String ecompName) {
448                 this.ecompName = ecompName;
449         }
450         public String getD2Service() {
451                 return d2Service;
452         }
453         public void setD2Service(String d2Service) {
454                 this.d2Service = d2Service;
455         }
456         public String getVnfType() {
457                 return vnfType;
458         }
459         public void setVnfType(String vnfType) {
460                 this.vnfType = vnfType;
461         }
462         public String getPolicyStatus() {
463                 return policyStatus;
464         }
465         public void setPolicyStatus(String policyStatus) {
466                 this.policyStatus = policyStatus;
467         }
468         public String getVproAction() {
469                 return vproAction;
470         }
471         public void setVproAction(String vproAction) {
472                 this.vproAction = vproAction;
473         }
474         public String getServiceType() {
475                 return serviceType;
476         }
477         public void setServiceType(String serviceType) {
478                 this.serviceType = serviceType;
479         }
480         public String getBindTextSearch() {
481                 return bindTextSearch;
482         }
483         public void setBindTextSearch(String bindTextSearch) {
484                 this.bindTextSearch = bindTextSearch;
485         }
486 }