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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger;
43 import org.onap.policy.common.logging.flexlogger.Logger;
44 import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType;
45 import org.onap.policy.pap.xacml.rest.util.JsonMessage;
46 import org.onap.policy.rest.adapter.PolicyRestAdapter;
47 import org.onap.policy.rest.dao.CommonClassDao;
48 import org.onap.policy.rest.jpa.ActionPolicyDict;
49 import org.onap.policy.rest.jpa.Attribute;
50 import org.onap.policy.rest.jpa.BRMSParamTemplate;
51 import org.onap.policy.rest.jpa.ClosedLoopD2Services;
52 import org.onap.policy.rest.jpa.ClosedLoopSite;
53 import org.onap.policy.rest.jpa.DCAEuuid;
54 import org.onap.policy.rest.jpa.DecisionSettings;
55 import org.onap.policy.rest.jpa.DescriptiveScope;
56 import org.onap.policy.rest.jpa.OnapName;
57 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
58 import org.onap.policy.rest.jpa.MicroServiceLocation;
59 import org.onap.policy.rest.jpa.MicroServiceModels;
60 import org.onap.policy.rest.jpa.PEPOptions;
61 import org.onap.policy.rest.jpa.RiskType;
62 import org.onap.policy.rest.jpa.SafePolicyWarning;
63 import org.onap.policy.rest.jpa.TermList;
64 import org.onap.policy.rest.jpa.VNFType;
65 import org.onap.policy.rest.jpa.VSCLAction;
66 import org.onap.policy.rest.jpa.VarbindDictionary;
67 import org.onap.policy.xacml.api.XACMLErrorConstants;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.stereotype.Controller;
70 import org.springframework.web.bind.annotation.RequestMapping;
71 import org.springframework.web.bind.annotation.RequestMethod;
72 import org.springframework.web.servlet.ModelAndView;
74 import com.fasterxml.jackson.databind.DeserializationFeature;
75 import com.fasterxml.jackson.databind.JsonNode;
76 import com.fasterxml.jackson.databind.ObjectMapper;
77 import com.google.gson.JsonArray;
79 import io.searchbox.client.JestResult;
82 @RequestMapping({"/"})
83 public class PolicyElasticSearchController{
85 private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class);
88 attribute, onapName, actionPolicy, brmsParam, pepOptions,
89 clSite, clService, clVarbind, clVnf, clVSCL, decision,
90 fwTerm, msDCAEUUID, msConfigName, msLocation, msModels,
91 psGroupPolicy, safeRisk, safePolicyWarning
94 public static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() {
95 private static final long serialVersionUID = 1L;
98 public static CommonClassDao commonClassDao;
101 public PolicyElasticSearchController(CommonClassDao commonClassDao) {
102 PolicyElasticSearchController.commonClassDao = commonClassDao;
105 public PolicyElasticSearchController() {}
107 public static void TurnOffCertsCheck() {
108 // Create a trust manager that does not validate certificate chains
109 TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
110 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
113 public void checkClientTrusted(X509Certificate[] certs,
116 public void checkServerTrusted(X509Certificate[] certs,
121 // Install all-trusting trust manager
124 ctx = SSLContext.getInstance("SSL");
125 ctx.init(null, trustAllCerts, new java.security.SecureRandom());
126 HttpsURLConnection.setDefaultSSLSocketFactory(ctx
127 .getSocketFactory());
128 } catch (NoSuchAlgorithmException | KeyManagementException e) {
129 LOGGER.error("SSL Security Error: " + e);
132 // Create all-trusting host name verifier
133 HostnameVerifier allHostsValid = new HostnameVerifier() {
134 public boolean verify(String hostname, SSLSession session) {
139 // Install the all-trusting host verifier
140 HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
146 public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException {
147 if (type == null || type.isEmpty()){
148 return PolicyIndexType.all;
150 return PolicyIndexType.valueOf(type);
153 public boolean updateElk(PolicyRestAdapter policyData) {
154 boolean success = true;
156 success = ElkConnector.singleton.update(policyData);
158 if (LOGGER.isWarnEnabled()) {
159 LOGGER.warn("FAILURE to create ELK record created for " + policyData.getNewFileName());
162 if (LOGGER.isInfoEnabled()) {
163 LOGGER.warn("SUCCESS creating ELK record created for " + policyData.getNewFileName());
166 } catch (Exception e) {
167 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
173 public boolean deleteElk(PolicyRestAdapter policyData) {
174 boolean success = true;
176 success = ElkConnector.singleton.delete(policyData);
178 if (LOGGER.isWarnEnabled()) {
179 LOGGER.warn("FAILURE to delete ELK record created for " + policyData.getNewFileName());
182 if (LOGGER.isInfoEnabled()) {
183 LOGGER.warn("SUCCESS deleting ELK record created for " + policyData.getNewFileName());
186 } catch (Exception e) {
187 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
194 @RequestMapping(value="/searchPolicy", method= RequestMethod.POST)
195 public void searchPolicy(HttpServletRequest request, HttpServletResponse response) {
197 boolean result = false;
198 boolean policyResult = false;
199 ObjectMapper mapper = new ObjectMapper();
200 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
201 PolicyRestAdapter policyData = new PolicyRestAdapter();
202 PolicyElasticSearchController controller = new PolicyElasticSearchController();
203 Map<String, String> searchKeyValue = new HashMap<>();
204 List<String> policyList = new ArrayList<>();
205 if(request.getParameter("policyName") != null){
206 String policyName = request.getParameter("policyName");
207 policyData.setNewFileName(policyName);
208 if("delete".equalsIgnoreCase(request.getParameter("action"))){
209 result = controller.deleteElk(policyData);
211 result = controller.updateElk(policyData);
214 if("search".equalsIgnoreCase(request.getParameter("action"))){
216 JsonNode root = mapper.readTree(request.getReader());
217 SearchData searchData = (SearchData)mapper.readValue(root.get("searchdata").toString(), SearchData.class);
219 String policyType = searchData.getPolicyType();
221 String searchText = searchData.getQuery();
222 String descriptivevalue = searchData.getDescriptiveScope();
223 if(descriptivevalue != null){
224 DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", descriptivevalue);
225 if(dsSearch != null){
226 String[] descriptiveList = dsSearch.getSearch().split("AND");
227 for(String keyValue : descriptiveList){
228 String[] entry = keyValue.split(":");
229 if(searchData.getPolicyType() != null && "closedLoop".equals(searchData.getPolicyType())){
230 searchKeyValue.put("jsonBodyData", "*" +entry[1] +"*");
232 searchKeyValue.put(entry[0], entry[1]);
238 if(searchData.getClosedLooppolicyType() != null){
239 String closedLoopType;
240 if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){
241 closedLoopType = "ClosedLoop_Fault";
243 closedLoopType = "ClosedLoop_PM";
245 searchKeyValue.put("configPolicyType", closedLoopType);
247 if(searchData.getOnapName() != null){
248 searchKeyValue.put("onapName", searchData.getOnapName());
250 if(searchData.getD2Service() != null){
251 String d2Service = searchData.getD2Service().trim();
252 if(d2Service.equalsIgnoreCase("Hosted Voice (Trinity)")){
253 d2Service = "trinity";
254 }else if(d2Service.equalsIgnoreCase("vUSP")){
256 }else if(d2Service.equalsIgnoreCase("MCR")){
258 }else if(d2Service.equalsIgnoreCase("Gamma")){
260 }else if(d2Service.equalsIgnoreCase("vDNS")){
263 searchKeyValue.put("jsonBodyData."+d2Service+"", "true");
265 if(searchData.getVnfType() != null){
266 searchKeyValue.put("jsonBodyData", "*" +searchData.getVnfType() +"*");
268 if(searchData.getPolicyStatus() != null){
269 searchKeyValue.put("jsonBodyData", "*" +searchData.getPolicyStatus()+"*");
271 if(searchData.getVproAction() != null){
272 searchKeyValue.put("jsonBodyData", "*" +searchData.getVproAction()+"*");
274 if(searchData.getServiceType() != null){
275 searchKeyValue.put("serviceType", searchData.getServiceType());
277 if(searchData.getBindTextSearch() != null){
278 searchKeyValue.put(searchData.getBindTextSearch(), searchText);
281 PolicyIndexType type = null;
282 if(policyType != null){
283 if(policyType.equalsIgnoreCase("action")){
284 type = ElkConnector.PolicyIndexType.action;
285 }else if(policyType.equalsIgnoreCase("decision")){
286 type = ElkConnector.PolicyIndexType.decision;
287 }else if(policyType.equalsIgnoreCase("config")){
288 type = ElkConnector.PolicyIndexType.config;
290 type = ElkConnector.PolicyIndexType.closedloop;
293 type = ElkConnector.PolicyIndexType.all;
295 JestResult policyResultList = controller.search(type, searchText, searchKeyValue);
296 if(policyResultList.isSucceeded()){
299 JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray();
300 for(int i =0; i < resultObject.size(); i++){
301 String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString();
302 policyList.add(policyName);
305 LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs");
308 LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e);
313 message = "Elastic Server Transaction is success";
315 message = "Elastic Server Transaction is failed, please check the logs";
317 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(message));
318 JSONObject j = new JSONObject(msg);
319 response.setStatus(HttpServletResponse.SC_OK);
320 response.addHeader("success", "success");
322 JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
323 response.getWriter().write(k.toString());
325 response.getWriter().write(j.toString());
328 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
329 response.addHeader("error", "Exception Occured While Performing Elastic Transaction");
330 LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage());
334 @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
335 public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
337 PolicyIndexType config = PolicyIndexType.config;
338 PolicyIndexType closedloop = PolicyIndexType.closedloop;
339 PolicyIndexType action = PolicyIndexType.action;
340 PolicyIndexType decision = PolicyIndexType.decision;
341 PolicyIndexType all = PolicyIndexType.all;
343 ObjectMapper mapper = new ObjectMapper();
344 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
345 JsonNode root = mapper.readTree(request.getReader());
346 String dictionaryType = root.get("type").textValue();
347 Mode mode = Mode.valueOf(dictionaryType);
349 List<String> policyList = new ArrayList<>();
352 Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class);
353 value = attributedata.getXacmlId();
354 policyList = searchElkDatabase(all, "pholder",value);
357 OnapName onapName = (OnapName)mapper.readValue(root.get("data").toString(), OnapName.class);
358 value = onapName.getOnapName();
359 policyList = searchElkDatabase(all, "onapName",value);
362 ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class);
363 value = actionPolicyDict.getAttributeName();
364 policyList = searchElkDatabase(action, "actionAttributeValue",value);
367 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class);
368 value = bRMSParamTemplate.getRuleName();
369 policyList = searchElkDatabase(config, "ruleName",value);
372 PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class);
373 value = pEPOptions.getPepName();
374 policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value);
377 ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class);
378 value = closedLoopSite.getSiteName();
379 policyList = searchElkDatabase(closedloop,"siteNames",value);
382 ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class);
383 value = closedLoopD2Services.getServiceName();
384 policyList = searchElkDatabase(closedloop, "pholder",value);
387 VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class);
388 value = varbindDictionary.getVarbindName();
389 policyList = searchElkDatabase(closedloop, "jsonBodyData.triggerSignaturesUsedForUI.signatures",value);
392 VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class);
393 value = vNFType.getVnftype();
394 policyList = searchElkDatabase(closedloop, "jsonBodyData.vnfType",value);
397 VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class);
398 value = vsclAction.getVsclaction();
399 policyList = searchElkDatabase(closedloop, "jsonBodyData.actions",value);
402 DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class);
403 value = decisionSettings.getXacmlId();
404 policyList = searchElkDatabase(decision,"pholder",value);
407 TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class);
408 value = term.getTermName();
409 policyList = searchElkDatabase(config, "pholder",value);
412 DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class);
413 value = dcaeUUID.getName();
414 policyList = searchElkDatabase(config, "uuid",value);
417 MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class);
418 value = mslocation.getName();
419 policyList = searchElkDatabase(config, "location",value);
422 MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class);
423 value = msModels.getModelName();
424 policyList = searchElkDatabase(config, "serviceType",value);
427 GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class);
428 value = groupPoilicy.getGroupName();
429 policyList = searchElkDatabase(config, "pholder",value);
432 RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class);
433 value = riskType.getRiskName();
434 policyList = searchElkDatabase(config, "riskType",value);
436 case safePolicyWarning :
437 SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class);
438 value = safePolicy.getName();
439 policyList = searchElkDatabase(config, "pholder",value);
444 response.setStatus(HttpServletResponse.SC_OK);
445 response.addHeader("success", "success");
446 JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
447 response.getWriter().write(k.toString());
449 response.setCharacterEncoding("UTF-8");
450 request.setCharacterEncoding("UTF-8");
451 PrintWriter out = response.getWriter();
452 out.write(e.getMessage());
457 //Search the Elk database
458 public List<String> searchElkDatabase(PolicyIndexType type, String key, String value){
459 PolicyElasticSearchController controller = new PolicyElasticSearchController();
460 Map<String, String> searchKeyValue = new HashMap<>();
461 if(!"pholder".equals(key)){
462 searchKeyValue.put(key, value);
465 List<String> policyList = new ArrayList<>();
466 JestResult policyResultList = controller.search(type, value, searchKeyValue);
467 if(policyResultList.isSucceeded()){
468 JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray();
469 for(int i =0; i < resultObject.size(); i++){
470 String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString();
471 policyList.add(policyName);
474 LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs");
479 public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) {
480 return ElkConnector.singleton.search(type, text, searchKeyValue);
486 private String query;
487 private String policyType;
488 private String descriptiveScope;
489 private String closedLooppolicyType;
490 private String onapName;
491 private String d2Service;
492 private String vnfType;
493 private String policyStatus;
494 private String vproAction;
495 private String serviceType;
496 private String bindTextSearch;
497 public String getQuery() {
500 public void setQuery(String query) {
503 public String getPolicyType() {
506 public void setPolicyType(String policyType) {
507 this.policyType = policyType;
509 public String getDescriptiveScope() {
510 return descriptiveScope;
512 public void setDescriptiveScope(String descriptiveScope) {
513 this.descriptiveScope = descriptiveScope;
515 public String getClosedLooppolicyType() {
516 return closedLooppolicyType;
518 public void setClosedLooppolicyType(String closedLooppolicyType) {
519 this.closedLooppolicyType = closedLooppolicyType;
521 public String getOnapName() {
524 public void setOnapName(String onapName) {
525 this.onapName = onapName;
527 public String getD2Service() {
530 public void setD2Service(String d2Service) {
531 this.d2Service = d2Service;
533 public String getVnfType() {
536 public void setVnfType(String vnfType) {
537 this.vnfType = vnfType;
539 public String getPolicyStatus() {
542 public void setPolicyStatus(String policyStatus) {
543 this.policyStatus = policyStatus;
545 public String getVproAction() {
548 public void setVproAction(String vproAction) {
549 this.vproAction = vproAction;
551 public String getServiceType() {
554 public void setServiceType(String serviceType) {
555 this.serviceType = serviceType;
557 public String getBindTextSearch() {
558 return bindTextSearch;
560 public void setBindTextSearch(String bindTextSearch) {
561 this.bindTextSearch = bindTextSearch;