Fixed the Sonar technical debt.
[policy/engine.git] / ONAP-REST / src / main / java / org / onap / policy / rest / XACMLRest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-REST
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.rest;
22
23 import java.io.IOException;
24 import java.util.Enumeration;
25 import java.util.Map;
26 import java.util.Properties;
27 import java.util.Set;
28
29 import javax.servlet.ServletConfig;
30 import javax.servlet.http.HttpServletRequest;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.onap.policy.common.logging.eelf.MessageCodes;
35 import org.onap.policy.common.logging.eelf.PolicyLogger;
36
37 import com.att.research.xacml.util.XACMLProperties;
38
39
40 /**
41  * This static class is used by both the PDP and PAP servlet's. It contains some common
42  * static functions and objects used by both the servlet's.
43  * 
44  *
45  */
46 public class XACMLRest {
47         private static final Log logger = LogFactory.getLog(XACMLRest.class);
48         private static Properties restProperties = new Properties();
49
50         private XACMLRest(){
51             // Empty constructor
52     }
53         /**
54          * This must be called during servlet initialization. It sets up the xacml.?.properties
55          * file as a system property. If the System property is already set, then it does not
56          * do anything. This allows the developer to specify their own xacml.properties file to be
57          * used. They can 1) modify the default properties that comes with the project, or 2) change
58          * the WebInitParam annotation, or 3) specify an alternative path in the web.xml, or 4) set
59          * the Java System property to point to their xacml.properties file.
60          * 
61          * The recommended way of overriding the default xacml.properties file is using a Java System
62          * property:
63          * 
64          * -Dxacml.properties=/opt/app/xacml/etc/xacml.admin.properties
65          * 
66          * This way one does not change any actual code or files in the project and can leave the 
67          * defaults alone.
68          * 
69          * @param config - The servlet config file passed from the javax servlet init() function
70          */
71         public static void xacmlInit(ServletConfig config) {
72                 //
73                 // Get the XACML Properties File parameter first
74                 //
75                 String propFile = config.getInitParameter("XACML_PROPERTIES_NAME");
76                 if (propFile != null) {
77                         //
78                         // Look for system override
79                         //
80                         String xacmlPropertiesName = System.getProperty(XACMLProperties.XACML_PROPERTIES_NAME);
81                         logger.info("\n\n" + xacmlPropertiesName + "\n" + XACMLProperties.XACML_PROPERTIES_NAME);
82                         if (xacmlPropertiesName == null) {
83                                 //
84                                 // Set it to our servlet default
85                                 //
86                                 if (logger.isDebugEnabled()) {
87                                         logger.debug("Using Servlet Config Property for XACML_PROPERTIES_NAME:" + propFile);
88                                 }
89                                 System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, propFile);
90                         } else {
91                                 if (logger.isDebugEnabled()) {
92                                         logger.debug("Using System Property for XACML_PROPERTIES_NAME:" + xacmlPropertiesName);
93                                 }
94                         }
95                 }
96                 //
97                 // Setup the remaining properties
98                 //
99                 Enumeration<String> params = config.getInitParameterNames();
100                 while (params.hasMoreElements()) {
101                         String param = params.nextElement();
102                         if (! "XACML_PROPERTIES_NAME".equals(param)) {
103                                 String value = config.getInitParameter(param);
104                                 PolicyLogger.info(param + "=" + config.getInitParameter(param));
105                                 restProperties.setProperty(param, value);
106                         }
107                 }
108         }
109         
110         /**
111          * Reset's the XACMLProperties internal properties object so we start
112          * in a fresh environment. Then adds back in our Servlet init properties that were
113          * passed in the javax Servlet init() call.
114          * 
115          * This function is primarily used when a new configuration is passed in and the
116          * PDP servlet needs to load a new PDP engine instance.
117          * 
118          * @param pipProperties - PIP configuration properties
119          * @param policyProperties  - Policy configuration properties
120          */
121         public static void loadXacmlProperties(Properties policyProperties, Properties pipProperties) {
122                 try {
123                         //
124                         // Start fresh
125                         //
126                         XACMLProperties.reloadProperties();
127                         //
128                         // Now load our init properties
129                         //
130                         XACMLProperties.getProperties().putAll(XACMLRest.restProperties);
131                         //
132                         // Load our policy properties
133                         //
134                         if (policyProperties != null) {
135                                 XACMLProperties.getProperties().putAll(policyProperties);
136                         }
137                         //
138                         // Load our pip config properties
139                         //
140                         if (pipProperties != null) {
141                                 XACMLProperties.getProperties().putAll(pipProperties);
142                         }
143                 } catch (IOException e) {
144                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Failed to put init properties into Xacml properties");
145                 }
146                 //
147                 // Dump them
148                 //
149                 if (logger.isDebugEnabled()) {
150                         try {
151                                 logger.debug(XACMLProperties.getProperties().toString());                               
152                         } catch (IOException e) {
153                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Cannot dump properties");
154                         }
155                 }
156         }
157         
158         /**
159          * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging.
160          * 
161          * @param request - Servlet request (from a POST/GET/PUT/etc.)
162          */
163         public static void dumpRequest(HttpServletRequest request) {
164                 if (logger.isDebugEnabled()) {
165                         // special-case for receiving heartbeat - don't need to repeatedly output all of the information in multiple lines
166                         if ("GET".equals(request.getMethod()) && "hb".equals(request.getParameter("type"))  ) {
167                                 PolicyLogger.debug("GET type=hb : heartbeat received");
168                                 return;                         
169                         }
170                         logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " " + request.getRemotePort());
171                         logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
172                         Enumeration<String> en = request.getHeaderNames();
173                         logger.debug("Headers:");
174                         while (en.hasMoreElements()) {
175                                 String element = en.nextElement();
176                                 Enumeration<String> values = request.getHeaders(element);
177                                 while (values.hasMoreElements()) {
178                                         String value = values.nextElement();
179                                         logger.debug(element + ":" + value);
180                                 }
181                         }
182                         logger.debug("Attributes:");
183                         en = request.getAttributeNames();
184                         while (en.hasMoreElements()) {
185                                 String element = en.nextElement();
186                                 logger.debug(element + ":" + request.getAttribute(element));
187                         }
188                         logger.debug("ContextPath: " + request.getContextPath());
189                         if ("PUT".equals(request.getMethod()) || "POST".equals(request.getMethod())) {
190                                 // POST and PUT are allowed to have parameters in the content, but in our usage the parameters are always in the Query string.
191                                 // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it might contain a Policy file).
192                                 // Unfortunately the request.getParameterMap method reads the content to see if there are any parameters,
193                                 // and once the content is read it cannot be read again.
194                                 // Thus for PUT and POST we must avoid reading the content here so that the main code can read it.
195                                 logger.debug("Query String:" + request.getQueryString());
196                                 try {
197                                         if (request.getInputStream() == null) {
198                                                 logger.debug("Content: No content inputStream");
199                                         } else {
200                                                 logger.debug("Content available: " + request.getInputStream().available());
201                                         }
202                                 } catch (Exception e) {
203                                         logger.debug("Content: inputStream exception: " + e.getMessage() + ";  (May not be relevant)" +e);
204                                 }
205                         } else {
206                                 logger.debug("Parameters:");
207                                 Map<String, String[]> params = request.getParameterMap();
208                                 Set<String> keys = params.keySet();
209                                 for (String key : keys) {
210                                         String[] values = params.get(key);
211                                         logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : ""));
212                                 }
213                         }
214                         logger.debug("Request URL:" + request.getRequestURL());
215                 }
216         }
217 }