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