Enhancement on Dashboard
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / DashboardController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2018 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
21 package org.onap.policy.controller;
22
23 import com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.api.pap.PDP;
25 import com.att.research.xacml.api.pap.PDPGroup;
26 import com.att.research.xacml.api.pap.PDPPolicy;
27 import com.att.research.xacml.util.XACMLProperties;
28 import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
29 import com.fasterxml.jackson.annotation.PropertyAccessor;
30 import com.fasterxml.jackson.databind.JsonNode;
31 import com.fasterxml.jackson.databind.ObjectMapper;
32 import java.io.IOException;
33 import java.io.PrintWriter;
34 import java.net.MalformedURLException;
35 import java.sql.Timestamp;
36 import java.time.LocalDate;
37 import java.util.ArrayList;
38 import java.util.HashMap;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Set;
42 import java.util.regex.Matcher;
43 import java.util.regex.Pattern;
44 import javax.management.AttributeNotFoundException;
45 import javax.management.InstanceNotFoundException;
46 import javax.management.MBeanException;
47 import javax.management.MalformedObjectNameException;
48 import javax.management.ObjectName;
49 import javax.management.ReflectionException;
50 import javax.management.remote.JMXConnector;
51 import javax.management.remote.JMXConnectorFactory;
52 import javax.management.remote.JMXServiceURL;
53 import javax.script.SimpleBindings;
54 import javax.servlet.http.HttpServletRequest;
55 import javax.servlet.http.HttpServletResponse;
56 import org.json.JSONObject;
57 import org.onap.policy.common.logging.flexlogger.FlexLogger;
58 import org.onap.policy.common.logging.flexlogger.Logger;
59 import org.onap.policy.dao.SystemLogDbDao;
60 import org.onap.policy.model.PDPGroupContainer;
61 import org.onap.policy.rest.XACMLRestProperties;
62 import org.onap.policy.rest.dao.CommonClassDao;
63 import org.onap.policy.rest.jpa.PolicyEntity;
64 import org.onap.policy.utils.PolicyUtils;
65 import org.onap.policy.xacml.api.XACMLErrorConstants;
66 import org.onap.policy.xacml.api.pap.OnapPDP;
67 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
68 import org.onap.portalsdk.core.controller.RestrictedBaseController;
69 import org.onap.portalsdk.core.web.support.JsonMessage;
70 import org.springframework.beans.factory.annotation.Autowired;
71 import org.springframework.http.MediaType;
72 import org.springframework.stereotype.Controller;
73 import org.springframework.web.bind.annotation.RequestMapping;
74
75 @Controller
76 @RequestMapping({"/"})
77 public class DashboardController extends RestrictedBaseController {
78     private static final Logger policyLogger = FlexLogger.getLogger(DashboardController.class);
79     @Autowired
80     CommonClassDao commonClassDao;
81
82     @Autowired
83     SystemLogDbDao systemDAO;
84
85     public void setCommonClassDao(CommonClassDao commonClassDao) {
86         this.commonClassDao = commonClassDao;
87     }
88
89     public void setSystemLogDbDao(SystemLogDbDao systemDAO) {
90         this.systemDAO = systemDAO;
91     }
92
93     private int pdpCount;
94     private PDPGroupContainer pdpConatiner;
95     private ArrayList<Object> pdpStatusData;
96     private ArrayList<Object> papStatusData;
97     private ArrayList<Object> policyStatusCrudData;
98     private ArrayList<Object> pdpStatusCrudData;
99     private ArrayList<Object> policyActivityData;
100     private PolicyController policyController;
101     private static String defaultTime = "0000-00-00";
102     private static String createDate = "createdDate";
103     private static String modifiedDate = "modifiedDate";
104     private static String scope = "scope";
105     private static String stage = "stage";
106     private static String exceptionOccured = "Exception Occured";
107
108     public PolicyController getPolicyController() {
109         return policyController;
110     }
111
112     public void setPolicyController(PolicyController policyController) {
113         this.policyController = policyController;
114     }
115
116     private PolicyController getPolicyControllerInstance() {
117         return policyController != null ? getPolicyController() : new PolicyController();
118     }
119
120
121
122     /**
123      * This method is to retrieve all the data of last 30 days from PolicyEntity table as default.
124      * 
125      * @param request object
126      * @param response object contains retrieved data
127      */
128     @RequestMapping(value = {"/get_DashboardPolicyCRUDData"},
129             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
130             produces = MediaType.APPLICATION_JSON_VALUE)
131     public void get_DashboardPolicyCrudData(HttpServletRequest request, HttpServletResponse response) {
132         try {
133             Map<String, Object> model = new HashMap<>();
134             ObjectMapper mapper = new ObjectMapper();
135             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
136             addPolicyCrudInfoToTable();
137             model.put("papStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData));
138             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
139             JSONObject j = new JSONObject(msg);
140             response.getWriter().write(j.toString());
141         } catch (Exception e) {
142             policyLogger.error(exceptionOccured, e);
143         }
144     }
145
146     /**
147      * This method retrieves data based on input criteria.
148      * 
149      * @param request object
150      * @param response object contains retrieved data
151      */
152     @RequestMapping(value = {"/dashboardController/dashboardAdvancedSearch.htm"},
153             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
154     public void dashboardAdvancedSearch(HttpServletRequest request, HttpServletResponse response) throws IOException {
155         String lscope = null;
156         String lstage = "both";
157         String isDelected = "both";
158         String ttlDateAfter = null;
159         String ttlDateBefore = null;
160         try {
161             ObjectMapper mapper = new ObjectMapper();
162             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
163             JsonNode root = mapper.readTree(request.getReader());
164             JsonNode inputData = root.get("policyData");
165             JsonNode jscope = inputData.path(scope);
166             if (jscope != null) {
167                 lscope = jscope.textValue();
168             }
169             JsonNode jstage = inputData.path(stage);
170             if (jstage != null) {
171                 lstage = jstage.textValue();
172             }
173             JsonNode jisDelected = inputData.path("isDelected");
174             if (jisDelected != null) {
175                 isDelected = jisDelected.textValue();
176             }
177             JsonNode jttlDateAfter = inputData.path("ttlDate_after");
178             if (jttlDateAfter != null) {
179                 ttlDateAfter = jttlDateAfter.textValue();
180             }
181             JsonNode jttlDateBefore = inputData.path("ttlDate_before");
182             if (jttlDateBefore != null) {
183                 ttlDateBefore = jttlDateBefore.textValue();
184             }
185             getPolicyData(lscope, lstage, isDelected, ttlDateAfter, ttlDateBefore);
186             Map<String, Object> model = new HashMap<>();
187             model.put("policyStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData));
188             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
189             JSONObject j = new JSONObject(msg);
190             response.getWriter().write(j.toString());
191         } catch (Exception e) {
192             response.setCharacterEncoding("UTF-8");
193             PrintWriter out = response.getWriter();
194             out.write(PolicyUtils.CATCH_EXCEPTION);
195         }
196
197     }
198
199     /**
200      * This method is to retrieve data from PolicyEntity table.
201      * 
202      * @param request object
203      * @param response object contains retrieved data
204      */
205     @RequestMapping(value = {"/get_DashboardPdpPolicyCRUDData"},
206             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
207             produces = MediaType.APPLICATION_JSON_VALUE)
208     public void get_DashboardPdpPolicyCrudData(HttpServletRequest request, HttpServletResponse response) {
209         try {
210             Map<String, Object> model = new HashMap<>();
211             ObjectMapper mapper = new ObjectMapper();
212             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
213             model.put("pdpStatusCRUDData", mapper.writeValueAsString(pdpStatusCrudData));
214             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
215             JSONObject j = new JSONObject(msg);
216             response.getWriter().write(j.toString());
217         } catch (Exception e) {
218             policyLogger.error(exceptionOccured, e);
219         }
220     }
221
222     @RequestMapping(value = {"/get_DashboardLoggingData"},
223             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
224             produces = MediaType.APPLICATION_JSON_VALUE)
225     public void getData(HttpServletRequest request, HttpServletResponse response) {
226         try {
227             Map<String, Object> model = new HashMap<>();
228             ObjectMapper mapper = new ObjectMapper();
229             model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData()));
230             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
231             JSONObject j = new JSONObject(msg);
232             response.getWriter().write(j.toString());
233         } catch (Exception e) {
234             policyLogger.error(exceptionOccured + e);
235         }
236     }
237
238     @RequestMapping(value = {"/get_DashboardSystemAlertData"},
239             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
240             produces = MediaType.APPLICATION_JSON_VALUE)
241     public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response) {
242         try {
243             Map<String, Object> model = new HashMap<>();
244             ObjectMapper mapper = new ObjectMapper();
245             model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData()));
246             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
247             JSONObject j = new JSONObject(msg);
248             response.getWriter().write(j.toString());
249         } catch (Exception e) {
250             policyLogger.error(exceptionOccured + e);
251         }
252     }
253
254     @RequestMapping(value = {"/get_DashboardPAPStatusData"},
255             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
256             produces = MediaType.APPLICATION_JSON_VALUE)
257     public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response) {
258         try {
259             Map<String, Object> model = new HashMap<>();
260             ObjectMapper mapper = new ObjectMapper();
261             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
262             addPAPToTable();
263             model.put("papTableDatas", mapper.writeValueAsString(papStatusData));
264             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
265             JSONObject j = new JSONObject(msg);
266             response.getWriter().write(j.toString());
267         } catch (Exception e) {
268             policyLogger.error(exceptionOccured + e);
269         }
270     }
271
272     @RequestMapping(value = {"/get_DashboardPDPStatusData"},
273             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
274             produces = MediaType.APPLICATION_JSON_VALUE)
275     public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response) {
276         try {
277             Map<String, Object> model = new HashMap<>();
278             ObjectMapper mapper = new ObjectMapper();
279             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
280             PolicyController controller = getPolicyControllerInstance();
281             this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine());
282             addPDPToTable();
283             model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData));
284             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
285             JSONObject j = new JSONObject(msg);
286             response.getWriter().write(j.toString());
287         } catch (Exception e) {
288             policyLogger.error(exceptionOccured + e);
289         }
290     }
291
292     @RequestMapping(value = {"/get_DashboardPolicyActivityData"},
293             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
294             produces = MediaType.APPLICATION_JSON_VALUE)
295     public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response) {
296         try {
297             Map<String, Object> model = new HashMap<>();
298             ObjectMapper mapper = new ObjectMapper();
299             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
300             PolicyController controller = getPolicyControllerInstance();
301             this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine());
302             addPolicyToTable();
303             model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData));
304             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
305             JSONObject j = new JSONObject(msg);
306             response.getWriter().write(j.toString());
307         } catch (Exception e) {
308             policyLogger.error(exceptionOccured + e);
309         }
310     }
311
312     /*
313      * Add the PAP information to the PAP Table
314      */
315     public void addPAPToTable() {
316         papStatusData = new ArrayList<>();
317         String papStatus = null;
318         try {
319             PolicyController controller = getPolicyControllerInstance();
320             Set<OnapPDPGroup> groups = controller.getPapEngine().getOnapPDPGroups();
321             if (groups == null) {
322                 throw new PAPException("PAP not running");
323             } else {
324                 papStatus = "IS_OK";
325             }
326         } catch (PAPException | NullPointerException e1) {
327             papStatus = "CANNOT_CONNECT";
328             policyLogger.error("Error getting PAP status, PAP not responding to requests", e1);
329         }
330         String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
331         JSONObject object = new JSONObject();
332         object.put("system", papURL);
333         object.put("status", papStatus);
334         List<Object> data = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
335         object.put("noOfPolicy", data.size());
336         object.put("noOfConnectedTrap", pdpCount);
337         papStatusData.add(0, object);
338     }
339
340
341     /*
342      * Add the PAP Policy information to the PAP Table
343      */
344     public void addPolicyCrudInfoToTable() {
345         policyStatusCrudData = new ArrayList<>();
346         LocalDate now = LocalDate.now();
347         LocalDate lastThirtyDate = now.minusDays(30);
348         policyLogger.info("now: " + now);
349         policyLogger.info("thirty: " + lastThirtyDate);
350         String entityquery = "from PolicyEntity where created_date >= :createdDate";
351         SimpleBindings geParams = new SimpleBindings();
352         geParams.put(createDate, lastThirtyDate.toString());
353         List<Object> datas = commonClassDao.getDataByQuery(entityquery, geParams);
354
355         if (datas == null) {
356             return;
357         }
358
359         datas.stream().forEach((data) -> {
360             JSONObject object = new JSONObject();
361             object.put("id", ((PolicyEntity) data).getPolicyId());
362             object.put(scope, ((PolicyEntity) data).getScope());
363             object.put("policyName", ((PolicyEntity) data).getPolicyName());
364             object.put("version", ((PolicyEntity) data).getVersion());
365             if (isPushedToPDP(((PolicyEntity) data).getPolicyId())) {
366                 object.put(stage, "PDP");
367             } else {
368                 object.put(stage, "PAP");
369             }
370             object.put("createdBy", ((PolicyEntity) data).getCreatedBy());
371             object.put("deleted", ((PolicyEntity) data).isDeleted());
372             object.put("deleteReasonCode", ((PolicyEntity) data).getDeleteReasonCode());
373             object.put("deletedBy", ((PolicyEntity) data).getDeletedBy());
374             object.put("modifiedBy", ((PolicyEntity) data).getModifiedBy());
375             if (((PolicyEntity) data).getModifiedDate() != null) {
376                 Timestamp ts = new Timestamp(((PolicyEntity) data).getModifiedDate().getTime());
377                 Timestamp cts = new Timestamp(((PolicyEntity) data).getCreatedDate().getTime());
378                 object.put(modifiedDate, ts.toString());
379                 object.put(createDate, cts.toString());
380             } else {
381                 object.put(modifiedDate, defaultTime);
382                 object.put(createDate, defaultTime);
383             }
384             policyStatusCrudData.add(object);
385         });
386     }
387
388     /*
389      * Add the PDP Policy information to the PDP Table
390      */
391     private boolean isPushedToPDP(long policyId) {
392         try {
393             String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
394             SimpleBindings geParams = new SimpleBindings();
395             geParams.put("policyEntityId", policyId);
396             List<Object> groupobject = commonClassDao.getDataByQuery(groupEntityquery, geParams);
397             if (groupobject != null && groupobject.size() > 0) {
398                 return true;
399             }
400         } catch (Exception e) {
401             policyLogger.error(exceptionOccured + e);
402         }
403
404         return false;
405     }
406
407     /*
408      * Add the Policy information to the policyStatusCRUDDataTable
409      */
410     private void getPolicyData(String inputScope, String inputStage, String isDeleted, String createdAfter, String createdBefore) {
411         policyStatusCrudData = new ArrayList<>();
412         List<Object> policyData = null;
413         SimpleBindings geParams = new SimpleBindings();
414         try {
415             StringBuilder entityquery = buildSqlQuery(inputScope, isDeleted, createdAfter, createdBefore);
416             if (entityquery == null) {
417                 return;
418             }
419             policyLogger.info("entityquery: " + entityquery.toString());
420             policyLogger.info("geParams: " + geParams.toString());
421
422             policyData = commonClassDao.getDataByQuery(entityquery.toString(), geParams);
423             if (policyData == null) {
424                 return;
425             }
426             policyData.stream().forEach((data) -> {
427                 JSONObject object = populatePolicyData((PolicyEntity) data);
428
429                 if (object.get(stage).equals("PDP") && "PDP".equalsIgnoreCase(inputStage)) {
430                     policyStatusCrudData.add(object);
431                 }
432                 if (object.get(stage).equals("PAP") && "PAP".equalsIgnoreCase(inputStage)) {
433                     policyStatusCrudData.add(object);
434                 }
435                 if ("both".equalsIgnoreCase(inputStage)) {
436                     policyStatusCrudData.add(object);
437                 }
438             });
439         } catch (Exception e) {
440             policyLogger.error(exceptionOccured, e);
441         }
442     }
443
444     /*
445      * Build SQL query
446      */
447     private StringBuilder buildSqlQuery(String scope, String isDeleted, String createdAfter, String createdBefore) {
448         SimpleBindings geParams = new SimpleBindings();
449
450         // since scope is required
451         if (scope == null || scope.isEmpty()) {
452             return null;
453         } else {
454             geParams.put(scope, "%" + scope + "%");
455         }
456         StringBuilder entityquery = new StringBuilder("from PolicyEntity where scope like :scope ");
457         if (!"both".equalsIgnoreCase(isDeleted)) {
458             entityquery.append(" and deleted = :isDeleted");
459             if ("Yes".equalsIgnoreCase(isDeleted)) {
460                 geParams.put("isDeleted", true);
461             } else {
462                 geParams.put("isDeleted", false);
463             }
464         }
465         if (createdAfter != null && !createdAfter.isEmpty()) {
466             entityquery.append(" and created_date >= :createdAfter");
467             geParams.put("createdAfter", createdAfter);
468         }
469         if (createdBefore != null && !createdBefore.isEmpty()) {
470             entityquery.append(" and created_date <= :createdBefore");
471             geParams.put("createdBefore", createdBefore);
472         }
473         return entityquery;
474     }
475
476     private JSONObject populatePolicyData(PolicyEntity data) {
477         JSONObject object = new JSONObject();
478         object.put("id", data.getPolicyId());
479         object.put(scope, data.getScope());
480         object.put("policyName", data.getPolicyName());
481         object.put("version", data.getVersion());
482         if (isPushedToPDP(data.getPolicyId())) {
483             object.put(stage, "PDP");
484         } else {
485             object.put(stage, "PAP");
486         }
487         object.put("createdBy", data.getCreatedBy());
488         object.put("deleted", data.isDeleted());
489         object.put("deleteReasonCode", data.getDeleteReasonCode());
490         object.put("deletedBy", data.getDeletedBy());
491         object.put("modifiedBy", data.getModifiedBy());
492         if (data.getModifiedDate() != null) {
493             Timestamp ts = new Timestamp(data.getModifiedDate().getTime());
494             Timestamp cts = new Timestamp(data.getCreatedDate().getTime());
495             object.put(modifiedDate, ts.toString());
496             object.put(createDate, cts.toString());
497         } else {
498             object.put(modifiedDate, defaultTime);
499             object.put(createDate, defaultTime);
500         }
501
502         return object;
503     }
504
505     /**
506      * Add PDP Information to the PDP Table
507      *
508      */
509     public void addPDPToTable() {
510         pdpCount = 0;
511         pdpStatusData = new ArrayList<>();
512         long naCount;
513         long denyCount = 0;
514         long permitCount = 0;
515         for (PDPGroup group : this.pdpConatiner.getGroups()) {
516             for (PDP pdp : group.getPdps()) {
517                 naCount = -1;
518                 if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) {
519                     String pdpIpAddress = parseIPSystem(pdp.getId());
520                     int port = ((OnapPDP) pdp).getJmxPort();
521                     if (port != 0) {
522                         policyLogger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port);
523                         naCount = getRequestCounts(pdpIpAddress, port, "pdpEvaluationNA");
524                         permitCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationPermit");
525                         denyCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationDeny");
526                     }
527                 }
528                 if (naCount == -1) {
529                     JSONObject object = new JSONObject();
530                     object.put("id", pdp.getId());
531                     object.put("name", pdp.getName());
532                     object.put("groupname", group.getName());
533                     object.put("status", pdp.getStatus().getStatus().toString());
534                     object.put("description", pdp.getDescription());
535                     object.put("permitCount", "NA");
536                     object.put("denyCount", "NA");
537                     object.put("naCount", "NA");
538                     pdpStatusData.add(object);
539                 } else {
540                     JSONObject object = new JSONObject();
541                     object.put("id", pdp.getId());
542                     object.put("name", pdp.getName());
543                     object.put("groupname", group.getName());
544                     object.put("status", pdp.getStatus().getStatus().toString());
545                     object.put("description", pdp.getDescription());
546                     object.put("permitCount", permitCount);
547                     object.put("denyCount", denyCount);
548                     object.put("naCount", naCount);
549                     pdpStatusData.add(object);
550                 }
551                 pdpCount++;
552             }
553         }
554     }
555
556     private static String parseIPSystem(String line) {
557         Pattern pattern = Pattern.compile("://(.+?):");
558         Matcher ip = pattern.matcher(line);
559         if (ip.find()) {
560             return ip.group(1);
561         }
562         return null;
563     }
564
565     /*
566      * Contact JMX Connector Sever and return the value of the given jmxAttribute
567      */
568     @SuppressWarnings({"rawtypes", "unchecked"})
569     private long getRequestCounts(String host, int port, String jmxAttribute) {
570
571         policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server");
572         HashMap map = null;
573         try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
574             jmxConnection.connect();
575             Object o =
576                     jmxConnection.getMBeanServerConnection().getAttribute(
577                             new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
578             policyLogger.debug("pdpEvaluationNA value retreived: " + o);
579             return (long) o;
580         } catch (MalformedURLException e) {
581             policyLogger.error("MalformedURLException for JMX connection", e);
582         } catch (IOException e) {
583             policyLogger.error("Error in reteriving" + jmxAttribute + " from JMX connection", e);
584         } catch (AttributeNotFoundException e) {
585             policyLogger.error("AttributeNotFoundException  " + jmxAttribute + " for JMX connection", e);
586         } catch (InstanceNotFoundException e) {
587             policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e);
588         } catch (MalformedObjectNameException e) {
589             policyLogger.error("MalformedObjectNameException for JMX connection", e);
590         } catch (MBeanException e) {
591             policyLogger.error("MBeanException for JMX connection");
592             policyLogger.error(exceptionOccured + e);
593         } catch (ReflectionException e) {
594             policyLogger.error("ReflectionException for JMX connection", e);
595         }
596
597         return -1;
598     }
599
600     private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException {
601         return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi");
602     }
603
604
605     /*
606      * Add the information to the Policy Table
607      */
608     private void addPolicyToTable() {
609         policyActivityData = new ArrayList<>();
610         String policyID;
611         int policyFireCount;
612         Map<String, String> policyMap = new HashMap<>();
613         Object policyList;
614         // get list of policy
615
616         for (PDPGroup group : this.pdpConatiner.getGroups()) {
617             for (PDPPolicy policy : group.getPolicies()) {
618                 try {
619                     policyMap.put(policy.getPolicyId().replace(" ", ""), policy.getId());
620                 } catch (Exception e) {
621                     policyLogger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + policy.getName() + e);
622                 }
623             }
624
625             for (PDP pdp : group.getPdps()) {
626                 // Add rows to the Policy Table
627                 policyList = null;
628                 if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) {
629                     String pdpIpAddress = parseIPSystem(pdp.getId());
630                     policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort(), "policyCount");
631                 }
632                 if (policyList != null && policyList.toString().length() > 3) {
633                     String[] splitPolicy = policyList.toString().split(",");
634                     for (String policyKeyValue : splitPolicy) {
635                         policyID = urnPolicyID(policyKeyValue);
636                         policyFireCount = countPolicyID(policyKeyValue);
637                         if (policyID != null && policyMap.containsKey(policyID)) {
638                             JSONObject object = new JSONObject();
639                             object.put("policyId", policyMap.get(policyID));
640                             object.put("fireCount", policyFireCount);
641                             object.put("system", pdp.getId());
642                             policyActivityData.add(object);
643                         }
644                     }
645                 } else {
646                     if (policyList != null) {
647                         JSONObject object = new JSONObject();
648                         object.put("policyId", "Unable to retrieve policy information");
649                         object.put("fireCount", "NA");
650                         object.put("system", pdp.getId());
651                         policyActivityData.add(object);
652                     } else {
653                         JSONObject object = new JSONObject();
654                         object.put("policyId", "Unable to access PDP JMX Server");
655                         object.put("fireCount", "NA");
656                         object.put("system", pdp.getId());
657                         policyActivityData.add(object);
658                     }
659                 }
660             }
661         }
662     }
663
664     /*
665      * Contact JMX Connector Sever and return the list of {policy id , count}
666      */
667     @SuppressWarnings({"rawtypes", "unchecked"})
668     private Object getPolicy(String host, int port, String jmxAttribute) {
669         policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: "
670                 + host);
671         HashMap map = null;
672         try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
673             jmxConnection.connect();
674             Object o =
675                     jmxConnection.getMBeanServerConnection().getAttribute(
676                             new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
677             policyLogger.debug("policyMap value retreived: " + o);
678             return o;
679         } catch (MalformedURLException e) {
680             policyLogger.error("MalformedURLException for JMX connection", e);
681         } catch (IOException e) {
682             policyLogger.error("AttributeNotFoundException for policyMap", e);
683         } catch (AttributeNotFoundException e) {
684             policyLogger.error("AttributeNotFoundException for JMX connection", e);
685         } catch (InstanceNotFoundException e) {
686             policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e);
687         } catch (MalformedObjectNameException e) {
688             policyLogger.error("MalformedObjectNameException for JMX connection", e);
689         } catch (MBeanException e) {
690             policyLogger.error("MBeanException for JMX connection", e);
691             policyLogger.error(exceptionOccured + e);
692         } catch (ReflectionException e) {
693             policyLogger.error("ReflectionException for JMX connection", e);
694         }
695
696         return null;
697
698     }
699
700     private static String urnPolicyID(String line) {
701         String[] splitLine = line.split("=");
702         String removeSpaces = splitLine[0].replaceAll("\\s+", "");
703         return removeSpaces.replace("{", "");
704     }
705
706     private static Integer countPolicyID(String line) {
707         String[] splitLine = line.split("=");
708         String sCount = splitLine[1].replace("}", "");
709         return Integer.parseInt(sCount);
710     }
711
712 }