2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.policy.admin;
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;
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;
41 import org.apache.commons.io.IOUtils;
42 import org.openecomp.policy.adapter.PolicyAdapter;
43 import org.openecomp.policy.rest.XACMLRestProperties;
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;
72 * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet
73 * through a RESTful interface
77 public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
78 private static final Logger logger = FlexLogger.getLogger(RESTfulPAPEngine.class);
81 // URL of the PAP Servlet that this Admin Console talks to
83 private String papServletURLString;
86 * Set up link with PAP Servlet and get our initial set of Groups
89 public RESTfulPAPEngine (String myURLString) throws PAPException, IOException {
91 // Get our URL to the PAP servlet
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);
101 // register this Admin Console with the PAP Servlet to get updates
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");
118 // High-level commands used by the Admin Console code through the PAPEngine Interface
122 public EcompPDPGroup getDefaultGroup() throws PAPException {
123 EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "default=");
128 public void SetDefaultGroup(EcompPDPGroup group) throws PAPException {
129 sendToPAP("POST", null, null, null, "groupId=" + group.getId(), "default=true");
132 @SuppressWarnings("unchecked")
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);
142 public EcompPDPGroup getGroup(String id) throws PAPException {
143 EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=" + id);
148 public void newGroup(String name, String description)
149 throws PAPException, NullPointerException {
150 String escapedName = null;
151 String escapedDescription = null;
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());
159 this.sendToPAP("POST", null, null, null, "groupId=", "groupName="+escapedName, "groupDescription=" + escapedDescription);
164 * Update the configuration on the PAP for a single Group.
168 * @throws PAPException
170 public void updateGroup(EcompPDPGroup group) throws PAPException {
175 // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP!
177 // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace.
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.
186 // now update the group object on the PAP
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);
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();
204 sendToPAP("DELETE", null, null, null, "groupId=" + group.getId(), moveToGroupString);
208 public EcompPDPGroup getPDPGroup(EcompPDP pdp) throws PAPException {
209 return getPDPGroup(pdp.getId());
213 public EcompPDPGroup getPDPGroup(String pdpId) throws PAPException {
214 EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "pdpId=" + pdpId, "getPDPGroup=");
219 public EcompPDP getPDP(String pdpId) throws PAPException {
220 EcompPDP newPDP = (EcompPDP)sendToPAP("GET", null, null, StdPDP.class, "groupId=", "pdpId=" + pdpId);
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);
233 public void movePDP(EcompPDP pdp, EcompPDPGroup newGroup) throws PAPException {
234 sendToPAP("POST", null, null, null, "groupId=" + newGroup.getId(), "pdpId=" + pdp.getId());
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());
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());
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());
260 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base");
262 //send JSON object to PAP
263 isValidData = (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType);
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;
273 if (policyAdapter.getPolicyType().equalsIgnoreCase("Config")) {
275 if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Firewall Config")) {
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());
283 else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Raw")) {
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());
292 else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Param")) {
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());
302 else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Base")) {
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());
310 }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")) {
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());
318 }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_PM")) {
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());
326 }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("DCAE Micro Service")) {
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());
335 } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Action")) {
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());
343 } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Decision")) {
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());
354 //send JSON object to PAP
355 successMap = (Map<String, String>) sendToPAP("PUT", newPAPPolicy, null, null, "operation=create", "apiflag=admin", "policyType=" + policyAdapter.getPolicyType());
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;
367 if (policyAdapter.getPolicyType().equalsIgnoreCase("Config")) {
369 if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Firewall Config")) {
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());
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());
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());
392 }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Base")) {
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());
400 }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")) {
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());
408 }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_PM")) {
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());
416 }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("DCAE Micro Service")) {
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());
425 } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Action")) {
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());
433 } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Decision")) {
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());
444 //send JSON object to PAP
445 successMap = (Map<String, String>) sendToPAP("PUT", newPAPPolicy, null, null, "operation=update", "apiflag=admin", "policyType=" + policyAdapter.getPolicyType());
450 public void publishPolicy(String id, String name, boolean isRoot,
451 InputStream policy, EcompPDPGroup group) throws PAPException {
454 // copy the (one) file into the target directory on the PAP servlet
455 copyFile(id, group, policy);
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);
461 // tell the PAP servlet to include the policy in the configuration
470 * Copy a single Policy file from the input stream to the PAP Servlet.
471 * Either this works (silently) or it throws an exception.
477 * @throws PAPException
479 public void copyFile(String policyId, EcompPDPGroup group, InputStream policy) throws PAPException {
480 // send the policy file to the PAP Servlet
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);
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);
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);
509 public void removePolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException {
510 throw new PAPException("NOT IMPLEMENTED");
517 * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly
518 * to get detailed status info.
522 * @throws PAPException
525 public PDPStatus getStatus(EcompPDP pdp) throws PAPException {
526 StdPDPStatus status = (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class);
534 // Internal Operations called by the PAPEngine Interface methods
538 * Send a request to the PAP Servlet and get the response.
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.
543 * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
546 * @param content - EITHER an InputStream OR an Object to be encoded in JSON
547 * @param collectionTypeClass
548 * @param responseContentClass
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);
563 String fullURL = papServletURLString;
564 if (parameters != null && parameters.length > 0) {
565 String queryString = "";
566 for (String p : parameters) {
567 queryString += "&" + p;
569 fullURL += "?" + queryString.substring(1);
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";
578 if(CheckPDP.validateID(pdpID)){
579 encoding = CheckPDP.getEncoding(pdpID);
584 URL url = new URL(fullURL);
587 // Open up the connection
589 connection = (HttpURLConnection)url.openConnection();
591 // Setup our method and headers
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);
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.
602 // So we need to handle this ourselves.
604 connection.setInstanceFollowRedirects(false);
605 connection.setRequestProperty("Authorization", "Basic " + encoding);
606 connection.setDoOutput(true);
607 connection.setDoInput(true);
609 if (content != null) {
610 if (content instanceof InputStream) {
613 // Send our current policy configuration
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);
621 } catch (Exception e) {
622 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
626 // The content is an object to be encoded in JSON
627 ObjectMapper mapper = new ObjectMapper();
628 mapper.writeValue(connection.getOutputStream(), content);
634 connection.connect();
635 if (connection.getResponseCode() == 204) {
636 logger.info("Success - no content.");
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.");
646 } else if (isValidData != null && isValidData.equalsIgnoreCase("false")) {
647 logger.info("Policy Data is invalid.");
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);
654 } else if (isSuccess != null && isSuccess.equalsIgnoreCase("error")) {
655 logger.info("There was an error while creating the policy!");
656 successMap.put("error", "error");
659 // get the response content into a String
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() : "";
666 logger.info("JSON response from PAP: " + json);
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);
676 Object objectFromJSON = mapper.readValue(json, javaType);
677 return objectFromJSON;
679 // single value object expected
680 Object objectFromJSON = mapper.readValue(json, responseContentClass);
681 return objectFromJSON;
685 } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
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());
692 int qIndex = newURL.indexOf("?");
694 newURL = newURL.substring(0, qIndex);
696 logger.info("Redirect seen. Redirecting " + fullURL + " to " + newURL);
699 logger.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
700 throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
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);
707 // cleanup the connection
708 if (connection != null) {
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;
714 is = connection.getInputStream();
715 } catch (Exception e1) {
722 } catch (IOException ex) {
723 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
725 connection.disconnect();