Use builder for std pap policy
[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-2018 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 package org.onap.policy.pdp.rest.api.services;
22
23 import java.io.File;
24 import java.util.UUID;
25
26 import org.onap.policy.api.DeletePolicyParameters;
27 import org.onap.policy.api.PolicyException;
28 import org.onap.policy.common.logging.flexlogger.FlexLogger;
29 import org.onap.policy.common.logging.flexlogger.Logger;
30 import org.onap.policy.xacml.api.XACMLErrorConstants;
31 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
32 import org.onap.policy.xacml.std.pap.StdPAPPolicyParams;
33 import org.springframework.http.HttpStatus;
34
35 public class DeletePolicyService {
36     private static final Logger LOGGER = FlexLogger.getLogger(DeletePolicyService.class.getName());
37
38     private String deleteResult = null;
39     private HttpStatus status = HttpStatus.BAD_REQUEST;
40     private DeletePolicyParameters deletePolicyParameters = null;
41     private String message = null;
42     private String filePrefix = null;
43     private String clientScope = null;
44     private String policyType = null;
45     private String policyName = null;
46     private String policyScope = null;
47
48     public DeletePolicyService(final DeletePolicyParameters deletePolicyParameters, final String requestID) {
49         this.deletePolicyParameters = deletePolicyParameters;
50         if (deletePolicyParameters.getRequestID() == null) {
51             UUID requestUUID = null;
52             if (requestID != null && !requestID.isEmpty()) {
53                 try {
54                     requestUUID = UUID.fromString(requestID);
55                 } catch (final IllegalArgumentException e) {
56                     requestUUID = UUID.randomUUID();
57                     LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e);
58                 }
59             } else {
60                 requestUUID = UUID.randomUUID();
61                 LOGGER.info("Generated Random UUID: " + requestUUID.toString());
62             }
63             this.deletePolicyParameters.setRequestID(requestUUID);
64         }
65         try {
66             run();
67             specialCheck();
68         } catch (final PolicyException e) {
69             LOGGER.error("Unable to process delete policy request for : " + this.deletePolicyParameters);
70             deleteResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
71             status = HttpStatus.BAD_REQUEST;
72         }
73     }
74
75     private void specialCheck() {
76         if (deleteResult == null) {
77             return;
78         }
79         if (deleteResult.contains("BAD REQUEST") || deleteResult.contains("PE300") || deleteResult.contains("PE200")
80                 || deleteResult.contains("not exist") || deleteResult.contains("Invalid policyName")) {
81             if (deleteResult.contains("groupId")) {
82                 status = HttpStatus.NOT_FOUND;
83             } else {
84                 status = HttpStatus.BAD_REQUEST;
85             }
86         } else if (deleteResult.contains("locked down")) {
87             status = HttpStatus.ACCEPTED;
88         } else if (deleteResult.contains("not Authorized")) {
89             status = HttpStatus.FORBIDDEN;
90         } else if (deleteResult.contains("JPAUtils") || deleteResult.contains("database")
91                 || deleteResult.contains("policy file") || deleteResult.contains("unknown")
92                 || deleteResult.contains("configuration")) {
93             status = HttpStatus.INTERNAL_SERVER_ERROR;
94         }
95     }
96
97     private void run() throws PolicyException {
98         // Check Validation.
99         if (!getValidation()) {
100             LOGGER.error(message);
101             throw new PolicyException(message);
102         }
103         // Get Result.
104         try {
105             LOGGER.debug("Processing delete request:  " + deletePolicyParameters.toString());
106             status = HttpStatus.OK;
107             deleteResult = processResult();
108         } catch (final Exception e) {
109             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
110             status = HttpStatus.BAD_REQUEST;
111             throw new PolicyException(e);
112         }
113     }
114
115     private String processResult() throws PolicyException {
116         String response = null;
117         String fullPolicyName = null;
118         String pdpGroup = deletePolicyParameters.getPdpGroup();
119         // PDP Group Check.
120         if (pdpGroup == null) {
121             pdpGroup = "NA";
122         }
123         final PAPServices papServices = new PAPServices();
124         if (!deletePolicyParameters.getPolicyName().contains("xml")) {
125
126             final String activeVersion = papServices.getActiveVersion(policyScope, filePrefix, policyName, clientScope,
127                     deletePolicyParameters.getRequestID());
128             LOGGER.debug("The active version of " + policyScope + File.separator + filePrefix + policyName + " is "
129                     + activeVersion);
130             String id = null;
131             if ("pe100".equalsIgnoreCase(activeVersion)) {
132                 response = XACMLErrorConstants.ERROR_PERMISSIONS
133                         + "response code of the URL is 403. PEP is not Authorized for making this Request!! "
134                         + "Contact Administrator for this Scope. ";
135                 LOGGER.error(response);
136                 return response;
137             } else if ("pe300".equalsIgnoreCase(activeVersion)) {
138                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404.  "
139                         + "This indicates a problem with getting the version from the PAP or the policy does not exist.";
140                 LOGGER.error(response);
141                 return response;
142             }
143             if (!"0".equalsIgnoreCase(activeVersion)) {
144                 id = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml";
145                 LOGGER.debug("The policyId is " + id);
146             } else {
147                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
148                         + "could not retrieve the activeVersion for this policy. could not retrieve the activeVersion for this policy.  "
149                         + "This indicates the policy does not exist, please verify the policy exists.";
150                 LOGGER.error(response);
151                 return response;
152             }
153
154             fullPolicyName = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml";
155
156         } else {
157             fullPolicyName = policyName;
158         }
159
160         if ("PAP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) {
161             if (deletePolicyParameters.getDeleteCondition() == null
162                     || deletePolicyParameters.getDeleteCondition().toString().trim().isEmpty()) {
163                 message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Delete Condition given.";
164                 LOGGER.error(message);
165                 return message;
166             }
167             // for deleting policies from the API
168             final StdPAPPolicy deletePapPolicy =
169                     new StdPAPPolicy(StdPAPPolicyParams.builder()
170                             .policyName(fullPolicyName)
171                             .deleteCondition(deletePolicyParameters.getDeleteCondition().toString())
172                             .build());
173             // send JSON object to PAP
174             response = (String) papServices.callPAP(deletePapPolicy,
175                     new String[] {"groupId=" + pdpGroup, "apiflag=deletePapApi", "operation=delete"},
176                     deletePolicyParameters.getRequestID(), clientScope);
177         } else if ("PDP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) {
178             if (deletePolicyParameters.getPdpGroup() == null || deletePolicyParameters.getPdpGroup().trim().isEmpty()) {
179                 message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given.";
180                 LOGGER.error(message);
181                 return message;
182             }
183             // send JSON object to PAP
184             response =
185                     (String) papServices.callPAP(
186                             null, new String[] {"policyName=" + fullPolicyName, "groupId=" + pdpGroup,
187                                 "apiflag=deletePdpApi", "operation=delete"},
188                             deletePolicyParameters.getRequestID(), clientScope);
189         } else {
190             message = XACMLErrorConstants.ERROR_DATA_ISSUE
191                     + "Policy Component does not exist. Please enter either PAP or PDP to delete the policy from a specified Policy Component.";
192             LOGGER.error(message);
193             response = message;
194         }
195         return response;
196     }
197
198     private boolean getValidation() {
199         // While Validating, extract the required values.
200         if (deletePolicyParameters.getPolicyName() == null || deletePolicyParameters.getPolicyName().trim().isEmpty()) {
201             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
202             return false;
203         }
204         if (!deletePolicyParameters.getPolicyName().contains("xml")) {
205             if (deletePolicyParameters.getPolicyName() != null
206                     && deletePolicyParameters.getPolicyName().contains(".")) {
207                 policyName = deletePolicyParameters.getPolicyName().substring(
208                         deletePolicyParameters.getPolicyName().lastIndexOf('.') + 1,
209                         deletePolicyParameters.getPolicyName().length());
210                 policyScope = deletePolicyParameters.getPolicyName().substring(0,
211                         deletePolicyParameters.getPolicyName().lastIndexOf('.'));
212                 LOGGER.info("Name is " + policyName + "   scope is " + policyScope);
213             } else {
214                 message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
215                 return false;
216             }
217         } else {
218             policyName = deletePolicyParameters.getPolicyName();
219         }
220         policyType = deletePolicyParameters.getPolicyType();
221         if (policyType == null || policyType.trim().isEmpty()) {
222             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given.";
223             return false;
224         }
225         setClientScope();
226         if (clientScope == null || clientScope.trim().isEmpty()) {
227             message = XACMLErrorConstants.ERROR_DATA_ISSUE + deletePolicyParameters.getPolicyType()
228                     + " is not a valid Policy Type.";
229             LOGGER.error(message);
230             return false;
231         }
232         LOGGER.debug("clientScope is " + clientScope);
233         LOGGER.debug("filePrefix is " + filePrefix);
234         if (deletePolicyParameters.getPolicyComponent() == null) {
235             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Component given.";
236             return false;
237         }
238         return true;
239     }
240
241     private void setClientScope() {
242         if ("Firewall".equalsIgnoreCase(policyType)) {
243             clientScope = "ConfigFirewall";
244             filePrefix = "Config_FW_";
245         } else if ("Action".equalsIgnoreCase(policyType)) {
246             clientScope = "Action";
247             filePrefix = "Action_";
248         } else if ("Decision".equalsIgnoreCase(policyType)) {
249             clientScope = "Decision";
250             filePrefix = "Decision_";
251         } else if ("Base".equalsIgnoreCase(policyType)) {
252             clientScope = "Config";
253             filePrefix = "Config_";
254         } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyType)) {
255             clientScope = "ConfigClosedLoop";
256             filePrefix = "Config_Fault_";
257         } else if ("ClosedLoop_PM".equalsIgnoreCase(policyType)) {
258             clientScope = "ConfigClosedLoop";
259             filePrefix = "Config_PM_";
260         } else if ("MicroService".equalsIgnoreCase(policyType)) {
261             clientScope = "ConfigMS";
262             filePrefix = "Config_MS_";
263         } else if ("Optimization".equalsIgnoreCase(policyType)) {
264             clientScope = "ConfigOptimization";
265             filePrefix = "Config_OOF_";
266         } else if ("BRMS_RAW".equalsIgnoreCase(policyType)) {
267             clientScope = "ConfigBrmsRaw";
268             filePrefix = "Config_BRMS_Raw_";
269         } else if ("BRMS_PARAM".equalsIgnoreCase(policyType)) {
270             clientScope = "ConfigBrmsParam";
271             filePrefix = "Config_BRMS_Param_";
272         } else {
273             clientScope = null;
274             message = XACMLErrorConstants.ERROR_DATA_ISSUE + policyType + " is not a valid Policy Type.";
275         }
276     }
277
278     public String getResult() {
279         return deleteResult;
280     }
281
282     public HttpStatus getResponseCode() {
283         return status;
284     }
285
286 }