ff0ac826f103c37671f7479519fe6f14b97541f6
[policy/engine.git] / ONAP-PDP-REST / src / main / java / org / onap / policy / pdp / rest / api / services / DeletePolicyService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PDP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pdp.rest.api.services;
23
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.List;
27 import java.util.stream.Collectors;
28 import org.apache.commons.lang3.StringUtils;
29 import org.onap.policy.api.DeletePolicyParameters;
30 import org.onap.policy.api.PolicyException;
31 import org.onap.policy.api.PolicyNameType;
32 import org.onap.policy.common.logging.flexlogger.FlexLogger;
33 import org.onap.policy.common.logging.flexlogger.Logger;
34 import org.onap.policy.xacml.api.XACMLErrorConstants;
35 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
36 import org.onap.policy.xacml.std.pap.StdPAPPolicyParams;
37 import org.springframework.http.HttpStatus;
38
39
40 /**
41  * The Class DeletePolicyService.
42  */
43 public class DeletePolicyService extends PdpApiService {
44
45     private static final Logger LOGGER = FlexLogger.getLogger(DeletePolicyService.class.getName());
46     private static final String PRINT_REQUESTID = " - RequestId - ";
47     private DeletePolicyParameters deletePolicyParameters = null;
48     private String result = null;
49     private List<PolicyNameType> policyList = new ArrayList<>();
50
51
52     /**
53      * Instantiates a new delete policy service.
54      *
55      * @param deletePolicyParameters the delete policy parameters
56      * @param reqId the request id
57      */
58     public DeletePolicyService(final DeletePolicyParameters deletePolicyParameters, final String reqId) {
59         super();
60         this.deletePolicyParameters = deletePolicyParameters;
61         deletePolicyParameters.setRequestID(populateRequestId(deletePolicyParameters.getRequestID(), reqId));
62         try {
63             run();
64             specialCheck();
65         } catch (final PolicyException e) {
66             LOGGER.error("Unable to process delete policy request for : " + this.deletePolicyParameters
67                     + PRINT_REQUESTID + this.requestId);
68             result = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
69             status = HttpStatus.BAD_REQUEST;
70         }
71     }
72
73     /**
74      * Special check.
75      */
76     private void specialCheck() {
77         if (result == null) {
78             return;
79         }
80         if (result.contains("BAD REQUEST") || result.contains("PE300") || result.contains("PE200")
81                 || result.contains("not exist") || result.contains("Invalid policyName")) {
82             if (result.contains("groupId")) {
83                 status = HttpStatus.NOT_FOUND;
84             } else {
85                 status = HttpStatus.BAD_REQUEST;
86             }
87         } else if (result.contains("locked down")) {
88             status = HttpStatus.ACCEPTED;
89         } else if (result.contains("not Authorized")) {
90             status = HttpStatus.FORBIDDEN;
91         } else if (result.contains("JPAUtils") || result.contains("database")
92                 || result.contains("policy file") || result.contains("unknown")
93                 || result.contains("configuration")) {
94             status = HttpStatus.INTERNAL_SERVER_ERROR;
95         }
96     }
97
98     /**
99      * Run.
100      *
101      * @throws PolicyException the policy exception
102      */
103     private void run() throws PolicyException {
104         // Check Validation.
105         if (!getValidation()) {
106             LOGGER.error(message);
107             throw new PolicyException(message);
108         }
109         // Get Result.
110         try {
111             LOGGER.debug("Processing delete request:  " + deletePolicyParameters.toString() + PRINT_REQUESTID
112                     + this.requestId);
113             status = HttpStatus.OK;
114             result = processResult();
115         } catch (final Exception e) {
116             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
117             status = HttpStatus.BAD_REQUEST;
118             throw new PolicyException(e);
119         }
120     }
121
122     /**
123      * Process result.
124      *
125      * @return the string
126      * @throws PolicyException the policy exception
127      */
128     private String processResult() throws PolicyException {
129         String response = null;
130         String pdpGroup = deletePolicyParameters.getPdpGroup();
131
132         final PAPServices papServices = new PAPServices();
133         if (!populateFullPolicyName(papServices)) {
134             LOGGER.error(message);
135             return message;
136         }
137
138         if ("PAP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) {
139             // for deleting policies from the API
140             for (PolicyNameType policyData : policyList) {
141                 // validation ensures there will be one delete policy at a time
142                 final StdPAPPolicy deletePapPolicy =
143                         new StdPAPPolicy(StdPAPPolicyParams.builder().policyName(policyData.getFullPolicyName())
144                                 .deleteCondition(deletePolicyParameters.getDeleteCondition().toString()).build());
145                 // send JSON object to PAP
146                 response = (String) papServices.callPAP(deletePapPolicy,
147                         new String[] {"groupId=" + pdpGroup, "apiflag=deletePapApi", "operation=delete"},
148                         deletePolicyParameters.getRequestID(), policyData.getClientScope());
149             }
150         } else if ("PDP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) {
151             String policies =
152                     policyList.stream().map(PolicyNameType::getFullPolicyName).collect(Collectors.joining(","));
153             // send JSON object to PAP
154             response =
155                     (String) papServices.callPAP(null,
156                             new String[] {"policyName=" + policies, "groupId=" + pdpGroup, "apiflag=deletePdpApi",
157                                     "operation=delete", "userId=API"},
158                             deletePolicyParameters.getRequestID(), clientScope);
159         } else {
160             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Component does not exist."
161                     + "Please enter either PAP or PDP to delete the policy from a specified Policy Component.";
162             LOGGER.warn(message + PRINT_REQUESTID + requestId);
163             response = message;
164         }
165         return response;
166     }
167
168     /**
169      * Populate full policy name.
170      *
171      * @param papServices the pap services
172      * @return true, if successful
173      */
174     private boolean populateFullPolicyName(final PAPServices papServices) {
175         for (PolicyNameType policyData : policyList) {
176             if (policyData.getPolicyName().contains("xml")) {
177                 policyData.setFullPolicyName(policyData.getPolicyName());
178                 continue;
179             }
180
181             final String activeVersion = papServices.getActiveVersion(policyData.getPolicyScope(),
182                     policyData.getFilePrefix(), policyData.getPolicyName(), policyData.getClientScope(),
183                     deletePolicyParameters.getRequestID());
184
185             if ("pe100".equalsIgnoreCase(activeVersion)) {
186                 message = XACMLErrorConstants.ERROR_PERMISSIONS
187                         + "response code of the URL is 403. PEP is not Authorized for making this Request!! "
188                         + "Contact Administrator for this Scope. ";
189                 LOGGER.warn(message + PRINT_REQUESTID + this.requestId);
190                 return false;
191             } else if ("pe300".equalsIgnoreCase(activeVersion)) {
192                 message = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404.  "
193                         + "This indicates a problem with getting the version"
194                         + "from the PAP or the policy does not exist.";
195                 LOGGER.warn(message + PRINT_REQUESTID + this.requestId);
196                 return false;
197             }
198             if ("0".equalsIgnoreCase(activeVersion)) {
199                 message = XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy."
200                         + "This indicates the policy does not exist, please verify the policy exists.";
201                 LOGGER.warn(message + PRINT_REQUESTID + this.requestId);
202                 return false;
203             }
204
205             policyData.setFullPolicyName(policyData.getPolicyScope() + "." + policyData.getFilePrefix()
206                     + policyData.getPolicyName() + "." + activeVersion + ".xml");
207         }
208         return true;
209     }
210
211     /**
212      * Gets the validation.
213      *
214      * @return the validation
215      */
216     private boolean getValidation() {
217         if (StringUtils.isBlank(deletePolicyParameters.getPolicyName())) {
218             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
219             return false;
220         }
221
222         String policyType = deletePolicyParameters.getPolicyType();
223         if (StringUtils.isBlank(policyType)) {
224             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given.";
225             return false;
226         }
227
228         if (StringUtils.isBlank(deletePolicyParameters.getPolicyComponent())) {
229             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Component given.";
230             return false;
231         }
232
233         List<String> policyNames = Arrays.asList(deletePolicyParameters.getPolicyName().split(","));
234         List<String> policyTypes = Arrays.asList(deletePolicyParameters.getPolicyType().split(","));
235
236         if (policyTypes.size() > 1 && (policyNames.size() != policyTypes.size())) {
237             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid number of PolicyTypes";
238             return false;
239         }
240
241         if ((policyNames.stream().anyMatch(StringUtils::isBlank))
242                 || (policyTypes.stream().anyMatch(StringUtils::isBlank))) {
243             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid PolicyName or PolicyType";
244             return false;
245         }
246
247         if ("PAP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent()) && policyNames.size() > 1) {
248             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Only one policy can be deleted from PAP at a time";
249             return false;
250         }
251
252         if ("PAP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())
253                 && (deletePolicyParameters.getDeleteCondition() == null
254                         || deletePolicyParameters.getDeleteCondition().toString().trim().isEmpty())) {
255             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Delete Condition given.";
256             LOGGER.warn(message + PRINT_REQUESTID + requestId);
257             return false;
258         }
259
260         if ("PDP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())
261                 && StringUtils.isBlank(deletePolicyParameters.getPdpGroup())) {
262             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given.";
263             LOGGER.warn(message + PRINT_REQUESTID + requestId);
264             return false;
265         }
266
267         if (!validatePolicyNameAndScope(policyNames, policyTypes, policyList)) {
268             LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed validation in validatePolicyNameAndScope - "
269                     + message + PRINT_REQUESTID + requestId);
270             return false;
271         }
272
273         return true;
274     }
275
276     public String getResult() {
277         return result;
278     }
279 }