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