[POLICY-73] replace openecomp for policy-engine
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / admin / RESTfulPAPEngine.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.admin;
22
23
24
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.OutputStream;
30 import java.io.UnsupportedEncodingException;
31 import java.net.HttpURLConnection;
32 import java.net.URL;
33 import java.net.URLEncoder;
34 import java.nio.charset.StandardCharsets;
35 import java.util.Base64;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.Map;
39 import java.util.Set;
40
41 import org.apache.commons.io.IOUtils;
42 import org.onap.policy.rest.XACMLRestProperties;
43 import org.onap.policy.rest.adapter.PolicyRestAdapter;
44 import org.onap.policy.xacml.api.XACMLErrorConstants;
45 import org.onap.policy.xacml.api.pap.OnapPDP;
46 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
47 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
48 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
49 import org.onap.policy.xacml.std.pap.StdPDP;
50 import org.onap.policy.xacml.std.pap.StdPDPGroup;
51 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier;
52 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
53 import org.onap.policy.xacml.std.pap.StdPDPStatus;
54 import com.att.research.xacml.api.pap.PAPException;
55 import com.att.research.xacml.api.pap.PDPPolicy;
56 import com.att.research.xacml.api.pap.PDPStatus;
57 import com.att.research.xacml.util.XACMLProperties;
58 import com.fasterxml.jackson.databind.DeserializationFeature;
59 import com.fasterxml.jackson.databind.ObjectMapper;
60 import com.fasterxml.jackson.databind.type.CollectionType;
61 import org.onap.policy.common.logging.flexlogger.FlexLogger; 
62 import org.onap.policy.common.logging.flexlogger.Logger;
63
64 /**
65  * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet
66  * through a RESTful interface
67  * 
68  *
69  */
70 public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
71         private static final Logger LOGGER      = FlexLogger.getLogger(RESTfulPAPEngine.class);
72         
73         private static final String groupID = "groupId=";
74
75         //
76         // URL of the PAP Servlet that this Admin Console talks to
77         //
78         private String papServletURLString;
79         
80         /**
81          * Set up link with PAP Servlet and get our initial set of Groups
82          * @throws Exception 
83          */
84         public RESTfulPAPEngine (String myURLString) throws PAPException, IOException  {
85                 //
86                 // Get our URL to the PAP servlet
87                 //
88                 this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
89                 if (this.papServletURLString == null || this.papServletURLString.length() == 0) {
90                         String message = "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation.  Admin Console cannot call PAP.";
91                         LOGGER.error(message);
92                         throw new PAPException(message);
93                 }
94
95                 //
96                 // register this Admin Console with the PAP Servlet to get updates
97                 //
98                 Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
99                 if (newURL != null) {
100                         // assume this was a re-direct and try again
101                         LOGGER.warn("Redirecting to '" + newURL + "'");
102                         this.papServletURLString = (String)newURL;
103                         newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
104                         if (newURL != null) {
105                                 LOGGER.error("Failed to redirect to " + this.papServletURLString);
106                                 throw new PAPException("Failed to register with PAP");
107                         }
108                 }
109         }
110         
111
112         //
113         // High-level commands used by the Admin Console code through the PAPEngine Interface
114         //
115         
116         @Override
117         public OnapPDPGroup getDefaultGroup() throws PAPException {
118                 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "default=");
119         }
120
121         @Override
122         public void SetDefaultGroup(OnapPDPGroup group) throws PAPException {
123                 sendToPAP("POST", null, null, null, groupID + group.getId(), "default=true");
124         }
125
126         @SuppressWarnings("unchecked")
127         @Override
128         public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException {
129                 Set<OnapPDPGroup> newGroupSet;
130                 newGroupSet = (Set<OnapPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, groupID);
131                 return Collections.unmodifiableSet(newGroupSet);
132         }
133
134
135         @Override
136         public OnapPDPGroup getGroup(String id) throws PAPException {
137                 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id);
138         }
139
140         @Override
141         public void newGroup(String name, String description)
142                         throws PAPException, NullPointerException {
143                 String escapedName = null;
144                 String escapedDescription = null;
145                 try {
146                         escapedName = URLEncoder.encode(name, "UTF-8");
147                         escapedDescription = URLEncoder.encode(description, "UTF-8");
148                 } catch (UnsupportedEncodingException e) {
149                         throw new PAPException("Unable to send name or description to PAP: " + e.getMessage()  +e);
150                 }
151                 
152                 this.sendToPAP("POST", null, null, null, groupID, "groupName="+escapedName, "groupDescription=" + escapedDescription);
153         }
154         
155         
156         /**
157          * Update the configuration on the PAP for a single Group.
158          * 
159          * @param group
160          * @return
161          * @throws PAPException
162          */
163         public void updateGroup(OnapPDPGroup group) throws PAPException {
164
165                 try {
166                         
167                         //
168                         // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP!
169                         //
170                         // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace.
171                         // 
172                         
173                         
174                         // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory.
175                         // This is not efficient since most of the policies will already exist there.
176                         // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any corrupted files on the PAP get refreshed.
177                 
178                         
179                         // now update the group object on the PAP
180                         
181                         sendToPAP("PUT", group, null, null, groupID + group.getId());
182                 } catch (Exception e) {
183                         String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
184                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
185                         throw new PAPException(message);
186                 }
187         }
188         
189         
190         @Override
191         public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup)
192                         throws PAPException, NullPointerException {
193                 String moveToGroupString = null;
194                 if (newGroup != null) {
195                         moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
196                 }
197                 sendToPAP("DELETE", null, null, null, groupID + group.getId(), moveToGroupString);
198         }
199         
200         @Override
201         public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException {
202                 return getPDPGroup(pdp.getId());
203         }
204
205         
206         public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
207                 return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup=");
208         }
209
210         @Override
211         public OnapPDP getPDP(String pdpId) throws PAPException {
212                 return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId);
213         }
214         
215         @Override
216         public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException,
217                         NullPointerException {
218                 StdPDP newPDP = new StdPDP(id, name, description, jmxport);
219                 sendToPAP("PUT", newPDP, null, null, groupID + group.getId(), "pdpId=" + id);
220                 return;
221         }
222
223         @Override
224         public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
225                 sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId());
226                 return;
227         }
228
229         @Override
230         public void updatePDP(OnapPDP pdp) throws PAPException {
231                 OnapPDPGroup group = getPDPGroup(pdp);
232                 sendToPAP("PUT", pdp, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
233                 return;
234         }
235         
236         @Override
237         public void removePDP(OnapPDP pdp) throws PAPException {
238                 OnapPDPGroup group = getPDPGroup(pdp);
239                 sendToPAP("DELETE", null, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
240                 return;
241         }
242         
243         //Validate the Policy Data
244         public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
245                 Boolean isValidData = false;
246                 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base");
247                 
248                 //send JSON object to PAP
249                 isValidData = (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType);
250                 return isValidData;
251         }
252         
253         
254         
255         @Override
256         public void publishPolicy(String id, String name, boolean isRoot,
257                         InputStream policy, OnapPDPGroup group) throws PAPException {
258                 
259
260                 // copy the (one) file into the target directory on the PAP servlet
261                 copyFile(id, group, policy);
262                 
263                 // adjust the local copy of the group to include the new policy
264                 PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
265                 group.getPolicies().add(pdpPolicy);
266                 
267                 // tell the PAP servlet to include the policy in the configuration
268                 updateGroup(group);
269                                 
270                 return;
271         }
272         
273         /**
274          * Copy a single Policy file from the input stream to the PAP Servlet.
275          * Either this works (silently) or it throws an exception.
276          * 
277          * @param policyId
278          * @param group
279          * @param policy
280          * @return
281          * @throws PAPException
282          */
283         public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
284                 // send the policy file to the PAP Servlet
285                 try {
286                         sendToPAP("POST", policy, null, null, groupID + group.getId(), "policyId="+policyId);
287                 } catch (Exception e) {
288                         String message = "Unable to PUT policy '" + policyId + "', e:" + e;
289                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
290                         throw new PAPException(message);
291                 }
292         }
293         
294
295         @Override
296         public void     copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
297                 if (policy == null || group == null) {
298                         throw new PAPException("Null input policy="+policy+"  group="+group);
299                 }
300                 try (InputStream is = new FileInputStream(new File(policy.getLocation())) ) {
301                         copyFile(policy.getId(), group, is );
302                 } catch (Exception e) {
303                         String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
304                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
305                         throw new PAPException(message);
306                 }
307         }
308         
309         @Override
310         public void     removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
311                 throw new PAPException("NOT IMPLEMENTED");
312
313         }
314
315         
316         /**
317          * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly
318          * to get detailed status info.
319          * 
320          * @param pdp
321          * @return
322          * @throws PAPException 
323          */
324         
325         public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
326                 return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class);
327         }
328         
329         
330         //
331         // Internal Operations called by the PAPEngine Interface methods
332         //
333         
334         /**
335          * Send a request to the PAP Servlet and get the response.
336          * 
337          * The content is either an InputStream to be copied to the Request OutputStream
338          *      OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream.
339          * 
340          * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
341          * 
342          * @param method
343          * @param content       - EITHER an InputStream OR an Object to be encoded in JSON
344          * @param collectionTypeClass
345          * @param responseContentClass
346          * @param parameters
347          * @return
348          * @throws Exception
349          */
350         @SuppressWarnings({ "rawtypes", "unchecked" })
351         private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException {
352                 HttpURLConnection connection = null;
353                 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
354                 LOGGER.info("User Id is " + papID);
355                 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
356                 Base64.Encoder encoder = Base64.getEncoder();
357                 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
358                 LOGGER.info("Encoding for the PAP is: " + encoding);
359                 try {
360                         String fullURL = papServletURLString;
361                         if (parameters != null && parameters.length > 0) {
362                                 String queryString = "";
363                                 for (String p : parameters) {
364                                         queryString += "&" + p;
365                                 }
366                                 fullURL += "?" + queryString.substring(1);
367                         }
368                         
369                         // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
370                         if (method.equals("GET") &&     (content instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) {
371                                 // Adjust the url and properties appropriately
372                                 String pdpID =((OnapPDP)content).getId(); 
373                                 fullURL = pdpID + "?type=Status";
374                                 content = null;
375                                 if(CheckPDP.validateID(pdpID)){
376                                         encoding = CheckPDP.getEncoding(pdpID);
377                                 }
378                         }
379                         
380                         
381                         URL url = new URL(fullURL);
382
383                         //
384                         // Open up the connection
385                         //
386                         connection = (HttpURLConnection)url.openConnection();
387                         //
388                         // Setup our method and headers
389                         //
390             connection.setRequestMethod(method);
391             connection.setUseCaches(false);
392             //
393             // Adding this in. It seems the HttpUrlConnection class does NOT
394             // properly forward our headers for POST re-direction. It does so
395             // for a GET re-direction.
396             //
397             // So we need to handle this ourselves.
398             //
399             connection.setInstanceFollowRedirects(false);
400             connection.setRequestProperty("Authorization", "Basic " + encoding);
401                         connection.setDoOutput(true);
402                         connection.setDoInput(true);
403                         
404                         if (content != null) {
405                                 if (content instanceof InputStream) {
406                                 try {
407                                         //
408                                         // Send our current policy configuration
409                                         //
410                                         try (OutputStream os = connection.getOutputStream()) {
411                                                 int count = IOUtils.copy((InputStream)content, os);
412                                                 if (LOGGER.isDebugEnabled()) {
413                                                         LOGGER.debug("copied to output, bytes="+count);
414                                                 }
415                                         }
416                                 } catch (Exception e) {
417                                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
418                                 }
419                                 } else {
420                                         // The content is an object to be encoded in JSON
421                             ObjectMapper mapper = new ObjectMapper();
422                             mapper.writeValue(connection.getOutputStream(),  content);
423                                 }
424                         }
425             //
426             // Do the connect
427             //
428             connection.connect();
429             if (connection.getResponseCode() == 204) {
430                 LOGGER.info("Success - no content.");
431                 return null;
432             } else if (connection.getResponseCode() == 200) {
433                 LOGGER.info("Success. We have a return object.");
434                 String isValidData = connection.getHeaderField("isValidData");
435                 String isSuccess = connection.getHeaderField("successMapKey");
436                 Map<String, String> successMap = new HashMap<>();
437                 if (isValidData != null && isValidData.equalsIgnoreCase("true")){
438                     LOGGER.info("Policy Data is valid.");       
439                         return true;
440                 } else if (isValidData != null && isValidData.equalsIgnoreCase("false")) {
441                     LOGGER.info("Policy Data is invalid.");     
442                         return false;
443                 } else if (isSuccess != null && isSuccess.equalsIgnoreCase("success")) {
444                         LOGGER.info("Policy Created Successfully!" );
445                         String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
446                         successMap.put("success", finalPolicyPath);
447                         return successMap;
448                 } else if (isSuccess != null && isSuccess.equalsIgnoreCase("error")) {
449                         LOGGER.info("There was an error while creating the policy!");
450                         successMap.put("error", "error");
451                         return successMap;
452                 } else {
453                         // get the response content into a String
454                         String json = null;
455                                 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
456                             java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
457                             scanner.useDelimiter("\\A");
458                             json =  scanner.hasNext() ? scanner.next() : "";
459                             scanner.close();
460                             LOGGER.info("JSON response from PAP: " + json);
461                         
462                         // convert Object sent as JSON into local object
463                             ObjectMapper mapper = new ObjectMapper();
464                             mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
465                             if (collectionTypeClass != null) {
466                                 // collection of objects expected
467                                 final CollectionType javaType = 
468                                       mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass);
469         
470                                 Object objectFromJSON = mapper.readValue(json, javaType);
471                                                 return objectFromJSON;
472                             } else {
473                                 // single value object expected
474                                     Object objectFromJSON = mapper.readValue(json, responseContentClass);
475                                                 return objectFromJSON;
476                             }
477                 }
478
479             } else if (connection.getResponseCode() >= 300 && connection.getResponseCode()  <= 399) {
480                 // redirection
481                 String newURL = connection.getHeaderField("Location");
482                 if (newURL == null) {
483                         LOGGER.error("No Location header to redirect to when response code="+connection.getResponseCode());
484                         throw new IOException("No redirect Location header when response code="+connection.getResponseCode());
485                 }
486                 int qIndex = newURL.indexOf("?");
487                 if (qIndex > 0) {
488                         newURL = newURL.substring(0, qIndex);
489                 }
490                 LOGGER.info("Redirect seen.  Redirecting " + fullURL + " to " + newURL);
491                 return newURL;
492             } else {
493                 LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
494                 throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
495             }
496
497                 } catch (Exception e) {
498                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e);
499                         throw new PAPException("Request/Response threw :" + e);
500                 } finally {
501                         // cleanup the connection
502                         if (connection != null) {
503                                 try {
504                                         // For some reason trying to get the inputStream from the connection
505                                         // throws an exception rather than returning null when the InputStream does not exist.
506                                         InputStream is = connection.getInputStream();
507                                         if (is != null) {
508                                                 is.close();
509                                         }
510                                 } catch (IOException ex) {
511                                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
512                                 }
513                                 connection.disconnect();
514                         }
515                 }
516         }
517 }