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