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=========================================================
20 package org.openecomp.policy.pap.xacml.rest.handler;
23 import java.io.IOException;
24 import java.sql.Connection;
25 import java.sql.DriverManager;
26 import java.sql.ResultSet;
27 import java.sql.SQLException;
28 import java.sql.Statement;
29 import java.util.List;
31 import javax.persistence.EntityManager;
32 import javax.persistence.Query;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
36 import org.openecomp.policy.common.logging.ECOMPLoggingContext;
37 import org.openecomp.policy.common.logging.eelf.MessageCodes;
38 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
39 import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
40 import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
41 import org.openecomp.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController;
42 import org.openecomp.policy.pap.xacml.rest.model.RemoveGroupPolicy;
43 import org.openecomp.policy.pap.xacml.rest.util.JPAUtils;
44 import org.openecomp.policy.rest.XACMLRestProperties;
45 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
46 import org.openecomp.policy.rest.jpa.PolicyEntity;
47 import org.openecomp.policy.rest.jpa.PolicyVersion;
48 import org.openecomp.policy.utils.PolicyUtils;
49 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
50 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
51 import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
52 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
54 import com.att.research.xacml.api.pap.PAPException;
55 import com.att.research.xacml.api.pap.PDPPolicy;
56 import com.att.research.xacml.util.XACMLProperties;
58 public class DeleteHandler {
60 private EcompPDPGroup newgroup;
62 private static String papDbDriver = null;
63 private static String papDbUrl = null;
64 private static String papDbUser = null;
65 private static String papDbPassword = null;
67 public void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws Exception {
68 // get the request content into a String
70 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
71 scanner.useDelimiter("\\A");
72 json = scanner.hasNext() ? scanner.next() : "";
74 PolicyLogger.info("JSON request from API: " + json);
75 // convert Object sent as JSON into local object
76 StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class);
77 String policyName = policy.getPolicyName();
78 Boolean policyVersionDeleted = false;
79 String removeXMLExtension;
81 String removeVersionExtension;
82 String splitPolicyName = null;
83 String[] split = null;
84 String status = "error";
85 PolicyEntity policyEntity = null;
86 JPAUtils jpaUtils = null;
88 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
89 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
90 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
91 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
92 Connection con = null;
95 jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
96 } catch (Exception e) {
97 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP");
98 response.addHeader("error", "jpautils");
99 response.addHeader("operation", "delete");
100 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
103 if (jpaUtils.dbLockdownIgnoreErrors()) {
104 PolicyLogger.warn("Policies are locked down");
105 response.addHeader("operation", "delete");
106 response.addHeader("lockdown", "true");
107 response.setStatus(HttpServletResponse.SC_ACCEPTED);
110 EntityManager em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager();
111 Query policyEntityQuery = null;
113 if(policyName.endsWith(".xml")){
114 removeXMLExtension = policyName.replace(".xml", "");
115 currentVersion = Integer.parseInt(removeXMLExtension.substring(removeXMLExtension.lastIndexOf(".")+1));
116 removeVersionExtension = removeXMLExtension.substring(0, removeXMLExtension.lastIndexOf("."));
117 boolean queryCheck = true;
118 if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
119 if(policyName.contains("Config_")){
120 splitPolicyName = removeVersionExtension.replace(".Config_", ":Config_");
121 }else if(policyName.contains("Action_")){
122 splitPolicyName = removeVersionExtension.replace(".Action_", ":Action_");
123 }else if(policyName.contains("Decision_")){
124 splitPolicyName = removeVersionExtension.replace(".Decision_", ":Decision_");
126 if(splitPolicyName != null){
127 split = splitPolicyName.split(":");
129 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy. Please, provide the valid policyname.");
130 response.addHeader("error", "unknown");
131 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
134 policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName LIKE :pName and p.scope=:pScope");
135 }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")) {
136 if(policyName.contains("Config_")){
137 splitPolicyName = policyName.replace(".Config_", ":Config_");
138 }else if(policyName.contains("Action_")){
139 splitPolicyName = policyName.replace(".Action_", ":Action_");
140 }else if(policyName.contains("Decision_")){
141 splitPolicyName = policyName.replace(".Decision_", ":Decision_");
143 split = splitPolicyName.split(":");
145 policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope");
149 policyEntityQuery.setParameter("pName", "%"+split[1]+"%");
151 policyEntityQuery.setParameter("pName", split[1]);
154 policyEntityQuery.setParameter("pScope", split[0]);
155 List<?> peResult = policyEntityQuery.getResultList();
156 if(!peResult.isEmpty()){
157 Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
158 getPolicyVersion.setParameter("pname", removeVersionExtension.replace(".", File.separator));
159 List<?> pvResult = getPolicyVersion.getResultList();
160 PolicyVersion pVersion = (PolicyVersion) pvResult.get(0);
161 int highestVersion = 0;
162 em.getTransaction().begin();
163 Class.forName(papDbDriver);
164 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
166 if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
167 boolean groupCheck = checkPolicyGroupEntity(em, con, peResult);
169 for(Object peData : peResult){
170 policyEntity = (PolicyEntity) peData;
171 status = deletePolicyEntityData(em, policyEntity);
174 status = "PolicyInPDP";
176 if(status.equals("error")){
177 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
178 response.addHeader("error", "unknown");
179 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
181 }else if(status.equals("PolicyInPDP")){
182 PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
183 response.addHeader("error", "unknown");
184 response.setStatus(HttpServletResponse.SC_CONFLICT);
188 policyVersionDeleted = true;
191 policyVersionDeleted = false;
194 }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")){
195 boolean groupCheck = checkPolicyGroupEntity(em, con, peResult);
197 policyEntity = (PolicyEntity) peResult.get(0);
198 status = deletePolicyEntityData(em, policyEntity);
200 status = "PolicyInPDP";
203 if(status.equals("error")){
204 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
205 response.addHeader("error", "unknown");
206 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
208 }else if(status.equals("PolicyInPDP")){
209 PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
210 response.addHeader("error", "unknown");
211 response.setStatus(HttpServletResponse.SC_CONFLICT);
214 if(currentVersion > 1){
215 if(!peResult.isEmpty()){
216 for(Object object : peResult){
217 policyEntity = (PolicyEntity) object;
218 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
219 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
220 if(policyEntityVersion > highestVersion){
221 highestVersion = policyEntityVersion;
225 pVersion.setActiveVersion(highestVersion);
226 pVersion.setHigherVersion(highestVersion);
228 policyVersionDeleted = true;
229 em.persist(pVersion);
231 policyVersionDeleted = false;
235 policyVersionDeleted = true;
238 policyVersionDeleted = false;
244 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
245 response.addHeader("error", "unknown");
246 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
250 em.getTransaction().commit();
252 em.getTransaction().rollback();
253 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
254 response.addHeader("error", "deleteDB");
255 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
264 if (policyVersionDeleted) {
265 response.setStatus(HttpServletResponse.SC_OK);
266 response.addHeader("successMapKey", "success");
267 response.addHeader("operation", "delete");
270 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
271 response.addHeader("error", "unknown");
272 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
277 public String deletePolicyEntityData(EntityManager em, PolicyEntity policyEntity) throws SQLException{
278 PolicyElasticSearchController controller = new PolicyElasticSearchController();
279 PolicyRestAdapter policyData = new PolicyRestAdapter();
280 String policyName = policyEntity.getPolicyName();
282 if(policyName.contains("Config_")){
283 em.remove(policyEntity.getConfigurationData());
284 }else if(policyName.contains("Action_")){
285 em.remove(policyEntity.getActionBodyEntity());
287 String searchPolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
288 policyData.setNewFileName(searchPolicyName);
289 controller.deleteElk(policyData);
290 em.remove(policyEntity);
297 public boolean checkPolicyGroupEntity(EntityManager em, Connection con, List<?> peResult) throws SQLException{
298 for(Object peData : peResult){
299 PolicyEntity policyEntity = (PolicyEntity) peData;
303 st = con.createStatement();
304 rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'");
305 boolean gEntityList = rs.next();
317 public void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws IOException {
318 String policyName = request.getParameter("policyName");
319 String groupId = request.getParameter("groupId");
320 String responseString = null;
321 // for PUT operations the group may or may not need to exist before the operation can be done
322 EcompPDPGroup group = null;
324 group = XACMLPapServlet.getPAPEngine().getGroup(groupId);
325 } catch (PAPException e) {
326 PolicyLogger.error("Exception occured While PUT operation is performing for PDP Group"+e);
329 String message = "Unknown groupId '" + groupId + "'";
330 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
331 loggingContext.transactionEnded();
332 PolicyLogger.audit("Transaction Failed - See Error.log");
333 response.addHeader("error", "UnknownGroup");
334 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
337 loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup");
338 if (policyName.contains("xml")) {
339 PolicyLogger.debug("The full file name including the extension was provided for policyName.. continue.");
341 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
342 + "policyName must be the full name of the file to be deleted including version and extension";
343 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... "
344 + "policyName must be the full name of the file to be deleted including version and extension");
345 response.addHeader("error", message);
346 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
349 RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group);
350 PDPPolicy policy = group.getPolicy(policyName);
351 if (policy != null) {
353 if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) {
354 if (preSafetyCheck(policy)) {
355 PolicyLogger.debug("Precheck Successful.");
359 removePolicy.prepareToRemove(policy);
360 EcompPDPGroup updatedGroup = removePolicy.getUpdatedObject();
361 responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext);
363 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.";
364 PolicyLogger.error(message);
365 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP.");
366 response.addHeader("error", message);
367 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
371 if (responseString.equals("success")) {
372 PolicyLogger.info("Policy successfully deleted!");
373 PolicyLogger.audit("Policy successfully deleted!");
374 response.setStatus(HttpServletResponse.SC_OK);
375 response.addHeader("successMapKey", "success");
376 response.addHeader("operation", "delete");
378 } else if (responseString.equals("No Group")) {
379 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input.";
380 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input.");
381 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
382 response.addHeader("error", "groupUpdate");
383 response.addHeader("message", message);
385 } else if (responseString.equals("DB Error")) {
386 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database");
387 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
388 response.addHeader("error", "deleteDB");
391 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
392 response.addHeader("error", "unknown");
393 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
398 private String deletePolicyFromPDPGroup (EcompPDPGroup group, ECOMPLoggingContext loggingContext){
399 PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction();
400 String response = null;
401 loggingContext.setServiceName("API:PAP.DeleteHandler");
402 EcompPDPGroup existingGroup = null;
404 existingGroup = XACMLPapServlet.getPAPEngine().getGroup(group.getId());
405 } catch (PAPException e1) {
406 PolicyLogger.error("Exception occured While Deleting Policy From PDP Group"+e1);
408 if (group == null || ! (group instanceof StdPDPGroup) || existingGroup == null || ! (group.getId().equals(existingGroup.getId()))) {
409 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingGroup != null ? existingGroup.getId() : "null" + " objectFromJSON="+group);
410 loggingContext.transactionEnded();
411 PolicyLogger.audit("Transaction Failed - See Error.log");
412 response = "No Group";
415 // The Path on the PAP side is not carried on the RESTful interface with the AC
416 // (because it is local to the PAP)
417 // so we need to fill that in before submitting the group for update
418 ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory());
420 acPutTransaction.updateGroup(group, "XACMLPapServlet.doAPIDelete");
421 } catch(Exception e){
422 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
423 +"group="+existingGroup.getId());
424 response = "DB Error";
428 XACMLPapServlet.getPAPEngine().updateGroup(group);
429 } catch (PAPException e) {
430 PolicyLogger.error("Exception occured While Updating PDP Groups"+e);
431 response = "error in updateGroup method";
433 PolicyLogger.debug("Group '" + group.getId() + "' updated");
434 acPutTransaction.commitTransaction();
435 // Group changed, which might include changing the policies
437 newgroup = existingGroup;
438 } catch (Exception e) {
439 PolicyLogger.error("Exception occured in Group Change Method"+e);
440 response = "error in groupChanged method";
443 response = "success";
444 PolicyLogger.audit("Policy successfully deleted!");
445 PolicyLogger.audit("Transaction Ended Successfully");
447 loggingContext.transactionEnded();
448 PolicyLogger.audit("Transaction Ended");
452 public EcompPDPGroup getDeletedGroup(){
456 public boolean preSafetyCheck(PDPPolicy policy) {
460 public static DeleteHandler getInstance() {
462 Class<?> deleteHandler = Class.forName(XACMLProperties.getProperty("deletePolicy.impl.className", DeleteHandler.class.getName()));
463 DeleteHandler instance = (DeleteHandler) deleteHandler.newInstance();
465 } catch (Exception e) {
466 PolicyLogger.error(e.getMessage());