2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.openecomp.policy.pap.xacml.rest.elk.client;
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;
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;
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.pap.xacml.rest.util.JsonMessage;
46 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
47 import org.openecomp.policy.rest.dao.CommonClassDao;
48 import org.openecomp.policy.rest.jpa.ActionPolicyDict;
49 import org.openecomp.policy.rest.jpa.Attribute;
50 import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
51 import org.openecomp.policy.rest.jpa.ClosedLoopD2Services;
52 import org.openecomp.policy.rest.jpa.ClosedLoopSite;
53 import org.openecomp.policy.rest.jpa.DCAEuuid;
54 import org.openecomp.policy.rest.jpa.DecisionSettings;
55 import org.openecomp.policy.rest.jpa.DescriptiveScope;
56 import org.openecomp.policy.rest.jpa.EcompName;
57 import org.openecomp.policy.rest.jpa.GroupPolicyScopeList;
58 import org.openecomp.policy.rest.jpa.MicroServiceLocation;
59 import org.openecomp.policy.rest.jpa.MicroServiceModels;
60 import org.openecomp.policy.rest.jpa.PEPOptions;
61 import org.openecomp.policy.rest.jpa.RiskType;
62 import org.openecomp.policy.rest.jpa.SafePolicyWarning;
63 import org.openecomp.policy.rest.jpa.TermList;
64 import org.openecomp.policy.rest.jpa.VNFType;
65 import org.openecomp.policy.rest.jpa.VSCLAction;
66 import org.openecomp.policy.rest.jpa.VarbindDictionary;
67 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
68 import org.springframework.stereotype.Controller;
69 import org.springframework.web.bind.annotation.RequestMapping;
70 import org.springframework.web.bind.annotation.RequestMethod;
71 import org.springframework.web.servlet.ModelAndView;
73 import com.fasterxml.jackson.databind.DeserializationFeature;
74 import com.fasterxml.jackson.databind.JsonNode;
75 import com.fasterxml.jackson.databind.ObjectMapper;
76 import com.google.gson.JsonArray;
78 import io.searchbox.client.JestResult;
81 @RequestMapping({"/"})
82 public class PolicyElasticSearchController{
84 private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class);
87 attribute, ecompName, actionPolicy, brmsParam, pepOptions,
88 clSite, clService, clVarbind, clVnf, clVSCL, decision,
89 fwTerm, msDCAEUUID, msConfigName, msLocation, msModels,
90 psGroupPolicy, safeRisk, safePolicyWarning
93 public static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() {
94 private static final long serialVersionUID = 1L;
97 public static CommonClassDao commonClassDao;
99 public PolicyElasticSearchController(CommonClassDao commonClassDao) {
100 PolicyElasticSearchController.commonClassDao = commonClassDao;
103 public PolicyElasticSearchController() {}
105 public static void TurnOffCertsCheck() {
106 // Create a trust manager that does not validate certificate chains
107 TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
108 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
111 public void checkClientTrusted(X509Certificate[] certs,
114 public void checkServerTrusted(X509Certificate[] certs,
119 // Install all-trusting trust manager
122 ctx = SSLContext.getInstance("SSL");
123 ctx.init(null, trustAllCerts, new java.security.SecureRandom());
124 HttpsURLConnection.setDefaultSSLSocketFactory(ctx
125 .getSocketFactory());
126 } catch (NoSuchAlgorithmException | KeyManagementException e) {
127 LOGGER.error("SSL Security Error: " + e);
130 // Create all-trusting host name verifier
131 HostnameVerifier allHostsValid = new HostnameVerifier() {
132 public boolean verify(String hostname, SSLSession session) {
137 // Install the all-trusting host verifier
138 HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
144 public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException {
145 if (type == null || type.isEmpty()){
146 return PolicyIndexType.all;
148 return PolicyIndexType.valueOf(type);
151 public boolean updateElk(PolicyRestAdapter policyData) {
152 boolean success = true;
154 success = ElkConnector.singleton.update(policyData);
156 if (LOGGER.isWarnEnabled()) {
157 LOGGER.warn("FAILURE to create ELK record created for " + policyData.getNewFileName());
160 if (LOGGER.isInfoEnabled()) {
161 LOGGER.warn("SUCCESS creating ELK record created for " + policyData.getNewFileName());
164 } catch (Exception e) {
165 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
171 public boolean deleteElk(PolicyRestAdapter policyData) {
172 boolean success = true;
174 success = ElkConnector.singleton.delete(policyData);
176 if (LOGGER.isWarnEnabled()) {
177 LOGGER.warn("FAILURE to delete ELK record created for " + policyData.getNewFileName());
180 if (LOGGER.isInfoEnabled()) {
181 LOGGER.warn("SUCCESS deleting ELK record created for " + policyData.getNewFileName());
184 } catch (Exception e) {
185 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
192 @RequestMapping(value="/searchPolicy", method= RequestMethod.POST)
193 public void searchPolicy(HttpServletRequest request, HttpServletResponse response) {
195 boolean result = false;
196 boolean policyResult = false;
197 ObjectMapper mapper = new ObjectMapper();
198 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
199 PolicyRestAdapter policyData = new PolicyRestAdapter();
200 PolicyElasticSearchController controller = new PolicyElasticSearchController();
201 Map<String, String> searchKeyValue = new HashMap<>();
202 List<String> policyList = new ArrayList<>();
203 if(request.getParameter("policyName") != null){
204 String policyName = request.getParameter("policyName");
205 policyData.setNewFileName(policyName);
206 if("delete".equalsIgnoreCase(request.getParameter("action"))){
207 result = controller.deleteElk(policyData);
209 result = controller.updateElk(policyData);
212 if("search".equalsIgnoreCase(request.getParameter("action"))){
214 JsonNode root = mapper.readTree(request.getReader());
215 SearchData searchData = (SearchData)mapper.readValue(root.get("searchdata").toString(), SearchData.class);
217 String policyType = searchData.getPolicyType();
219 String searchText = searchData.getQuery();
220 String descriptivevalue = searchData.getDescriptiveScope();
221 if(descriptivevalue != null){
222 DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", searchData.getDescriptiveScope());
223 if(dsSearch != null){
224 String[] descriptiveList = dsSearch.getSearch().split("AND");
225 for(String keyValue : descriptiveList){
226 String[] entry = keyValue.split(":");
227 searchKeyValue.put(entry[0], entry[1]);
232 if(searchData.getClosedLooppolicyType() != null){
233 String closedLoopType;
234 if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){
235 closedLoopType = "ClosedLoop_Fault";
237 closedLoopType = "ClosedLoop_PM";
239 searchKeyValue.put("configPolicyType", closedLoopType);
241 if(searchData.getEcompName() != null){
242 searchKeyValue.put("ecompName", searchData.getEcompName());
244 if(searchData.getD2Service() != null){
245 String d2Service = searchData.getD2Service().trim();
246 if(d2Service.equalsIgnoreCase("Hosted Voice (Trinity)")){
247 d2Service = "trinity";
248 }else if(d2Service.equalsIgnoreCase("vUSP")){
250 }else if(d2Service.equalsIgnoreCase("MCR")){
252 }else if(d2Service.equalsIgnoreCase("Gamma")){
254 }else if(d2Service.equalsIgnoreCase("vDNS")){
257 searchKeyValue.put("jsonBodyData."+d2Service+"", "true");
259 if(searchData.getVnfType() != null){
260 searchKeyValue.put("jsonBodyData.vnfType", searchData.getVnfType());
262 if(searchData.getPolicyStatus() != null){
263 searchKeyValue.put("jsonBodyData.closedLoopPolicyStatus", searchData.getPolicyStatus());
265 if(searchData.getVproAction() != null){
266 searchKeyValue.put("jsonBodyData.actions", searchData.getVproAction());
268 if(searchData.getServiceType() != null){
269 searchKeyValue.put("jsonBodyData.serviceTypePolicyName", searchData.getServiceType());
271 if(searchData.getBindTextSearch() != null){
272 searchKeyValue.put(searchData.getBindTextSearch(), searchText);
275 PolicyIndexType type = null;
276 if(policyType != null){
277 if(policyType.equalsIgnoreCase("action")){
278 type = ElkConnector.PolicyIndexType.action;
279 }else if(policyType.equalsIgnoreCase("decision")){
280 type = ElkConnector.PolicyIndexType.decision;
281 }else if(policyType.equalsIgnoreCase("config")){
282 type = ElkConnector.PolicyIndexType.config;
284 type = ElkConnector.PolicyIndexType.closedloop;
287 type = ElkConnector.PolicyIndexType.all;
289 JestResult policyResultList = controller.search(type, searchText, searchKeyValue);
290 if(policyResultList.isSucceeded()){
293 JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray();
294 for(int i =0; i < resultObject.size(); i++){
295 String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString();
296 policyList.add(policyName);
299 LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs");
302 LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e);
307 message = "Elastic Server Transaction is success";
309 message = "Elastic Server Transaction is failed, please check the logs";
311 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(message));
312 JSONObject j = new JSONObject(msg);
313 response.setStatus(HttpServletResponse.SC_OK);
314 response.addHeader("success", "success");
316 JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
317 response.getWriter().write(k.toString());
319 response.getWriter().write(j.toString());
322 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
323 response.addHeader("error", "Exception Occured While Performing Elastic Transaction");
324 LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage());
328 @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
329 public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
331 PolicyIndexType config = PolicyIndexType.config;
332 PolicyIndexType closedloop = PolicyIndexType.closedloop;
333 PolicyIndexType action = PolicyIndexType.action;
334 PolicyIndexType decision = PolicyIndexType.decision;
335 PolicyIndexType all = PolicyIndexType.all;
337 ObjectMapper mapper = new ObjectMapper();
338 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
339 JsonNode root = mapper.readTree(request.getReader());
340 String dictionaryType = root.get("type").textValue();
341 Mode mode = Mode.valueOf(dictionaryType);
343 List<String> policyList = new ArrayList<>();
346 Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class);
347 value = attributedata.getXacmlId();
348 policyList = searchElkDatabase(all, "pholder",value);
351 EcompName ecompName = (EcompName)mapper.readValue(root.get("data").toString(), EcompName.class);
352 value = ecompName.getEcompName();
353 policyList = searchElkDatabase(all, "ecompName",value);
356 ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class);
357 value = actionPolicyDict.getAttributeName();
358 policyList = searchElkDatabase(action, "actionAttributeValue",value);
361 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class);
362 value = bRMSParamTemplate.getRuleName();
363 policyList = searchElkDatabase(config, "ruleName",value);
366 PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class);
367 value = pEPOptions.getPepName();
368 policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value);
371 ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class);
372 value = closedLoopSite.getSiteName();
373 policyList = searchElkDatabase(closedloop,"siteNames",value);
376 ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class);
377 value = closedLoopD2Services.getServiceName();
378 policyList = searchElkDatabase(closedloop, "pholder",value);
381 VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class);
382 value = varbindDictionary.getVarbindName();
383 policyList = searchElkDatabase(closedloop, "jsonBodyData.triggerSignaturesUsedForUI.signatures",value);
386 VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class);
387 value = vNFType.getVnftype();
388 policyList = searchElkDatabase(closedloop, "jsonBodyData.vnfType",value);
391 VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class);
392 value = vsclAction.getVsclaction();
393 policyList = searchElkDatabase(closedloop, "jsonBodyData.actions",value);
396 DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class);
397 value = decisionSettings.getXacmlId();
398 policyList = searchElkDatabase(decision,"pholder",value);
401 TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class);
402 value = term.getTermName();
403 policyList = searchElkDatabase(config, "pholder",value);
406 DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class);
407 value = dcaeUUID.getName();
408 policyList = searchElkDatabase(config, "uuid",value);
411 MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class);
412 value = mslocation.getName();
413 policyList = searchElkDatabase(config, "location",value);
416 MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class);
417 value = msModels.getModelName();
418 policyList = searchElkDatabase(config, "serviceType",value);
421 GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class);
422 value = groupPoilicy.getGroupName();
423 policyList = searchElkDatabase(config, "pholder",value);
426 RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class);
427 value = riskType.getRiskName();
428 policyList = searchElkDatabase(config, "riskType",value);
430 case safePolicyWarning :
431 SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class);
432 value = safePolicy.getName();
433 policyList = searchElkDatabase(config, "pholder",value);
438 response.setStatus(HttpServletResponse.SC_OK);
439 response.addHeader("success", "success");
440 JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
441 response.getWriter().write(k.toString());
443 response.setCharacterEncoding("UTF-8");
444 request.setCharacterEncoding("UTF-8");
445 PrintWriter out = response.getWriter();
446 out.write(e.getMessage());
451 //Search the Elk database
452 public List<String> searchElkDatabase(PolicyIndexType type, String key, String value){
453 PolicyElasticSearchController controller = new PolicyElasticSearchController();
454 Map<String, String> searchKeyValue = new HashMap<>();
455 if(!"pholder".equals(key)){
456 searchKeyValue.put(key, value);
459 List<String> policyList = new ArrayList<>();
460 JestResult policyResultList = controller.search(type, value, searchKeyValue);
461 if(policyResultList.isSucceeded()){
462 JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray();
463 for(int i =0; i < resultObject.size(); i++){
464 String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString();
465 policyList.add(policyName);
468 LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs");
473 public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) {
474 return ElkConnector.singleton.search(type, text, searchKeyValue);
480 private String query;
481 private String policyType;
482 private String descriptiveScope;
483 private String closedLooppolicyType;
484 private String ecompName;
485 private String d2Service;
486 private String vnfType;
487 private String policyStatus;
488 private String vproAction;
489 private String serviceType;
490 private String bindTextSearch;
491 public String getQuery() {
494 public void setQuery(String query) {
497 public String getPolicyType() {
500 public void setPolicyType(String policyType) {
501 this.policyType = policyType;
503 public String getDescriptiveScope() {
504 return descriptiveScope;
506 public void setDescriptiveScope(String descriptiveScope) {
507 this.descriptiveScope = descriptiveScope;
509 public String getClosedLooppolicyType() {
510 return closedLooppolicyType;
512 public void setClosedLooppolicyType(String closedLooppolicyType) {
513 this.closedLooppolicyType = closedLooppolicyType;
515 public String getEcompName() {
518 public void setEcompName(String ecompName) {
519 this.ecompName = ecompName;
521 public String getD2Service() {
524 public void setD2Service(String d2Service) {
525 this.d2Service = d2Service;
527 public String getVnfType() {
530 public void setVnfType(String vnfType) {
531 this.vnfType = vnfType;
533 public String getPolicyStatus() {
536 public void setPolicyStatus(String policyStatus) {
537 this.policyStatus = policyStatus;
539 public String getVproAction() {
542 public void setVproAction(String vproAction) {
543 this.vproAction = vproAction;
545 public String getServiceType() {
548 public void setServiceType(String serviceType) {
549 this.serviceType = serviceType;
551 public String getBindTextSearch() {
552 return bindTextSearch;
554 public void setBindTextSearch(String bindTextSearch) {
555 this.bindTextSearch = bindTextSearch;