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