Push and unpush to support multiple policies
[policy/engine.git] / ONAP-PDP-REST / src / main / java / org / onap / policy / pdp / rest / api / services / PushPolicyService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PDP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2019 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.pdp.rest.api.services;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.List;
26 import org.apache.commons.lang3.StringUtils;
27 import org.onap.policy.api.PolicyException;
28 import org.onap.policy.api.PolicyNameType;
29 import org.onap.policy.api.PushPolicyParameters;
30 import org.onap.policy.common.logging.flexlogger.FlexLogger;
31 import org.onap.policy.common.logging.flexlogger.Logger;
32 import org.onap.policy.xacml.api.XACMLErrorConstants;
33 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
34 import org.springframework.http.HttpStatus;
35
36 public class PushPolicyService extends PdpApiService {
37     private static final Logger LOGGER = FlexLogger.getLogger(PushPolicyService.class.getName());
38
39     private PushPolicyParameters pushPolicyParameters = null;
40     private List<PolicyNameType> policyList = new ArrayList<>();
41     private String pdpGroup = null;
42     private String result = null;
43
44     /**
45      * Instantiates a new push policy service.
46      *
47      * @param pushPolicyParameters the push policy parameters
48      * @param reqId the request ID
49      */
50     public PushPolicyService(final PushPolicyParameters pushPolicyParameters, final String reqId) {
51         this.pushPolicyParameters = pushPolicyParameters;
52         pushPolicyParameters.setRequestID(populateRequestId(pushPolicyParameters.getRequestID(), reqId));
53         LOGGER.info("Operation: pushPolicy - Request - " + pushPolicyParameters + ", RequestId - " + requestId);
54         try {
55             run();
56             specialCheck();
57         } catch (PolicyException e) {
58             result = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
59             status = HttpStatus.BAD_REQUEST;
60         }
61         LOGGER.info(
62                 "PushPolicyService - RequestId - " + requestId + " , Response - " + result + ", Status - " + status);
63     }
64
65     private void run() throws PolicyException {
66         // Check Validation.
67         if (!getValidation()) {
68             LOGGER.error(message);
69             throw new PolicyException(message);
70         }
71         // Process Results.
72         try {
73             status = HttpStatus.OK;
74             result = processResult();
75         } catch (Exception e) {
76             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
77             status = HttpStatus.BAD_REQUEST;
78             throw new PolicyException(e);
79         }
80     }
81
82     private String processResult() throws PolicyException {
83         PAPServices papServices = new PAPServices();
84         String response = null;
85
86         try {
87             // for each policy to be pushed, we need to call pap to get the active version
88             // and construct the full policy name. Then the list of policy names are sent to pap
89             // to do the actual push.
90             String policyId = constructPolicyNames(papServices);
91             response =
92                     (String) papServices
93                             .callPAP(null,
94                                     new String[] {"groupId=" + pdpGroup, "policyId=" + policyId, "apiflag=api",
95                                             "operation=POST", "userId=API"},
96                                     pushPolicyParameters.getRequestID(), clientScope);
97         } catch (Exception e) {
98             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e.getMessage());
99             throw new PolicyException(e);
100         }
101         LOGGER.debug("Final API response: " + response);
102         return response;
103     }
104
105     private void specialCheck() {
106         if (result.contains("BAD REQUEST") || result.contains("PE300")) {
107             status = HttpStatus.BAD_REQUEST;
108         }
109     }
110
111
112     private String constructPolicyNames(PAPServices papServices) throws PolicyException {
113         List<String> pushPolicyList = new ArrayList<>(policyList.size());
114         for (PolicyNameType policyData : policyList) {
115             LOGGER.info("PushPolicyService - constructPolicyNames - Policy Name is " + policyData.getPolicyName()
116                     + "   scope is " + policyData.getPolicyScope());
117             // for each policy we need to get the active version to construct policyId
118             StdPDPPolicy selectedPolicy = papServices.pushPolicy(policyData.getPolicyScope(),
119                     policyData.getFilePrefix(), policyData.getPolicyName(), policyData.getClientScope(),
120                     pdpGroup.trim(), pushPolicyParameters.getRequestID());
121             if (selectedPolicy != null) {
122                 pushPolicyList.add(selectedPolicy.getId());
123             } else {
124                 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404.  "
125                         + "This indicates a problem with getting the version "
126                         + "from the PAP or the policy does not exist - " + policyData);
127             }
128         }
129         return String.join(",", pushPolicyList);
130     }
131
132     private boolean getValidation() {
133         // While Validating, extract the required values.
134         if (StringUtils.isBlank(pushPolicyParameters.getPolicyName())) {
135             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
136             return false;
137         }
138
139         if (StringUtils.isBlank(pushPolicyParameters.getPolicyType())) {
140             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given.";
141             return false;
142         }
143
144         List<String> policyNames = Arrays.asList(pushPolicyParameters.getPolicyName().split(","));
145         List<String> policyTypes = Arrays.asList(pushPolicyParameters.getPolicyType().split(","));
146
147         if (policyTypes.size() != 1 && (policyNames.size() != policyTypes.size())) {
148             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid number of PolicyTypes";
149             return false;
150         }
151
152         if ((policyNames.stream().anyMatch(StringUtils::isBlank))
153                 || (policyTypes.stream().anyMatch(StringUtils::isBlank))) {
154             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid PolicyName or PolicyType";
155             return false;
156         }
157
158         if (!validatePolicyNameAndScope(policyNames, policyTypes, policyList)) {
159             LOGGER.warn("PushPolicyService - Failed validation in validatePolicyNameAndScope - " + message);
160             return false;
161         }
162
163         pdpGroup = pushPolicyParameters.getPdpGroup();
164         if (StringUtils.isBlank(pdpGroup)) {
165             pdpGroup = "default";
166         }
167
168         return true;
169     }
170
171     public String getResult() {
172         return result;
173     }
174 }