Merge "Add fix for SQL injection."
[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 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
24 import java.io.IOException;
25 import java.net.MalformedURLException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Set;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33
34 import javax.management.AttributeNotFoundException;
35 import javax.management.InstanceNotFoundException;
36 import javax.management.MBeanException;
37 import javax.management.MalformedObjectNameException;
38 import javax.management.ObjectName;
39 import javax.management.ReflectionException;
40 import javax.management.remote.JMXConnector;
41 import javax.management.remote.JMXConnectorFactory;
42 import javax.management.remote.JMXServiceURL;
43 import javax.script.SimpleBindings;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
46
47 import org.json.JSONObject;
48 import org.onap.policy.dao.SystemLogDbDao;
49 import org.onap.policy.model.PDPGroupContainer;
50 import org.onap.policy.rest.XACMLRestProperties;
51 import org.onap.policy.rest.dao.CommonClassDao;
52 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
53 import org.openecomp.portalsdk.core.web.support.JsonMessage;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.http.MediaType;
56 import org.springframework.stereotype.Controller;
57 import org.springframework.web.bind.annotation.RequestMapping;
58
59 import org.onap.policy.common.logging.flexlogger.FlexLogger;
60 import org.onap.policy.common.logging.flexlogger.Logger;
61 import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
62 import org.onap.policy.xacml.api.XACMLErrorConstants;
63 import org.onap.policy.xacml.api.pap.OnapPDP;
64 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
65
66 import com.att.research.xacml.api.pap.PAPException;
67 import com.att.research.xacml.api.pap.PDP;
68 import com.att.research.xacml.api.pap.PDPGroup;
69 import com.att.research.xacml.api.pap.PDPPolicy;
70 import com.att.research.xacml.util.XACMLProperties;
71 import com.fasterxml.jackson.annotation.PropertyAccessor;
72 import com.fasterxml.jackson.databind.ObjectMapper;
73
74 @Controller
75 @RequestMapping({"/"})
76 public class DashboardController  extends RestrictedBaseController{
77         private static final Logger policyLogger = FlexLogger.getLogger(DashboardController.class);
78         @Autowired
79         SystemLogDbDao systemDAO;
80
81         @Autowired
82         CommonClassDao commonClassDao;
83
84         private int pdpCount;
85         private PDPGroupContainer pdpConatiner;
86         private ArrayList<Object> pdpStatusData;
87         private ArrayList<Object> papStatusData;
88         private ArrayList<Object> policyActivityData;
89
90         private PolicyController policyController;
91         public PolicyController getPolicyController() {
92                 return policyController;
93         }
94
95         public void setPolicyController(PolicyController policyController) {
96                 this.policyController = policyController;
97         }
98
99         private PolicyController getPolicyControllerInstance(){
100                 return policyController != null ? getPolicyController() : new PolicyController();
101         }
102
103         @RequestMapping(value={"/get_DashboardLoggingData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
104         public void getData(HttpServletRequest request, HttpServletResponse response){
105                 try{
106                         Map<String, Object> model = new HashMap<>();
107                         ObjectMapper mapper = new ObjectMapper();
108                         model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData()));
109                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
110                         JSONObject j = new JSONObject(msg);
111                         response.getWriter().write(j.toString());
112                 }
113                 catch (Exception e){
114                         policyLogger.error("Exception Occured"+e);
115                 }
116         }
117
118         @RequestMapping(value={"/get_DashboardSystemAlertData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
119         public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response){
120                 try{
121                         Map<String, Object> model = new HashMap<>();
122                         ObjectMapper mapper = new ObjectMapper();
123                         model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData()));
124                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
125                         JSONObject j = new JSONObject(msg);
126                         response.getWriter().write(j.toString());
127                 }
128                 catch (Exception e){
129                         policyLogger.error("Exception Occured"+e);
130                 }
131         }
132
133         @RequestMapping(value={"/get_DashboardPAPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
134         public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response){
135                 try{
136                         Map<String, Object> model = new HashMap<>();
137                         ObjectMapper mapper = new ObjectMapper();
138                         mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
139                         addPAPToTable();
140                         model.put("papTableDatas", mapper.writeValueAsString(papStatusData));
141                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
142                         JSONObject j = new JSONObject(msg);
143                         response.getWriter().write(j.toString());
144                 }
145                 catch (Exception e){
146                         policyLogger.error("Exception Occured"+e);
147                 }
148         }
149
150         @RequestMapping(value={"/get_DashboardPDPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
151         public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response){
152                 try{
153                         Map<String, Object> model = new HashMap<>();
154                         ObjectMapper mapper = new ObjectMapper();
155                         mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
156                         PolicyController controller = getPolicyControllerInstance();
157                         this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine());
158                         addPDPToTable();
159                         model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData));
160                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
161                         JSONObject j = new JSONObject(msg);
162                         response.getWriter().write(j.toString());
163                 }
164                 catch (Exception e){
165                         policyLogger.error("Exception Occured"+e);
166                 }
167         }
168
169         @RequestMapping(value={"/get_DashboardPolicyActivityData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
170         public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response){
171                 try{
172                         Map<String, Object> model = new HashMap<>();
173                         ObjectMapper mapper = new ObjectMapper();
174                         mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
175                         PolicyController controller = getPolicyControllerInstance();
176                         this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine());
177                         addPolicyToTable();
178                         model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData));
179                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
180                         JSONObject j = new JSONObject(msg);
181                         response.getWriter().write(j.toString());
182                 }
183                 catch (Exception e){
184                         policyLogger.error("Exception Occured"+e);
185                 }
186         }
187
188         /*
189          * Add the PAP information to the PAP Table
190          */
191         public void addPAPToTable(){
192                 papStatusData = new ArrayList<>();
193                 String papStatus = null;
194                 try {
195                         PolicyController controller = getPolicyControllerInstance();
196                         Set<OnapPDPGroup> groups = controller.getPapEngine().getOnapPDPGroups();
197                         if (groups == null) {
198                                 papStatus = "UNKNOWN";
199                                 throw new PAPException("PAP not running");
200                         }else {
201                                 papStatus = "IS_OK";
202                         }
203                 } catch (PAPException | NullPointerException e1) {
204                         papStatus = "CANNOT_CONNECT";
205                         policyLogger.error("Error getting PAP status, PAP not responding to requests", e1);
206                 }
207                 String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
208                 JSONObject object = new JSONObject();
209                 object.put("system", papURL);
210                 object.put("status", papStatus);
211                 List<Object> data = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
212                 object.put("noOfPolicy", data.size());
213                 object.put("noOfConnectedTrap", pdpCount);
214                 papStatusData.add(0, object);
215         }
216
217         /**
218          * Add PDP Information to the PDP Table
219          *
220          */
221         public void addPDPToTable(){
222                 pdpCount = 0;
223                 pdpStatusData = new ArrayList<>();
224                 long naCount;
225                 long denyCount = 0;
226                 long permitCount = 0;
227                 for (PDPGroup group : this.pdpConatiner.getGroups()){
228                         for (PDP pdp : group.getPdps()){
229                                 naCount = -1;
230                                 if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString())  && ((OnapPDP) pdp).getJmxPort() != 0){
231                                         String pdpIpAddress = parseIPSystem(pdp.getId());
232                                         int port = ((OnapPDP) pdp).getJmxPort();
233                                         if (port != 0){
234                                                 policyLogger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port);
235                                                 naCount = getRequestCounts(pdpIpAddress, port, "pdpEvaluationNA");
236                                                 permitCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationPermit");
237                                                 denyCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationDeny");
238                                         }
239                                 }
240                                 if (naCount == -1){
241                                         JSONObject object = new JSONObject();
242                                         object.put("id", pdp.getId());
243                                         object.put("name", pdp.getName());
244                                         object.put("groupname", group.getName());
245                                         object.put("status", pdp.getStatus().getStatus().toString());
246                                         object.put("description", pdp.getDescription());
247                                         object.put("permitCount", "NA");
248                                         object.put("denyCount", "NA");
249                                         object.put("naCount", "NA");
250                                         pdpStatusData.add(object);
251                                 }else{
252                                         JSONObject object = new JSONObject();
253                                         object.put("id", pdp.getId());
254                                         object.put("name", pdp.getName());
255                                         object.put("groupname", group.getName());
256                                         object.put("status", pdp.getStatus().getStatus().toString());
257                                         object.put("description", pdp.getDescription());
258                                         object.put("permitCount", permitCount);
259                                         object.put("denyCount", denyCount);
260                                         object.put("naCount", naCount);
261                                         pdpStatusData.add(object);
262                                 }
263                                 pdpCount++;
264                         }
265                 }
266         }
267
268         private static String parseIPSystem(String line) {
269                 Pattern pattern = Pattern.compile("://(.+?):");
270                 Matcher ip = pattern.matcher(line);
271                 if (ip.find())
272                 {
273                         return ip.group(1);
274                 }
275                 return null;
276         }
277
278         /*
279          * Contact JMX Connector Sever and return the value of the given jmxAttribute
280          */
281         @SuppressWarnings({ "rawtypes", "unchecked" })
282         private long getRequestCounts(String host, int port, String jmxAttribute) {
283
284                 policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server");
285                 HashMap map = new HashMap();
286                 map = null;
287                 JMXConnector jmxConnection;
288                 try {
289                         jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
290                         jmxConnection.connect();
291                         Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
292                         jmxConnection.close();
293                         policyLogger.debug("pdpEvaluationNA value retreived: " + o);
294                         return (long) o;
295                 } catch (MalformedURLException e) {
296                         policyLogger.error("MalformedURLException for JMX connection" , e);
297                 } catch (IOException e) {
298                         policyLogger.error("Error in reteriving" + jmxAttribute + " from JMX connection", e);
299                 } catch (AttributeNotFoundException e) {
300                         policyLogger.error("AttributeNotFoundException  " + jmxAttribute +  " for JMX connection", e);
301                 } catch (InstanceNotFoundException e) {
302                         policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e);
303                 } catch (MalformedObjectNameException e) {
304                         policyLogger.error("MalformedObjectNameException for JMX connection", e);
305                 } catch (MBeanException e) {
306                         policyLogger.error("MBeanException for JMX connection");
307                         policyLogger.error("Exception Occured"+e);
308                 } catch (ReflectionException e) {
309                         policyLogger.error("ReflectionException for JMX connection", e);
310                 }
311
312                 return -1;
313         }
314
315         private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException{
316             return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi");
317         }
318
319
320         /*
321          * Add the information to the Policy Table
322          */
323         private void addPolicyToTable() {
324                 policyActivityData = new ArrayList<>();
325                 String policyID = null;
326                 int policyFireCount = 0;
327                 Map<String, String> policyMap = new HashMap<>();
328                 Object policyList = null;
329                 //get list of policy
330
331                 for (PDPGroup group : this.pdpConatiner.getGroups()){
332                         for (PDPPolicy policy : group.getPolicies()){
333                                 try{
334                                         policyMap.put(policy.getPolicyId().replace(" ", ""), policy.getId());
335                                 }catch(Exception e){
336                                         policyLogger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+policy.getName() +e);
337                                 }
338                         }
339
340                         for (PDP pdp : group.getPdps()){
341                                 // Add rows to the Policy Table
342                                 policyList = null;
343                                 if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0){
344                                         String pdpIpAddress = parseIPSystem(pdp.getId());
345                                         policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort(), "policyCount");
346                                 }
347                                 if (policyList != null && policyList.toString().length() > 3){
348                                         String[]  splitPolicy = policyList.toString().split(",");
349                                         for (String policyKeyValue : splitPolicy){
350                                                 policyID = urnPolicyID(policyKeyValue);
351                                                 policyFireCount = countPolicyID(policyKeyValue);
352                                                 if (policyID != null ){
353                                                         if (policyMap.containsKey(policyID)){
354                                                                 JSONObject object = new JSONObject();
355                                                                 object.put("policyId", policyMap.get(policyID));
356                                                                 object.put("fireCount", policyFireCount);
357                                                                 object.put("system", pdp.getId());
358                                                                 policyActivityData.add(object);
359                                                         }
360                                                 }
361                                         }
362                                 }else {
363                                         if (policyList != null){
364                                                 JSONObject object = new JSONObject();
365                                                 object.put("policyId", "Unable to retrieve policy information");
366                                                 object.put("fireCount", "NA");
367                                                 object.put("system", pdp.getId());
368                                                 policyActivityData.add(object);
369                                         }else{
370                                                 JSONObject object = new JSONObject();
371                                                 object.put("policyId", "Unable to access PDP JMX Server");
372                                                 object.put("fireCount", "NA");
373                                                 object.put("system", pdp.getId());
374                                                 policyActivityData.add(object);
375                                         }
376                                 }
377                         }
378                 }
379         }
380
381         /*
382          * Contact JMX Connector Sever and return the list of {policy id , count}
383          */
384         @SuppressWarnings({ "rawtypes", "unchecked" })
385         private Object getPolicy(String host, int port, String jmxAttribute){
386                 policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host);
387                 HashMap map = new HashMap();
388                 map = null;
389                 JMXConnector jmxConnection;
390                 try {
391                         jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
392                         jmxConnection.connect();
393                         Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
394                         jmxConnection.close();
395                         policyLogger.debug("policyMap value retreived: " + o);
396                         return  o;
397                 } catch (MalformedURLException e) {
398                         policyLogger.error("MalformedURLException for JMX connection" , e);
399                 } catch (IOException e) {
400                         policyLogger.error("AttributeNotFoundException for policyMap" , e);
401                 } catch (AttributeNotFoundException e) {
402                         policyLogger.error("AttributeNotFoundException for JMX connection", e);
403                 } catch (InstanceNotFoundException e) {
404                         policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e);
405                 } catch (MalformedObjectNameException e) {
406                         policyLogger.error("MalformedObjectNameException for JMX connection", e);
407                 } catch (MBeanException e) {
408                         policyLogger.error("MBeanException for JMX connection", e);
409                         policyLogger.error("Exception Occured"+e);
410                 } catch (ReflectionException e) {
411                         policyLogger.error("ReflectionException for JMX connection", e);
412                 }
413
414                 return null;
415
416         }
417
418         private static String urnPolicyID(String line){
419                 String[]  splitLine = line.toString().split("=");
420                 String removeSpaces = splitLine[0].replaceAll("\\s+", "");
421                 return removeSpaces.replace("{", "");
422         }
423
424         private static Integer countPolicyID(String line){
425                 String[]  splitLine = line.toString().split("=");
426                 String sCount = splitLine[1].replace("}", "");
427                 int intCount = Integer.parseInt(sCount);
428                 return intCount;
429         }
430
431 }