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.IOException;
 
  24 import java.io.PrintWriter;
 
  25 import java.io.UnsupportedEncodingException;
 
  26 import java.security.KeyManagementException;
 
  27 import java.security.NoSuchAlgorithmException;
 
  28 import java.security.cert.X509Certificate;
 
  29 import java.util.ArrayList;
 
  30 import java.util.HashMap;
 
  31 import java.util.List;
 
  34 import javax.net.ssl.HostnameVerifier;
 
  35 import javax.net.ssl.HttpsURLConnection;
 
  36 import javax.net.ssl.SSLContext;
 
  37 import javax.net.ssl.SSLSession;
 
  38 import javax.net.ssl.TrustManager;
 
  39 import javax.net.ssl.X509TrustManager;
 
  40 import javax.servlet.http.HttpServletRequest;
 
  41 import javax.servlet.http.HttpServletResponse;
 
  43 import org.json.JSONObject;
 
  44 import org.onap.policy.common.logging.flexlogger.FlexLogger;
 
  45 import org.onap.policy.common.logging.flexlogger.Logger;
 
  46 import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType;
 
  47 import org.onap.policy.pap.xacml.rest.util.JsonMessage;
 
  48 import org.onap.policy.rest.adapter.PolicyRestAdapter;
 
  49 import org.onap.policy.rest.dao.CommonClassDao;
 
  50 import org.onap.policy.rest.jpa.ActionPolicyDict;
 
  51 import org.onap.policy.rest.jpa.Attribute;
 
  52 import org.onap.policy.rest.jpa.BRMSParamTemplate;
 
  53 import org.onap.policy.rest.jpa.ClosedLoopD2Services;
 
  54 import org.onap.policy.rest.jpa.ClosedLoopSite;
 
  55 import org.onap.policy.rest.jpa.DCAEuuid;
 
  56 import org.onap.policy.rest.jpa.DecisionSettings;
 
  57 import org.onap.policy.rest.jpa.DescriptiveScope;
 
  58 import org.onap.policy.rest.jpa.OnapName;
 
  59 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
 
  60 import org.onap.policy.rest.jpa.MicroServiceLocation;
 
  61 import org.onap.policy.rest.jpa.MicroServiceModels;
 
  62 import org.onap.policy.rest.jpa.PEPOptions;
 
  63 import org.onap.policy.rest.jpa.RiskType;
 
  64 import org.onap.policy.rest.jpa.SafePolicyWarning;
 
  65 import org.onap.policy.rest.jpa.TermList;
 
  66 import org.onap.policy.rest.jpa.VNFType;
 
  67 import org.onap.policy.rest.jpa.VSCLAction;
 
  68 import org.onap.policy.rest.jpa.VarbindDictionary;
 
  69 import org.onap.policy.xacml.api.XACMLErrorConstants;
 
  70 import org.springframework.beans.factory.annotation.Autowired;
 
  71 import org.springframework.stereotype.Controller;
 
  72 import org.springframework.web.bind.annotation.RequestMapping;
 
  73 import org.springframework.web.bind.annotation.RequestMethod;
 
  74 import org.springframework.web.servlet.ModelAndView;
 
  76 import com.fasterxml.jackson.databind.DeserializationFeature;
 
  77 import com.fasterxml.jackson.databind.JsonNode;
 
  78 import com.fasterxml.jackson.databind.ObjectMapper;
 
  79 import com.google.gson.JsonArray;
 
  81 import io.searchbox.client.JestResult;
 
  84 @RequestMapping({"/"})
 
  85 public class PolicyElasticSearchController{
 
  87         private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class);
 
  90                 attribute, onapName, actionPolicy, brmsParam, pepOptions,
 
  91                 clSite, clService, clVarbind, clVnf, clVSCL, decision, 
 
  92                 fwTerm, msDCAEUUID, msConfigName, msLocation, msModels,
 
  93                 psGroupPolicy, safeRisk, safePolicyWarning
 
  96         protected static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() {
 
  97                 private static final long serialVersionUID = 1L;
 
 100         private static CommonClassDao commonClassDao;
 
 103         public PolicyElasticSearchController(CommonClassDao commonClassDao) {
 
 104                 PolicyElasticSearchController.commonClassDao = commonClassDao;
 
 107         public PolicyElasticSearchController() {}
 
 109         public static void TurnOffCertsCheck() {
 
 110                 // Create a trust manager that does not validate certificate chains
 
 111                 TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
 
 112                         public java.security.cert.X509Certificate[] getAcceptedIssuers() {
 
 115                         public void checkClientTrusted(X509Certificate[] certs,
 
 118                         public void checkServerTrusted(X509Certificate[] certs,
 
 123                 // Install all-trusting trust manager
 
 126                         ctx = SSLContext.getInstance("SSL");
 
 127                         ctx.init(null, trustAllCerts, new java.security.SecureRandom());
 
 128                         HttpsURLConnection.setDefaultSSLSocketFactory(ctx
 
 129                                         .getSocketFactory());
 
 130                 } catch (NoSuchAlgorithmException | KeyManagementException e) {
 
 131                         LOGGER.error("SSL Security Error: " + e);
 
 134                 // Create all-trusting host name verifier
 
 135                 HostnameVerifier allHostsValid = new HostnameVerifier() {
 
 136                         public boolean verify(String hostname, SSLSession session) {
 
 141                 // Install the all-trusting host verifier
 
 142                 HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
 
 148         public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException {
 
 149                 if (type == null || type.isEmpty()){
 
 150                         return PolicyIndexType.all;
 
 152                 return PolicyIndexType.valueOf(type);
 
 155         public boolean updateElk(PolicyRestAdapter policyData) {
 
 156                 boolean success = true;
 
 158                         success = ElkConnector.singleton.update(policyData);
 
 160                                 if (LOGGER.isWarnEnabled()) {
 
 161                                         LOGGER.warn("FAILURE to create ELK record created for " + policyData.getNewFileName());
 
 164                                 if (LOGGER.isInfoEnabled()) {
 
 165                                         LOGGER.warn("SUCCESS creating ELK record created for " + policyData.getNewFileName());
 
 168                 } catch (Exception e) {
 
 169                         LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
 
 175         public boolean deleteElk(PolicyRestAdapter policyData) {
 
 176                 boolean success = true;
 
 178                         success = ElkConnector.singleton.delete(policyData);
 
 180                                 if (LOGGER.isWarnEnabled()) {
 
 181                                         LOGGER.warn("FAILURE to delete ELK record created for " + policyData.getNewFileName());
 
 184                                 if (LOGGER.isInfoEnabled()) {
 
 185                                         LOGGER.warn("SUCCESS deleting ELK record created for " + policyData.getNewFileName());
 
 188                 } catch (Exception e) {
 
 189                         LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
 
 196         @RequestMapping(value="/searchPolicy", method= RequestMethod.POST)
 
 197         public void searchPolicy(HttpServletRequest request, HttpServletResponse response) {
 
 199                         boolean result = false;
 
 200                         boolean policyResult = false;
 
 201                         ObjectMapper mapper = new ObjectMapper();
 
 202                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
 203                         PolicyRestAdapter policyData = new PolicyRestAdapter();
 
 204                         PolicyElasticSearchController controller = new PolicyElasticSearchController();
 
 205                         Map<String, String> searchKeyValue = new HashMap<>();
 
 206                         List<String> policyList = new ArrayList<>();
 
 207                         if(request.getParameter("policyName") != null){
 
 208                                 String policyName = request.getParameter("policyName");
 
 209                                 policyData.setNewFileName(policyName);
 
 210                                 if("delete".equalsIgnoreCase(request.getParameter("action"))){
 
 211                                         result = controller.deleteElk(policyData);
 
 213                                         result = controller.updateElk(policyData);
 
 216                         if("search".equalsIgnoreCase(request.getParameter("action"))){
 
 218                                         JsonNode root = mapper.readTree(request.getReader());
 
 219                                         SearchData searchData = (SearchData)mapper.readValue(root.get("searchdata").toString(), SearchData.class);
 
 221                                         String policyType = searchData.getPolicyType();
 
 223                                         String searchText = searchData.getQuery();
 
 224                                         String descriptivevalue = searchData.getDescriptiveScope();
 
 225                                         if(descriptivevalue != null){
 
 226                                                 DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", descriptivevalue);
 
 227                                                 if(dsSearch != null){
 
 228                                                         String[] descriptiveList =  dsSearch.getSearch().split("AND");
 
 229                                                         for(String keyValue : descriptiveList){
 
 230                                                                 String[] entry = keyValue.split(":");
 
 231                                                                 if(searchData.getPolicyType() != null && "closedLoop".equals(searchData.getPolicyType())){
 
 232                                                                         searchKeyValue.put("jsonBodyData", "*" +entry[1] +"*");
 
 234                                                                         searchKeyValue.put(entry[0], entry[1]);
 
 240                                         if(searchData.getClosedLooppolicyType() != null){
 
 241                                                 String closedLoopType;
 
 242                                                 if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){
 
 243                                                         closedLoopType  = "ClosedLoop_Fault";
 
 245                                                         closedLoopType  = "ClosedLoop_PM";
 
 247                                                 searchKeyValue.put("configPolicyType", closedLoopType);
 
 249                                         if(searchData.getOnapName() != null){
 
 250                                                 searchKeyValue.put("onapName", searchData.getOnapName());
 
 252                                         if(searchData.getD2Service() != null){
 
 253                                                 String d2Service = searchData.getD2Service().trim();
 
 254                                                 if(d2Service.equalsIgnoreCase("Hosted Voice (Trinity)")){
 
 255                                                         d2Service = "trinity";
 
 256                                                 }else if(d2Service.equalsIgnoreCase("vUSP")){
 
 258                                                 }else if(d2Service.equalsIgnoreCase("MCR")){
 
 260                                                 }else if(d2Service.equalsIgnoreCase("Gamma")){
 
 262                                                 }else if(d2Service.equalsIgnoreCase("vDNS")){
 
 265                                                 searchKeyValue.put("jsonBodyData."+d2Service+"", "true");
 
 267                                         if(searchData.getVnfType() != null){
 
 268                                                 searchKeyValue.put("jsonBodyData", "*" +searchData.getVnfType() +"*");                                  
 
 270                                         if(searchData.getPolicyStatus() != null){
 
 271                                                 searchKeyValue.put("jsonBodyData", "*" +searchData.getPolicyStatus()+"*");
 
 273                                         if(searchData.getVproAction() != null){
 
 274                                                 searchKeyValue.put("jsonBodyData", "*" +searchData.getVproAction()+"*");
 
 276                                         if(searchData.getServiceType() != null){
 
 277                                                 searchKeyValue.put("serviceType", searchData.getServiceType());
 
 279                                         if(searchData.getBindTextSearch() != null){
 
 280                                                 searchKeyValue.put(searchData.getBindTextSearch(), searchText);
 
 283                                         PolicyIndexType type = null;
 
 284                                         if(policyType != null){
 
 285                                                 if(policyType.equalsIgnoreCase("action")){
 
 286                                                         type = ElkConnector.PolicyIndexType.action;
 
 287                                                 }else if(policyType.equalsIgnoreCase("decision")){
 
 288                                                         type = ElkConnector.PolicyIndexType.decision;
 
 289                                                 }else if(policyType.equalsIgnoreCase("config")){
 
 290                                                         type = ElkConnector.PolicyIndexType.config;
 
 292                                                         type = ElkConnector.PolicyIndexType.closedloop;
 
 295                                                 type = ElkConnector.PolicyIndexType.all;
 
 297                                         JestResult policyResultList = controller.search(type, searchText, searchKeyValue);
 
 298                                         if(policyResultList.isSucceeded()){
 
 301                                                 JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray();
 
 302                                                 for(int i =0; i < resultObject.size(); i++){
 
 303                                                         String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString();
 
 304                                                         policyList.add(policyName);
 
 307                                                 LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs");
 
 310                                         LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e);
 
 315                                 message = "Elastic Server Transaction is success";
 
 317                                 message = "Elastic Server Transaction is failed, please check the logs";
 
 319                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(message));
 
 320                         JSONObject j = new JSONObject(msg);
 
 321                         response.setStatus(HttpServletResponse.SC_OK);
 
 322                         response.addHeader("success", "success"); 
 
 324                                 JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
 
 325                                 response.getWriter().write(k.toString());
 
 327                                 response.getWriter().write(j.toString());
 
 330                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
 
 331                         response.addHeader("error", "Exception Occured While Performing Elastic Transaction");
 
 332                         LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage(),e);
 
 336         @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
 
 337         public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException {
 
 339                         PolicyIndexType config = PolicyIndexType.config;
 
 340                         PolicyIndexType closedloop = PolicyIndexType.closedloop;
 
 341                         PolicyIndexType action = PolicyIndexType.action;
 
 342                         PolicyIndexType decision = PolicyIndexType.decision;
 
 343                         PolicyIndexType all = PolicyIndexType.all;
 
 345                         ObjectMapper mapper = new ObjectMapper();
 
 346                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
 347                         JsonNode root = mapper.readTree(request.getReader());
 
 348                         String dictionaryType = root.get("type").textValue();
 
 349                         Mode mode = Mode.valueOf(dictionaryType);
 
 351                         List<String> policyList = new ArrayList<>();
 
 354                                 Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class);
 
 355                                 value = attributedata.getXacmlId();
 
 356                                 policyList = searchElkDatabase(all, "pholder",value);
 
 359                                 OnapName onapName = (OnapName)mapper.readValue(root.get("data").toString(), OnapName.class);
 
 360                                 value = onapName.getOnapName();
 
 361                                 policyList = searchElkDatabase(all, "onapName",value);
 
 364                                 ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class);
 
 365                                 value = actionPolicyDict.getAttributeName();
 
 366                                 policyList = searchElkDatabase(action, "actionAttributeValue",value);
 
 369                                 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class);
 
 370                                 value = bRMSParamTemplate.getRuleName();
 
 371                                 policyList = searchElkDatabase(config, "ruleName",value);
 
 374                                 PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class);
 
 375                                 value = pEPOptions.getPepName();
 
 376                                 policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value);
 
 379                                 ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class);
 
 380                                 value = closedLoopSite.getSiteName();
 
 381                                 policyList = searchElkDatabase(closedloop,"siteNames",value);
 
 384                                 ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class);
 
 385                                 value = closedLoopD2Services.getServiceName();
 
 386                                 policyList = searchElkDatabase(closedloop, "pholder",value);
 
 389                                 VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class);
 
 390                                 value = varbindDictionary.getVarbindName();
 
 391                                 policyList = searchElkDatabase(closedloop, "jsonBodyData","*"+value+"*");
 
 394                                 VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class);
 
 395                                 value = vNFType.getVnftype();
 
 396                                 policyList = searchElkDatabase(closedloop, "jsonBodyData","*"+value+"*");
 
 399                                 VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class);
 
 400                                 value = vsclAction.getVsclaction();
 
 401                                 policyList = searchElkDatabase(closedloop, "jsonBodyData","*"+value+"*");
 
 404                                 DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class);
 
 405                                 value = decisionSettings.getXacmlId();
 
 406                                 policyList = searchElkDatabase(decision,"pholder",value);
 
 409                                 TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class);
 
 410                                 value = term.getTermName();
 
 411                                 policyList = searchElkDatabase(config, "pholder",value);
 
 414                                 DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class);
 
 415                                 value = dcaeUUID.getName();
 
 416                                 policyList = searchElkDatabase(config, "uuid",value);
 
 419                                 MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class);
 
 420                                 value = mslocation.getName();
 
 421                                 policyList = searchElkDatabase(config, "location",value);
 
 424                                 MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class);
 
 425                                 value = msModels.getModelName();
 
 426                                 policyList = searchElkDatabase(config, "serviceType",value);
 
 429                                 GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class);
 
 430                                 value = groupPoilicy.getGroupName();
 
 431                                 policyList = searchElkDatabase(config, "pholder",value);
 
 434                                 RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class);
 
 435                                 value = riskType.getRiskName();
 
 436                                 policyList = searchElkDatabase(config, "riskType",value);
 
 438                         case safePolicyWarning :
 
 439                                 SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class);
 
 440                                 value = safePolicy.getName();
 
 441                                 policyList = searchElkDatabase(config, "pholder",value);
 
 446                         response.setStatus(HttpServletResponse.SC_OK);
 
 447                         response.addHeader("success", "success"); 
 
 448                         JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
 
 449                         response.getWriter().write(k.toString());
 
 451                         response.setCharacterEncoding("UTF-8");
 
 452                         request.setCharacterEncoding("UTF-8");
 
 453                         PrintWriter out = response.getWriter();
 
 454                         out.write(e.getMessage());
 
 460         //Search the Elk database
 
 461         public List<String> searchElkDatabase(PolicyIndexType type, String key, String value){
 
 462                 PolicyElasticSearchController controller = new PolicyElasticSearchController();
 
 463                 Map<String, String> searchKeyValue = new HashMap<>();
 
 464                 if(!"pholder".equals(key)){
 
 465                         searchKeyValue.put(key, value);
 
 468                 List<String> policyList = new ArrayList<>();
 
 469                 JestResult policyResultList = controller.search(type, value, searchKeyValue);
 
 470                 if(policyResultList.isSucceeded()){
 
 471                         JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray();
 
 472                         for(int i =0; i < resultObject.size(); i++){
 
 473                                 String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString();
 
 474                                 policyList.add(policyName);
 
 477                         LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs");
 
 482         public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) {
 
 483                  return ElkConnector.singleton.search(type, text, searchKeyValue);
 
 489         private String query;
 
 490         private String policyType;
 
 491         private String descriptiveScope;
 
 492         private String closedLooppolicyType;
 
 493         private String onapName;
 
 494         private String d2Service;
 
 495         private String vnfType;
 
 496         private String policyStatus;
 
 497         private String vproAction;
 
 498         private String serviceType;
 
 499         private String bindTextSearch;
 
 500         public String getQuery() {
 
 503         public void setQuery(String query) {
 
 506         public String getPolicyType() {
 
 509         public void setPolicyType(String policyType) {
 
 510                 this.policyType = policyType;
 
 512         public String getDescriptiveScope() {
 
 513                 return descriptiveScope;
 
 515         public void setDescriptiveScope(String descriptiveScope) {
 
 516                 this.descriptiveScope = descriptiveScope;
 
 518         public String getClosedLooppolicyType() {
 
 519                 return closedLooppolicyType;
 
 521         public void setClosedLooppolicyType(String closedLooppolicyType) {
 
 522                 this.closedLooppolicyType = closedLooppolicyType;
 
 524         public String getOnapName() {
 
 527         public void setOnapName(String onapName) {
 
 528                 this.onapName = onapName;
 
 530         public String getD2Service() {
 
 533         public void setD2Service(String d2Service) {
 
 534                 this.d2Service = d2Service;
 
 536         public String getVnfType() {
 
 539         public void setVnfType(String vnfType) {
 
 540                 this.vnfType = vnfType;
 
 542         public String getPolicyStatus() {
 
 545         public void setPolicyStatus(String policyStatus) {
 
 546                 this.policyStatus = policyStatus;
 
 548         public String getVproAction() {
 
 551         public void setVproAction(String vproAction) {
 
 552                 this.vproAction = vproAction;
 
 554         public String getServiceType() {
 
 557         public void setServiceType(String serviceType) {
 
 558                 this.serviceType = serviceType;
 
 560         public String getBindTextSearch() {
 
 561                 return bindTextSearch;
 
 563         public void setBindTextSearch(String bindTextSearch) {
 
 564                 this.bindTextSearch = bindTextSearch;