Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / admin / RESTfulPAPEngine.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP 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.openecomp.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.openecomp.policy.adapter.PolicyAdapter;
43 import org.openecomp.policy.rest.XACMLRestProperties;
44
45 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
46 import org.openecomp.policy.xacml.api.pap.EcompPDP;
47 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
48 import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine;
49 import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
50 import org.openecomp.policy.xacml.std.pap.StdPDP;
51 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
52 import org.openecomp.policy.xacml.std.pap.StdPDPItemSetChangeNotifier;
53 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
54 import org.openecomp.policy.xacml.std.pap.StdPDPStatus;
55 import com.att.research.xacml.api.pap.PAPEngine;
56 import com.att.research.xacml.api.pap.PAPException;
57 import com.att.research.xacml.api.pap.PDP;
58 import com.att.research.xacml.api.pap.PDPGroup;
59 //import com.att.research.xacml.api.pap.PDP;
60 //import com.att.research.xacml.api.pap.PDPGroup;
61 import com.att.research.xacml.api.pap.PDPPolicy;
62 import com.att.research.xacml.api.pap.PDPStatus;
63 import com.att.research.xacml.util.XACMLProperties;
64 import com.fasterxml.jackson.databind.DeserializationFeature;
65 import com.fasterxml.jackson.databind.ObjectMapper;
66 import com.fasterxml.jackson.databind.introspect.VisibilityChecker;
67 import com.fasterxml.jackson.databind.type.CollectionType;
68 import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
69 import org.openecomp.policy.common.logging.flexlogger.Logger;
70
71 /**
72  * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet
73  * through a RESTful interface
74  * 
75  *
76  */
77 public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
78         private static final Logger logger      = FlexLogger.getLogger(RESTfulPAPEngine.class);
79
80         //
81         // URL of the PAP Servlet that this Admin Console talks to
82         //
83         private String papServletURLString;
84         
85         /**
86          * Set up link with PAP Servlet and get our initial set of Groups
87          * @throws Exception 
88          */
89         public RESTfulPAPEngine (String myURLString) throws PAPException, IOException  {
90                 //
91                 // Get our URL to the PAP servlet
92                 //
93                 this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
94                 if (this.papServletURLString == null || this.papServletURLString.length() == 0) {
95                         String message = "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation.  Admin Console cannot call PAP.";
96                         logger.error(message);
97                         throw new PAPException(message);
98                 }
99
100                 //
101                 // register this Admin Console with the PAP Servlet to get updates
102                 //
103                 Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
104                 if (newURL != null) {
105                         // assume this was a re-direct and try again
106                         logger.warn("Redirecting to '" + newURL + "'");
107                         this.papServletURLString = (String)newURL;
108                         newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
109                         if (newURL != null) {
110                                 logger.error("Failed to redirect to " + this.papServletURLString);
111                                 throw new PAPException("Failed to register with PAP");
112                         }
113                 }
114         }
115         
116
117         //
118         // High-level commands used by the Admin Console code through the PAPEngine Interface
119         //
120         
121         @Override
122         public EcompPDPGroup getDefaultGroup() throws PAPException {
123                 EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "default=");
124                 return newGroup;
125         }
126
127         @Override
128         public void SetDefaultGroup(EcompPDPGroup group) throws PAPException {
129                 sendToPAP("POST", null, null, null, "groupId=" + group.getId(), "default=true");
130         }
131
132         @SuppressWarnings("unchecked")
133         @Override
134         public Set<EcompPDPGroup> getEcompPDPGroups() throws PAPException {
135                 Set<EcompPDPGroup> newGroupSet;
136                 newGroupSet = (Set<EcompPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, "groupId=");
137                 return Collections.unmodifiableSet(newGroupSet);
138         }
139
140
141         @Override
142         public EcompPDPGroup getGroup(String id) throws PAPException {
143                 EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=" + id);
144                 return newGroup;
145         }
146
147         @Override
148         public void newGroup(String name, String description)
149                         throws PAPException, NullPointerException {
150                 String escapedName = null;
151                 String escapedDescription = null;
152                 try {
153                         escapedName = URLEncoder.encode(name, "UTF-8");
154                         escapedDescription = URLEncoder.encode(description, "UTF-8");
155                 } catch (UnsupportedEncodingException e) {
156                         throw new PAPException("Unable to send name or description to PAP: " + e.getMessage());
157                 }
158                 
159                 this.sendToPAP("POST", null, null, null, "groupId=", "groupName="+escapedName, "groupDescription=" + escapedDescription);
160         }
161         
162         
163         /**
164          * Update the configuration on the PAP for a single Group.
165          * 
166          * @param group
167          * @return
168          * @throws PAPException
169          */
170         public void updateGroup(EcompPDPGroup group) throws PAPException {
171
172                 try {
173                         
174                         //
175                         // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP!
176                         //
177                         // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace.
178                         // 
179                         
180                         
181 //                      // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory.
182 //                      // This is not efficient since most of the policies will already exist there.
183 //                      // 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.
184 //                      
185                         
186                         // now update the group object on the PAP
187                         
188                         sendToPAP("PUT", group, null, null, "groupId=" + group.getId());
189                 } catch (Exception e) {
190                         String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
191                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
192                         throw new PAPException(message);
193                 }
194         }
195         
196         
197         @Override
198         public void removeGroup(EcompPDPGroup group, EcompPDPGroup newGroup)
199                         throws PAPException, NullPointerException {
200                 String moveToGroupString = null;
201                 if (newGroup != null) {
202                         moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
203                 }
204                 sendToPAP("DELETE", null, null, null, "groupId=" + group.getId(), moveToGroupString);
205         }
206         
207         @Override
208         public EcompPDPGroup getPDPGroup(EcompPDP pdp) throws PAPException {
209                 return getPDPGroup(pdp.getId());
210         }
211
212         
213         public EcompPDPGroup getPDPGroup(String pdpId) throws PAPException {
214                 EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "pdpId=" + pdpId, "getPDPGroup=");
215                 return newGroup;
216         }
217
218         @Override
219         public EcompPDP getPDP(String pdpId) throws PAPException {
220                 EcompPDP newPDP = (EcompPDP)sendToPAP("GET", null, null, StdPDP.class, "groupId=", "pdpId=" + pdpId);
221                 return newPDP;
222         }
223         
224         @Override
225         public void newPDP(String id, EcompPDPGroup group, String name, String description, int jmxport) throws PAPException,
226                         NullPointerException {
227                 StdPDP newPDP = new StdPDP(id, name, description, jmxport);
228                 sendToPAP("PUT", newPDP, null, null, "groupId=" + group.getId(), "pdpId=" + id);
229                 return;
230         }
231
232         @Override
233         public void movePDP(EcompPDP pdp, EcompPDPGroup newGroup) throws PAPException {
234                 sendToPAP("POST", null, null, null, "groupId=" + newGroup.getId(), "pdpId=" + pdp.getId());
235                 return;
236         }
237
238         @Override
239         public void updatePDP(EcompPDP pdp) throws PAPException {
240                 EcompPDPGroup group = getPDPGroup(pdp);
241                 sendToPAP("PUT", pdp, null, null, "groupId=" + group.getId(), "pdpId=" + pdp.getId());
242                 return;
243         }
244         
245         @Override
246         public void removePDP(EcompPDP pdp) throws PAPException {
247                 EcompPDPGroup group = getPDPGroup(pdp);
248                 sendToPAP("DELETE", null, null, null, "groupId=" + group.getId(), "pdpId=" + pdp.getId());
249                 return;
250         }
251         
252         //Validate the Policy Data
253         public boolean validatePolicyRequest(PolicyAdapter policyAdapter, String policyType) throws PAPException {
254                 Boolean isValidData = false;
255 /*              StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getConfigName(),
256                                 policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getConfigBodyData(), policyAdapter.getPolicyID(), policyAdapter.getRuleID(), 
257                                 policyAdapter.getRuleCombiningAlgId(), policyAdapter.getParentPath().toString(), policyAdapter.getGitPath().toString(), policyAdapter.getConfigType(), policyAdapter.isEditPolicy());
258                 */
259                 
260                 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base");
261                 
262                 //send JSON object to PAP
263                 isValidData = (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType);
264                 return isValidData;
265         }
266         
267         //create a new policy
268         @SuppressWarnings("unchecked")
269         public Map<String, String> createPolicyRequest(PolicyAdapter policyAdapter) throws PAPException {
270                 Map<String, String> successMap = new HashMap<String, String>(); 
271                 StdPAPPolicy newPAPPolicy = null;
272                 
273                 if (policyAdapter.getPolicyType().equalsIgnoreCase("Config")) {
274                         
275                         if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Firewall Config")) {
276                                 
277                                 //create StdPAPPolicy object for Config Firewall Policy
278                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
279                                                 policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getJsonBody(), 
280                                                 policyAdapter.getHighestVersion() ,policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate());
281
282                         }
283                         else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Raw")) {
284                                 
285                                 //create StdPAPPolicy object for BRMS_Raw Policy
286                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
287                                                 policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), 
288                                                 policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getRiskLevel(), 
289                                                 policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate());
290
291                         }
292                         else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Param")) {
293                 
294                                 //create StdPAPPolicy object for BRMS_Param Policy
295                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
296                                                 policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), 
297                                                 policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getBRMSParamBody(),
298                                                 policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate());
299                         
300                         }
301         
302                         else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Base")) {
303                                 
304                                 //create StdPAPPolicy object for Config Base Policy
305                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
306                                                 policyAdapter.getEcompName(), policyAdapter.getConfigName(), policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getConfigType(), 
307                                                 policyAdapter.getConfigBodyData(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),
308                                                 policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate());
309                                 
310                         }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")) {
311                                 
312                                 //create StdPAPPolicy object for CloseLoop Fault Policy
313                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
314                                                 policyAdapter.getEcompName(), policyAdapter.getJsonBody(),  policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), null, policyAdapter.isEditPolicy(), 
315                                                 policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),
316                                                 policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate());
317                                 
318                         }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_PM")) {
319                                 
320                                 //create StdPAPPolicy object for CloseLoop PM Policy
321                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
322                                                 policyAdapter.getEcompName(), policyAdapter.getJsonBody(),  policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), policyAdapter.getServiceType(), 
323                                                 policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), 
324                                                 policyAdapter.getGuard(),policyAdapter.getTtlDate());
325                                 
326                         }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("DCAE Micro Service")) {
327                                 
328                                 //create StdPAPPolicy object for DCAE Micro Service Policy
329                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
330                                                 policyAdapter.getEcompName(), policyAdapter.getConfigName(), policyAdapter.getServiceType(), policyAdapter.getUuid(), policyAdapter.getLocation(), 
331                         policyAdapter.getJsonBody(), policyAdapter.getPriority(), null, policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), 
332                         policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate());
333                                 
334                         }
335                 } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Action")) {
336                         
337                         //create StdPAPPolicy object for Action Policy
338                         newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getDynamicFieldConfigAttributes(),
339                                         policyAdapter.getDynamicRuleAlgorithmLabels(), policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), 
340                                         policyAdapter.getDynamicRuleAlgorithmField2(), policyAdapter.getActionPerformer(), policyAdapter.getActionAttribute(),
341                                         policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion());
342                         
343                 } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Decision")) {
344                         
345                         //create StdPAPPolicy object for Decision Policy 
346                         newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getRuleProvider(), 
347                                         policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getDynamicSettingsMap(), policyAdapter.getDynamicRuleAlgorithmLabels(), 
348                                         policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), policyAdapter.getDynamicRuleAlgorithmField2(), 
349                                         policyAdapter.getDropDownMap(), policyAdapter.getDynamicVariableList(), policyAdapter.getDataTypeList(), policyAdapter.isEditPolicy(), 
350                                         policyAdapter.getDomainDir(), policyAdapter.getHighestVersion());
351                         
352                 }
353                 
354                 //send JSON object to PAP
355                 successMap = (Map<String, String>) sendToPAP("PUT", newPAPPolicy, null, null, "operation=create", "apiflag=admin", "policyType=" + policyAdapter.getPolicyType());
356                 return successMap;
357                 
358                 
359         }
360         
361         //update an existing policy
362         @SuppressWarnings("unchecked")
363         public Map<String, String> updatePolicyRequest(PolicyAdapter policyAdapter) throws PAPException {
364                 Map<String, String> successMap = new HashMap<String, String>();         
365                 StdPAPPolicy newPAPPolicy = null;
366                 
367                 if (policyAdapter.getPolicyType().equalsIgnoreCase("Config")) {
368                         
369                         if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Firewall Config")) {
370                                 
371                                 //create StdPAPPolicy object for Firewall Config Policy 
372                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getConfigName(),
373                                                 policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getPolicyID(),
374                                                 policyAdapter.getRuleID(), policyAdapter.getVersion(), policyAdapter.getJsonBody(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), 
375                                                 policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate());
376                                 
377                         } 
378                         else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Raw")) {
379                                 //create StdPAPPolicy object for BRMS_Raw Policy
380                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
381                                                 policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), 
382                                                 policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getRiskLevel(), 
383                                                 policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate());
384                                 
385                         }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Param")) {
386                                 //create StdPAPPolicy object for BRMS_Raw Policy
387                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
388                                                 policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), 
389                                                 policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getBRMSParamBody(),
390                                                 policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate());
391                                 
392                         }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Base")) {
393                                 
394                                 //create StdPAPPolicy object for Config Base Policy 
395                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getConfigName(),
396                                                 policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getConfigBodyData(), policyAdapter.getPolicyID(), policyAdapter.getRuleID(), 
397                                                 policyAdapter.getConfigType(), policyAdapter.isEditPolicy(), policyAdapter.getVersion(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), 
398                                                 policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate());
399                                 
400                         }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")) {
401                                 
402                                 //create StdPAPPolicy object for CloseLoop Fault Policy
403                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
404                                                 policyAdapter.getEcompName(), policyAdapter.getJsonBody(),  policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), null, policyAdapter.isEditPolicy(), 
405                                                 policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),
406                                                 policyAdapter.getTtlDate());
407                                 
408                         }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_PM")) {
409                                 
410                                 //create StdPAPPolicy object for CloseLoop PM Policy
411                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
412                                                 policyAdapter.getEcompName(), policyAdapter.getJsonBody(), policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), policyAdapter.getServiceType(), 
413                                                 policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), 
414                                                 policyAdapter.getGuard(),policyAdapter.getTtlDate());
415                                 
416                         }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("DCAE Micro Service")) {
417                                 
418                                 //create StdPAPPolicy object for DCAE Micro Service Policy
419                                 newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), 
420                                                 policyAdapter.getEcompName(), policyAdapter.getConfigName(), policyAdapter.getServiceType(), policyAdapter.getUuid(), policyAdapter.getLocation(), 
421                         policyAdapter.getJsonBody(), policyAdapter.getPriority(), null, policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),
422                         policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate());
423                                 
424                         }
425                 } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Action")) {
426                         
427                         //create StdPAPPolicy object for Action Policy 
428                         newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getDynamicFieldConfigAttributes(),
429                                         policyAdapter.getDynamicRuleAlgorithmLabels(), policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), 
430                                         policyAdapter.getDynamicRuleAlgorithmField2(), policyAdapter.getActionPerformer(), policyAdapter.getActionAttribute(),
431                                         policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion());
432                         
433                 } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Decision")) {
434                         
435                         //create StdPAPPolicy object for Decision Policy 
436                         newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getRuleProvider(),
437                                         policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getDynamicSettingsMap(), policyAdapter.getDynamicRuleAlgorithmLabels(), 
438                                         policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), policyAdapter.getDynamicRuleAlgorithmField2(), 
439                                         policyAdapter.getDropDownMap(), policyAdapter.getDynamicVariableList(), policyAdapter.getDataTypeList(), policyAdapter.isEditPolicy(), 
440                                         policyAdapter.getDomainDir(), policyAdapter.getHighestVersion());
441                         
442                 }
443                 
444                 //send JSON object to PAP
445                 successMap = (Map<String, String>) sendToPAP("PUT", newPAPPolicy, null, null, "operation=update", "apiflag=admin", "policyType=" + policyAdapter.getPolicyType());
446                 return successMap;
447         }
448         
449         @Override
450         public void publishPolicy(String id, String name, boolean isRoot,
451                         InputStream policy, EcompPDPGroup group) throws PAPException {
452                 
453
454                 // copy the (one) file into the target directory on the PAP servlet
455                 copyFile(id, group, policy);
456                 
457                 // adjust the local copy of the group to include the new policy
458                 PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
459                 group.getPolicies().add(pdpPolicy);
460                 
461                 // tell the PAP servlet to include the policy in the configuration
462                 updateGroup(group);
463                                 
464                 return;
465         }
466         
467         
468         
469         /**
470          * Copy a single Policy file from the input stream to the PAP Servlet.
471          * Either this works (silently) or it throws an exception.
472          * 
473          * @param policyId
474          * @param group
475          * @param policy
476          * @return
477          * @throws PAPException
478          */
479         public void copyFile(String policyId, EcompPDPGroup group, InputStream policy) throws PAPException {
480                 // send the policy file to the PAP Servlet
481                 try {
482                         sendToPAP("POST", policy, null, null, "groupId=" + group.getId(), "policyId="+policyId);
483                 } catch (Exception e) {
484                         String message = "Unable to PUT policy '" + policyId + "', e:" + e;
485                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
486                         throw new PAPException(message);
487                 }
488         }
489         
490
491         @Override
492         public void     copyPolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException {
493                 if (policy == null || group == null) {
494                         throw new PAPException("Null input policy="+policy+"  group="+group);
495                 }
496                 try (InputStream is = new FileInputStream(new File(policy.getLocation())) ) {
497                         copyFile(policy.getId(), group, is );
498                 } catch (Exception e) {
499                         String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
500                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
501                         throw new PAPException(message);
502                 }
503         }
504
505
506         
507         
508         @Override
509         public void     removePolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException {
510                 throw new PAPException("NOT IMPLEMENTED");
511
512         }
513
514         
515         
516         /**
517          * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly
518          * to get detailed status info.
519          * 
520          * @param pdp
521          * @return
522          * @throws PAPException 
523          */
524         
525         public PDPStatus getStatus(EcompPDP pdp) throws PAPException {
526                 StdPDPStatus status = (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class);
527                 return status;
528         }
529         
530         
531         
532         
533         //
534         // Internal Operations called by the PAPEngine Interface methods
535         //
536         
537         /**
538          * Send a request to the PAP Servlet and get the response.
539          * 
540          * The content is either an InputStream to be copied to the Request OutputStream
541          *      OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream.
542          * 
543          * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
544          * 
545          * @param method
546          * @param content       - EITHER an InputStream OR an Object to be encoded in JSON
547          * @param collectionTypeClass
548          * @param responseContentClass
549          * @param parameters
550          * @return
551          * @throws Exception
552          */
553         private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException {
554                 HttpURLConnection connection = null;
555                 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
556                 logger.info("User Id is " + papID);
557                 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
558                 logger.info("Pass is: " + papPass);
559                 Base64.Encoder encoder = Base64.getEncoder();
560                 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
561                 logger.info("Encoding for the PAP is: " + encoding);
562                 try {
563                         String fullURL = papServletURLString;
564                         if (parameters != null && parameters.length > 0) {
565                                 String queryString = "";
566                                 for (String p : parameters) {
567                                         queryString += "&" + p;
568                                 }
569                                 fullURL += "?" + queryString.substring(1);
570                         }
571                         
572                         // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
573                         if (method.equals("GET") &&     (content instanceof EcompPDP) &&        responseContentClass == StdPDPStatus.class) {
574                                 // Adjust the url and properties appropriately
575                                 String pdpID =((EcompPDP)content).getId(); 
576                                 fullURL = pdpID + "?type=Status";
577                                 content = null;
578                                 if(CheckPDP.validateID(pdpID)){
579                                         encoding = CheckPDP.getEncoding(pdpID);
580                                 }
581                         }
582                         
583                         
584                         URL url = new URL(fullURL);
585
586                         //
587                         // Open up the connection
588                         //
589                         connection = (HttpURLConnection)url.openConnection();
590                         //
591                         // Setup our method and headers
592                         //
593             connection.setRequestMethod(method);
594 //                              connection.setRequestProperty("Accept", "text/x-java-properties");
595 //                  connection.setRequestProperty("Content-Type", "text/x-java-properties");
596             connection.setUseCaches(false);
597             //
598             // Adding this in. It seems the HttpUrlConnection class does NOT
599             // properly forward our headers for POST re-direction. It does so
600             // for a GET re-direction.
601             //
602             // So we need to handle this ourselves.
603             //
604             connection.setInstanceFollowRedirects(false);
605             connection.setRequestProperty("Authorization", "Basic " + encoding);
606                         connection.setDoOutput(true);
607                         connection.setDoInput(true);
608                         
609                         if (content != null) {
610                                 if (content instanceof InputStream) {
611                                 try {
612                                         //
613                                         // Send our current policy configuration
614                                         //
615                                         try (OutputStream os = connection.getOutputStream()) {
616                                                 int count = IOUtils.copy((InputStream)content, os);
617                                                 if (logger.isDebugEnabled()) {
618                                                         logger.debug("copied to output, bytes="+count);
619                                                 }
620                                         }
621                                 } catch (Exception e) {
622                                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
623                                         throw e;
624                                 }
625                                 } else {
626                                         // The content is an object to be encoded in JSON
627                             ObjectMapper mapper = new ObjectMapper();
628                             mapper.writeValue(connection.getOutputStream(),  content);
629                                 }
630                         }
631             //
632             // Do the connect
633             //
634             connection.connect();
635             if (connection.getResponseCode() == 204) {
636                 logger.info("Success - no content.");
637                 return null;
638             } else if (connection.getResponseCode() == 200) {
639                 logger.info("Success. We have a return object.");
640                 String isValidData = connection.getHeaderField("isValidData");
641                 String isSuccess = connection.getHeaderField("successMapKey");
642                 Map<String, String> successMap = new HashMap<String, String>();
643                 if (isValidData != null && isValidData.equalsIgnoreCase("true")){
644                     logger.info("Policy Data is valid.");       
645                         return true;
646                 } else if (isValidData != null && isValidData.equalsIgnoreCase("false")) {
647                     logger.info("Policy Data is invalid.");     
648                         return false;
649                 } else if (isSuccess != null && isSuccess.equalsIgnoreCase("success")) {
650                         logger.info("Policy Created Successfully!" );
651                         String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
652                         successMap.put("success", finalPolicyPath);
653                         return successMap;
654                 } else if (isSuccess != null && isSuccess.equalsIgnoreCase("error")) {
655                         logger.info("There was an error while creating the policy!");
656                         successMap.put("error", "error");
657                         return successMap;
658                 } else {
659                         // get the response content into a String
660                         String json = null;
661                                 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
662                             java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
663                             scanner.useDelimiter("\\A");
664                             json =  scanner.hasNext() ? scanner.next() : "";
665                             scanner.close();
666                             logger.info("JSON response from PAP: " + json);
667                         
668                         // convert Object sent as JSON into local object
669                             ObjectMapper mapper = new ObjectMapper();
670                             mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
671                             if (collectionTypeClass != null) {
672                                 // collection of objects expected
673                                 final CollectionType javaType = 
674                                       mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass);
675         
676                                 Object objectFromJSON = mapper.readValue(json, javaType);
677                                                 return objectFromJSON;
678                             } else {
679                                 // single value object expected
680                                     Object objectFromJSON = mapper.readValue(json, responseContentClass);
681                                                 return objectFromJSON;
682                             }
683                 }
684
685             } else if (connection.getResponseCode() >= 300 && connection.getResponseCode()  <= 399) {
686                 // redirection
687                 String newURL = connection.getHeaderField("Location");
688                 if (newURL == null) {
689                         logger.error("No Location header to redirect to when response code="+connection.getResponseCode());
690                         throw new IOException("No redirect Location header when response code="+connection.getResponseCode());
691                 }
692                 int qIndex = newURL.indexOf("?");
693                 if (qIndex > 0) {
694                         newURL = newURL.substring(0, qIndex);
695                 }
696                 logger.info("Redirect seen.  Redirecting " + fullURL + " to " + newURL);
697                 return newURL;
698             } else {
699                 logger.warn("Unexpected response code: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
700                 throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
701             }
702
703                 } catch (Exception e) {
704                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e);
705                         throw new PAPException("Request/Response threw :" + e);
706                 } finally {
707                         // cleanup the connection
708                                 if (connection != null) {
709                                 try {
710                                         // For some reason trying to get the inputStream from the connection
711                                         // throws an exception rather than returning null when the InputStream does not exist.
712                                         InputStream is = null;
713                                         try {
714                                                 is = connection.getInputStream();
715                                         } catch (Exception e1) {
716                                                 // ignore this
717                                         }
718                                         if (is != null) {
719                                                 is.close();
720                                         }
721
722                                 } catch (IOException ex) {
723                                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
724                                 }
725                                 connection.disconnect();
726                         }
727                 }
728         }
729
730 }
731
732