Update css file name in conf.py
[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             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).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(
153             value = {"/dashboardController/dashboardAdvancedSearch.htm"},
154             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
155     public void dashboardAdvancedSearch(HttpServletRequest request, HttpServletResponse response) throws IOException {
156         String lscope = null;
157         String lstage = "both";
158         String isDelected = "both";
159         String ttlDateAfter = null;
160         String ttlDateBefore = null;
161         try {
162             ObjectMapper mapper = new ObjectMapper();
163             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
164             JsonNode root = mapper.readTree(request.getReader());
165             JsonNode inputData = root.get("policyData");
166             JsonNode jscope = inputData.path(scope);
167             if (jscope != null) {
168                 lscope = jscope.textValue();
169             }
170             JsonNode jstage = inputData.path(stage);
171             if (jstage != null) {
172                 lstage = jstage.textValue();
173             }
174             JsonNode jisDelected = inputData.path("isDelected");
175             if (jisDelected != null) {
176                 isDelected = jisDelected.textValue();
177             }
178             JsonNode jttlDateAfter = inputData.path("ttlDate_after");
179             if (jttlDateAfter != null) {
180                 ttlDateAfter = jttlDateAfter.textValue();
181             }
182             JsonNode jttlDateBefore = inputData.path("ttlDate_before");
183             if (jttlDateBefore != null) {
184                 ttlDateBefore = jttlDateBefore.textValue();
185             }
186             getPolicyData(lscope, lstage, isDelected, ttlDateAfter, ttlDateBefore);
187             Map<String, Object> model = new HashMap<>();
188             model.put("policyStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData));
189             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
190         } catch (Exception e) {
191             response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
192             PrintWriter out = response.getWriter();
193             out.write(PolicyUtils.CATCH_EXCEPTION);
194         }
195
196     }
197
198     /**
199      * This method is to retrieve data from PolicyEntity table.
200      *
201      * @param request object
202      * @param response object contains retrieved data
203      */
204     @RequestMapping(
205             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             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
215         } catch (Exception e) {
216             policyLogger.error(exceptionOccured, e);
217         }
218     }
219
220     /**
221      * getData.
222      *
223      * @param request HttpServletRequest
224      * @param response HttpServletResponse
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             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
236         } catch (Exception e) {
237             policyLogger.error(exceptionOccured + e);
238         }
239     }
240
241     /**
242      * getSystemAlertData.
243      *
244      * @param request HttpServletRequest
245      * @param response HttpServletResponse
246      */
247     @RequestMapping(
248             value = {"/get_DashboardSystemAlertData"},
249             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
250             produces = MediaType.APPLICATION_JSON_VALUE)
251     public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response) {
252         try {
253             Map<String, Object> model = new HashMap<>();
254             ObjectMapper mapper = new ObjectMapper();
255             model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData()));
256             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
257         } catch (Exception e) {
258             policyLogger.error(exceptionOccured + e);
259         }
260     }
261
262     /**
263      * getPAPStatusData.
264      *
265      * @param request HttpServletRequest
266      * @param response HttpServletResponse
267      */
268     @RequestMapping(
269             value = {"/get_DashboardPAPStatusData"},
270             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
271             produces = MediaType.APPLICATION_JSON_VALUE)
272     public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response) {
273         try {
274             Map<String, Object> model = new HashMap<>();
275             ObjectMapper mapper = new ObjectMapper();
276             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
277             addPAPToTable();
278             model.put("papTableDatas", mapper.writeValueAsString(papStatusData));
279             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
280         } catch (Exception e) {
281             policyLogger.error(exceptionOccured + e);
282         }
283     }
284
285     /**
286      * getPDPStatusData.
287      *
288      * @param request HttpServletRequest
289      * @param response HttpServletResponse
290      */
291     @RequestMapping(
292             value = {"/get_DashboardPDPStatusData"},
293             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
294             produces = MediaType.APPLICATION_JSON_VALUE)
295     public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response) {
296         try {
297             final 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             addPDPToTable();
303             model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData));
304             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
305             response.getWriter().write(new JSONObject(msg).toString());
306         } catch (Exception e) {
307             policyLogger.error(exceptionOccured + e);
308         }
309     }
310
311     /**
312      * getPolicyActivityData.
313      *
314      * @param request HttpServletRequest
315      * @param response HttpServletResponse
316      */
317     @RequestMapping(
318             value = {"/get_DashboardPolicyActivityData"},
319             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
320             produces = MediaType.APPLICATION_JSON_VALUE)
321     public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response) {
322         try {
323             final Map<String, Object> model = new HashMap<>();
324             ObjectMapper mapper = new ObjectMapper();
325             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
326             PolicyController controller = getPolicyControllerInstance();
327             this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine());
328             addPolicyToTable();
329             model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData));
330             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
331         } catch (Exception e) {
332             policyLogger.error(exceptionOccured + e);
333         }
334     }
335
336     /*
337      * Add the PAP information to the PAP Table
338      */
339     public void addPAPToTable() {
340         papStatusData = new ArrayList<>();
341         String papStatus = null;
342         try {
343             PolicyController controller = getPolicyControllerInstance();
344             Set<OnapPDPGroup> groups = controller.getPapEngine().getOnapPDPGroups();
345             if (groups == null) {
346                 throw new PAPException("PAP not running");
347             } else {
348                 papStatus = "IS_OK";
349             }
350         } catch (PAPException | NullPointerException e1) {
351             papStatus = "CANNOT_CONNECT";
352             policyLogger.error("Error getting PAP status, PAP not responding to requests", e1);
353         }
354         String papUrl = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
355         JSONObject object = new JSONObject();
356         object.put("system", papUrl);
357         object.put("status", papStatus);
358         List<Object> data = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
359         object.put("noOfPolicy", data.size());
360         object.put("noOfConnectedTrap", pdpCount);
361         papStatusData.add(0, object);
362     }
363
364     /**
365      * Add the PAP Policy information to the PAP Table.
366      */
367     public void addPolicyCrudInfoToTable() {
368         policyStatusCrudData = new ArrayList<>();
369         LocalDate now = LocalDate.now();
370         LocalDate lastThirtyDate = now.minusDays(30);
371         policyLogger.info("now: " + now);
372         policyLogger.info("thirty: " + lastThirtyDate);
373         String entityquery = "from PolicyEntity where created_date >= :createdDate";
374         SimpleBindings geParams = new SimpleBindings();
375         geParams.put(createDate, lastThirtyDate.toString());
376         List<Object> datas = commonClassDao.getDataByQuery(entityquery, geParams);
377
378         if (datas == null) {
379             return;
380         }
381
382         datas.stream().forEach((data) -> {
383             JSONObject object = new JSONObject();
384             object.put("id", ((PolicyEntity) data).getPolicyId());
385             object.put(scope, ((PolicyEntity) data).getScope());
386             object.put("policyName", ((PolicyEntity) data).getPolicyName());
387             object.put("version", ((PolicyEntity) data).getVersion());
388             if (isPushedToPdp(((PolicyEntity) data).getPolicyId())) {
389                 object.put(stage, "PDP");
390             } else {
391                 object.put(stage, "PAP");
392             }
393             object.put("createdBy", ((PolicyEntity) data).getCreatedBy());
394             object.put("deleted", ((PolicyEntity) data).isDeleted());
395             object.put("deleteReasonCode", ((PolicyEntity) data).getDeleteReasonCode());
396             object.put("deletedBy", ((PolicyEntity) data).getDeletedBy());
397             object.put("modifiedBy", ((PolicyEntity) data).getModifiedBy());
398             if (((PolicyEntity) data).getModifiedDate() != null) {
399                 Timestamp ts = new Timestamp(((PolicyEntity) data).getModifiedDate().getTime());
400                 Timestamp cts = new Timestamp(((PolicyEntity) data).getCreatedDate().getTime());
401                 object.put(modifiedDate, ts.toString());
402                 object.put(createDate, cts.toString());
403             } else {
404                 object.put(modifiedDate, defaultTime);
405                 object.put(createDate, defaultTime);
406             }
407             policyStatusCrudData.add(object);
408         });
409     }
410
411     /*
412      * Add the PDP Policy information to the PDP Table
413      */
414     private boolean isPushedToPdp(long policyId) {
415         try {
416             String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
417             SimpleBindings geParams = new SimpleBindings();
418             geParams.put("policyEntityId", policyId);
419             List<Object> groupobject = commonClassDao.getDataByQuery(groupEntityquery, geParams);
420             if (groupobject != null && ! groupobject.isEmpty()) {
421                 return true;
422             }
423         } catch (Exception e) {
424             policyLogger.error(exceptionOccured + e);
425         }
426
427         return false;
428     }
429
430     /*
431      * Add the Policy information to the policyStatusCRUDDataTable
432      */
433     private void getPolicyData(String inputScope, String inputStage, String isDeleted, String createdAfter,
434             String createdBefore) {
435         policyStatusCrudData = new ArrayList<>();
436         List<Object> policyData = null;
437         SimpleBindings geParams = new SimpleBindings();
438         try {
439             StringBuilder entityquery = buildSqlQuery(inputScope, isDeleted, createdAfter, createdBefore);
440             if (entityquery == null) {
441                 return;
442             }
443             policyLogger.info("entityquery: " + entityquery.toString());
444             policyLogger.info("geParams: " + geParams.toString());
445
446             policyData = commonClassDao.getDataByQuery(entityquery.toString(), geParams);
447             if (policyData == null) {
448                 return;
449             }
450             policyData.stream().forEach((data) -> {
451                 JSONObject object = populatePolicyData((PolicyEntity) data);
452
453                 if (object.get(stage).equals("PDP") && "PDP".equalsIgnoreCase(inputStage)) {
454                     policyStatusCrudData.add(object);
455                 }
456                 if (object.get(stage).equals("PAP") && "PAP".equalsIgnoreCase(inputStage)) {
457                     policyStatusCrudData.add(object);
458                 }
459                 if ("both".equalsIgnoreCase(inputStage)) {
460                     policyStatusCrudData.add(object);
461                 }
462             });
463         } catch (Exception e) {
464             policyLogger.error(exceptionOccured, e);
465         }
466     }
467
468     /*
469      * Build SQL query
470      */
471     private StringBuilder buildSqlQuery(String scope, String isDeleted, String createdAfter, String createdBefore) {
472         SimpleBindings geParams = new SimpleBindings();
473
474         // since scope is required
475         if (scope == null || scope.isEmpty()) {
476             return null;
477         } else {
478             geParams.put(scope, "%" + scope + "%");
479         }
480         StringBuilder entityquery = new StringBuilder("from PolicyEntity where scope like :scope ");
481         if (!"both".equalsIgnoreCase(isDeleted)) {
482             entityquery.append(" and deleted = :isDeleted");
483             if ("Yes".equalsIgnoreCase(isDeleted)) {
484                 geParams.put("isDeleted", true);
485             } else {
486                 geParams.put("isDeleted", false);
487             }
488         }
489         if (createdAfter != null && !createdAfter.isEmpty()) {
490             entityquery.append(" and created_date >= :createdAfter");
491             geParams.put("createdAfter", createdAfter);
492         }
493         if (createdBefore != null && !createdBefore.isEmpty()) {
494             entityquery.append(" and created_date <= :createdBefore");
495             geParams.put("createdBefore", createdBefore);
496         }
497         return entityquery;
498     }
499
500     private JSONObject populatePolicyData(PolicyEntity data) {
501         JSONObject object = new JSONObject();
502         object.put("id", data.getPolicyId());
503         object.put(scope, data.getScope());
504         object.put("policyName", data.getPolicyName());
505         object.put("version", data.getVersion());
506         if (isPushedToPdp(data.getPolicyId())) {
507             object.put(stage, "PDP");
508         } else {
509             object.put(stage, "PAP");
510         }
511         object.put("createdBy", data.getCreatedBy());
512         object.put("deleted", data.isDeleted());
513         object.put("deleteReasonCode", data.getDeleteReasonCode());
514         object.put("deletedBy", data.getDeletedBy());
515         object.put("modifiedBy", data.getModifiedBy());
516         if (data.getModifiedDate() != null) {
517             Timestamp ts = new Timestamp(data.getModifiedDate().getTime());
518             Timestamp cts = new Timestamp(data.getCreatedDate().getTime());
519             object.put(modifiedDate, ts.toString());
520             object.put(createDate, cts.toString());
521         } else {
522             object.put(modifiedDate, defaultTime);
523             object.put(createDate, defaultTime);
524         }
525
526         return object;
527     }
528
529     /**
530      * Add PDP Information to the PDP Table.
531      *
532      */
533     public void addPDPToTable() {
534         pdpCount = 0;
535         pdpStatusData = new ArrayList<>();
536         long naCount;
537         long denyCount = 0;
538         long permitCount = 0;
539         for (PDPGroup group : this.pdpConatiner.getGroups()) {
540             for (PDP pdp : group.getPdps()) {
541                 naCount = -1;
542                 if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) {
543                     String pdpIpAddress = parseIpSystem(pdp.getId());
544                     int port = ((OnapPDP) pdp).getJmxPort();
545                     if (port != 0) {
546                         policyLogger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port);
547                         naCount = getRequestCounts(pdpIpAddress, port, "pdpEvaluationNA");
548                         permitCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationPermit");
549                         denyCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationDeny");
550                     }
551                 }
552                 if (naCount == -1) {
553                     JSONObject object = new JSONObject();
554                     object.put("id", pdp.getId());
555                     object.put("name", pdp.getName());
556                     object.put("groupname", group.getName());
557                     object.put("status", pdp.getStatus().getStatus().toString());
558                     object.put("description", pdp.getDescription());
559                     object.put("permitCount", "NA");
560                     object.put("denyCount", "NA");
561                     object.put("naCount", "NA");
562                     pdpStatusData.add(object);
563                 } else {
564                     JSONObject object = new JSONObject();
565                     object.put("id", pdp.getId());
566                     object.put("name", pdp.getName());
567                     object.put("groupname", group.getName());
568                     object.put("status", pdp.getStatus().getStatus().toString());
569                     object.put("description", pdp.getDescription());
570                     object.put("permitCount", permitCount);
571                     object.put("denyCount", denyCount);
572                     object.put("naCount", naCount);
573                     pdpStatusData.add(object);
574                 }
575                 pdpCount++;
576             }
577         }
578     }
579
580     private static String parseIpSystem(String line) {
581         Pattern pattern = Pattern.compile("://(.+?):");
582         Matcher ip = pattern.matcher(line);
583         if (ip.find()) {
584             return ip.group(1);
585         }
586         return null;
587     }
588
589     /*
590      * Contact JMX Connector Sever and return the value of the given jmxAttribute
591      */
592     @SuppressWarnings({"rawtypes", "unchecked"})
593     private long getRequestCounts(String host, int port, String jmxAttribute) {
594
595         policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server");
596         HashMap map = null;
597         try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) {
598             jmxConnection.connect();
599             Object obj = jmxConnection.getMBeanServerConnection()
600                     .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
601             policyLogger.debug("pdpEvaluationNA value retreived: " + obj);
602             return (long) obj;
603         } catch (MalformedURLException e) {
604             policyLogger.error("MalformedURLException for JMX connection", e);
605         } catch (IOException e) {
606             policyLogger.error("Error in reteriving" + jmxAttribute + " from JMX connection", e);
607         } catch (AttributeNotFoundException e) {
608             policyLogger.error("AttributeNotFoundException  " + jmxAttribute + " for JMX connection", e);
609         } catch (InstanceNotFoundException e) {
610             policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e);
611         } catch (MalformedObjectNameException e) {
612             policyLogger.error("MalformedObjectNameException for JMX connection", e);
613         } catch (MBeanException e) {
614             policyLogger.error("MBeanException for JMX connection");
615             policyLogger.error(exceptionOccured + e);
616         } catch (ReflectionException e) {
617             policyLogger.error("ReflectionException for JMX connection", e);
618         }
619
620         return -1;
621     }
622
623     private static JMXServiceURL createConnectionUrl(String host, int port) throws MalformedURLException {
624         return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi");
625     }
626
627     /*
628      * Add the information to the Policy Table
629      */
630     private void addPolicyToTable() {
631         policyActivityData = new ArrayList<>();
632         String policyID;
633         int policyFireCount;
634         Map<String, String> policyMap = new HashMap<>();
635         Object policyList;
636         // get list of policy
637
638         for (PDPGroup group : this.pdpConatiner.getGroups()) {
639             for (PDPPolicy policy : group.getPolicies()) {
640                 try {
641                     policyMap.put(policy.getPolicyId().replace(" ", ""), policy.getId());
642                 } catch (Exception e) {
643                     policyLogger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + policy.getName() + e);
644                 }
645             }
646
647             for (PDP pdp : group.getPdps()) {
648                 // Add rows to the Policy Table
649                 policyList = null;
650                 if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) {
651                     String pdpIpAddress = parseIpSystem(pdp.getId());
652                     policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort());
653                 }
654                 if (policyList != null && policyList.toString().length() > 3) {
655                     String[] splitPolicy = policyList.toString().split(",");
656                     for (String policyKeyValue : splitPolicy) {
657                         policyID = urnPolicyID(policyKeyValue);
658                         policyFireCount = countPolicyID(policyKeyValue);
659                         if (policyID != null && policyMap.containsKey(policyID)) {
660                             JSONObject object = new JSONObject();
661                             object.put("policyId", policyMap.get(policyID));
662                             object.put("fireCount", policyFireCount);
663                             object.put("system", pdp.getId());
664                             policyActivityData.add(object);
665                         }
666                     }
667                 } else {
668                     JSONObject object = new JSONObject();
669                     if (policyList != null) {
670                         object.put("policyId", "Unable to retrieve policy information");
671                     } else {
672                         object.put("policyId", "Unable to access PDP JMX Server");
673                     }
674                     object.put("fireCount", "NA");
675                     object.put("system", pdp.getId());
676                     policyActivityData.add(object);
677                 }
678             }
679         }
680     }
681
682     /*
683      * Contact JMX Connector Sever and return the list of {policy id , count}
684      */
685     @SuppressWarnings({"rawtypes", "unchecked"})
686     private Object getPolicy(String host, int port) {
687         policyLogger
688                 .debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host);
689         HashMap map = null;
690         try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) {
691             jmxConnection.connect();
692             Object obj = jmxConnection.getMBeanServerConnection()
693                     .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
694             policyLogger.debug("policyMap value retreived: " + obj);
695             return obj;
696         } catch (MalformedURLException e) {
697             policyLogger.error("MalformedURLException for JMX connection", e);
698         } catch (IOException e) {
699             policyLogger.error("AttributeNotFoundException for policyMap", e);
700         } catch (AttributeNotFoundException e) {
701             policyLogger.error("AttributeNotFoundException for JMX connection", e);
702         } catch (InstanceNotFoundException e) {
703             policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e);
704         } catch (MalformedObjectNameException e) {
705             policyLogger.error("MalformedObjectNameException for JMX connection", e);
706         } catch (MBeanException e) {
707             policyLogger.error("MBeanException for JMX connection", e);
708             policyLogger.error(exceptionOccured + e);
709         } catch (ReflectionException e) {
710             policyLogger.error("ReflectionException for JMX connection", e);
711         }
712
713         return null;
714
715     }
716
717     private static String urnPolicyID(String line) {
718         String[] splitLine = line.split("=");
719         String removeSpaces = splitLine[0].replaceAll("\\s+", "");
720         return removeSpaces.replace("{", "");
721     }
722
723     private static Integer countPolicyID(String line) {
724         String[] splitLine = line.split("=");
725         return Integer.parseInt(splitLine[1].replace("}", ""));
726     }
727
728 }