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 searchText = 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;
291 }else if(policyType.equalsIgnoreCase("closedloop")){
292 type = ElkConnector.PolicyIndexType.closedloop;
294 type = ElkConnector.PolicyIndexType.all;
297 type = ElkConnector.PolicyIndexType.all;
299 JestResult policyResultList = controller.search(type, searchText, searchKeyValue);
300 if(policyResultList.isSucceeded()){
303 JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray();
304 for(int i =0; i < resultObject.size(); i++){
305 String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString();
306 policyList.add(policyName);
309 LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs");
312 LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e);
317 message = "Elastic Server Transaction is success";
319 message = "Elastic Server Transaction is failed, please check the logs";
321 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(message));
322 JSONObject j = new JSONObject(msg);
323 response.setStatus(HttpServletResponse.SC_OK);
324 response.addHeader("success", "success");
326 JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
327 response.getWriter().write(k.toString());
329 response.getWriter().write(j.toString());
332 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
333 response.addHeader("error", "Exception Occured While Performing Elastic Transaction");
334 LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage(),e);
338 @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
339 public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException {
341 PolicyIndexType config = PolicyIndexType.config;
342 PolicyIndexType closedloop = PolicyIndexType.closedloop;
343 PolicyIndexType action = PolicyIndexType.action;
344 PolicyIndexType decision = PolicyIndexType.decision;
345 PolicyIndexType all = PolicyIndexType.all;
347 ObjectMapper mapper = new ObjectMapper();
348 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
349 JsonNode root = mapper.readTree(request.getReader());
350 String dictionaryType = root.get("type").textValue();
351 Mode mode = Mode.valueOf(dictionaryType);
353 List<String> policyList = new ArrayList<>();
356 Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class);
357 value = attributedata.getXacmlId();
358 policyList = searchElkDatabase(all, "pholder",value);
361 OnapName onapName = (OnapName)mapper.readValue(root.get("data").toString(), OnapName.class);
362 value = onapName.getOnapName();
363 policyList = searchElkDatabase(all, "onapName",value);
366 ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class);
367 value = actionPolicyDict.getAttributeName();
368 policyList = searchElkDatabase(action, "actionAttributeValue",value);
371 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class);
372 value = bRMSParamTemplate.getRuleName();
373 policyList = searchElkDatabase(config, "ruleName",value);
376 PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class);
377 value = pEPOptions.getPepName();
378 policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value);
381 ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class);
382 value = closedLoopSite.getSiteName();
383 policyList = searchElkDatabase(closedloop,"siteNames",value);
386 ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class);
387 value = closedLoopD2Services.getServiceName();
388 policyList = searchElkDatabase(closedloop, "pholder",value);
391 VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class);
392 value = varbindDictionary.getVarbindName();
393 policyList = searchElkDatabase(closedloop, "jsonBodyData","*"+value+"*");
396 VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class);
397 value = vNFType.getVnftype();
398 policyList = searchElkDatabase(closedloop, "jsonBodyData","*"+value+"*");
401 VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class);
402 value = vsclAction.getVsclaction();
403 policyList = searchElkDatabase(closedloop, "jsonBodyData","*"+value+"*");
406 DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class);
407 value = decisionSettings.getXacmlId();
408 policyList = searchElkDatabase(decision,"pholder",value);
411 TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class);
412 value = term.getTermName();
413 policyList = searchElkDatabase(config, "pholder",value);
416 DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class);
417 value = dcaeUUID.getName();
418 policyList = searchElkDatabase(config, "uuid",value);
421 MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class);
422 value = mslocation.getName();
423 policyList = searchElkDatabase(config, "location",value);
426 MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class);
427 value = msModels.getModelName();
428 policyList = searchElkDatabase(config, "serviceType",value);
431 GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class);
432 value = groupPoilicy.getGroupName();
433 policyList = searchElkDatabase(config, "pholder",value);
436 RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class);
437 value = riskType.getRiskName();
438 policyList = searchElkDatabase(config, "riskType",value);
440 case safePolicyWarning :
441 SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class);
442 value = safePolicy.getName();
443 policyList = searchElkDatabase(config, "pholder",value);
448 response.setStatus(HttpServletResponse.SC_OK);
449 response.addHeader("success", "success");
450 JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
451 response.getWriter().write(k.toString());
453 response.setCharacterEncoding("UTF-8");
454 request.setCharacterEncoding("UTF-8");
455 PrintWriter out = response.getWriter();
456 out.write(e.getMessage());
462 //Search the Elk database
463 public List<String> searchElkDatabase(PolicyIndexType type, String key, String value){
464 PolicyElasticSearchController controller = new PolicyElasticSearchController();
465 Map<String, String> searchKeyValue = new HashMap<>();
466 if(!"pholder".equals(key)){
467 searchKeyValue.put(key, value);
470 List<String> policyList = new ArrayList<>();
471 JestResult policyResultList = controller.search(type, value, searchKeyValue);
472 if(policyResultList.isSucceeded()){
473 JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray();
474 for(int i =0; i < resultObject.size(); i++){
475 String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString();
476 policyList.add(policyName);
479 LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs");
484 public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) {
485 return ElkConnector.singleton.search(type, text, searchKeyValue);
491 private String query;
492 private String policyType;
493 private String descriptiveScope;
494 private String closedLooppolicyType;
495 private String onapName;
496 private String d2Service;
497 private String vnfType;
498 private String policyStatus;
499 private String vproAction;
500 private String serviceType;
501 private String bindTextSearch;
502 public String getQuery() {
505 public void setQuery(String query) {
508 public String getPolicyType() {
511 public void setPolicyType(String policyType) {
512 this.policyType = policyType;
514 public String getDescriptiveScope() {
515 return descriptiveScope;
517 public void setDescriptiveScope(String descriptiveScope) {
518 this.descriptiveScope = descriptiveScope;
520 public String getClosedLooppolicyType() {
521 return closedLooppolicyType;
523 public void setClosedLooppolicyType(String closedLooppolicyType) {
524 this.closedLooppolicyType = closedLooppolicyType;
526 public String getOnapName() {
529 public void setOnapName(String onapName) {
530 this.onapName = onapName;
532 public String getD2Service() {
535 public void setD2Service(String d2Service) {
536 this.d2Service = d2Service;
538 public String getVnfType() {
541 public void setVnfType(String vnfType) {
542 this.vnfType = vnfType;
544 public String getPolicyStatus() {
547 public void setPolicyStatus(String policyStatus) {
548 this.policyStatus = policyStatus;
550 public String getVproAction() {
553 public void setVproAction(String vproAction) {
554 this.vproAction = vproAction;
556 public String getServiceType() {
559 public void setServiceType(String serviceType) {
560 this.serviceType = serviceType;
562 public String getBindTextSearch() {
563 return bindTextSearch;
565 public void setBindTextSearch(String bindTextSearch) {
566 this.bindTextSearch = bindTextSearch;