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 split = splitPolicyName.split(":");
127 policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName LIKE :pName and p.scope=:pScope");
128 }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")) {
129 if(policyName.contains("Config_")){
130 splitPolicyName = policyName.replace(".Config_", ":Config_");
131 }else if(policyName.contains("Action_")){
132 splitPolicyName = policyName.replace(".Action_", ":Action_");
133 }else if(policyName.contains("Decision_")){
134 splitPolicyName = policyName.replace(".Decision_", ":Decision_");
136 split = splitPolicyName.split(":");
138 policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope");
142 policyEntityQuery.setParameter("pName", "%"+split[1]+"%");
144 policyEntityQuery.setParameter("pName", split[1]);
147 policyEntityQuery.setParameter("pScope", split[0]);
148 List<?> peResult = policyEntityQuery.getResultList();
149 if(!peResult.isEmpty()){
150 Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
151 getPolicyVersion.setParameter("pname", removeVersionExtension.replace(".", File.separator));
152 List<?> pvResult = getPolicyVersion.getResultList();
153 PolicyVersion pVersion = (PolicyVersion) pvResult.get(0);
154 int highestVersion = 0;
155 em.getTransaction().begin();
156 Class.forName(papDbDriver);
157 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
159 if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
160 boolean groupCheck = checkPolicyGroupEntity(em, con, peResult);
162 for(Object peData : peResult){
163 policyEntity = (PolicyEntity) peData;
164 status = deletePolicyEntityData(em, policyEntity);
167 status = "PolicyInPDP";
169 if(status.equals("error")){
170 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
171 response.addHeader("error", "unknown");
172 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
174 }else if(status.equals("PolicyInPDP")){
175 PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
176 response.addHeader("error", "unknown");
177 response.setStatus(HttpServletResponse.SC_CONFLICT);
181 policyVersionDeleted = true;
184 policyVersionDeleted = false;
187 }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")){
188 boolean groupCheck = checkPolicyGroupEntity(em, con, peResult);
190 policyEntity = (PolicyEntity) peResult.get(0);
191 status = deletePolicyEntityData(em, policyEntity);
193 status = "PolicyInPDP";
196 if(status.equals("error")){
197 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
198 response.addHeader("error", "unknown");
199 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
201 }else if(status.equals("PolicyInPDP")){
202 PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
203 response.addHeader("error", "unknown");
204 response.setStatus(HttpServletResponse.SC_CONFLICT);
207 if(currentVersion > 1){
208 if(!peResult.isEmpty()){
209 for(Object object : peResult){
210 policyEntity = (PolicyEntity) object;
211 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
212 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
213 if(policyEntityVersion > highestVersion){
214 highestVersion = policyEntityVersion;
218 pVersion.setActiveVersion(highestVersion);
219 pVersion.setHigherVersion(highestVersion);
221 policyVersionDeleted = true;
222 em.persist(pVersion);
224 policyVersionDeleted = false;
228 policyVersionDeleted = true;
231 policyVersionDeleted = false;
237 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
238 response.addHeader("error", "unknown");
239 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
243 em.getTransaction().commit();
245 em.getTransaction().rollback();
246 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
247 response.addHeader("error", "deleteDB");
248 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
255 if (policyVersionDeleted) {
256 response.setStatus(HttpServletResponse.SC_OK);
257 response.addHeader("successMapKey", "success");
258 response.addHeader("operation", "delete");
261 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
262 response.addHeader("error", "unknown");
263 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
268 public String deletePolicyEntityData(EntityManager em, PolicyEntity policyEntity) throws SQLException{
269 PolicyElasticSearchController controller = new PolicyElasticSearchController();
270 PolicyRestAdapter policyData = new PolicyRestAdapter();
271 String policyName = policyEntity.getPolicyName();
273 if(policyName.contains("Config_")){
274 em.remove(policyEntity.getConfigurationData());
275 }else if(policyName.contains("Action_")){
276 em.remove(policyEntity.getActionBodyEntity());
278 String searchPolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
279 policyData.setNewFileName(searchPolicyName);
280 controller.deleteElk(policyData);
281 em.remove(policyEntity);
288 public boolean checkPolicyGroupEntity(EntityManager em, Connection con, List<?> peResult) throws SQLException{
289 for(Object peData : peResult){
290 PolicyEntity policyEntity = (PolicyEntity) peData;
293 st = con.createStatement();
294 rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'");
295 boolean gEntityList = rs.next();
304 public void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws IOException {
305 String policyName = request.getParameter("policyName");
306 String groupId = request.getParameter("groupId");
307 String responseString = null;
308 // for PUT operations the group may or may not need to exist before the operation can be done
309 EcompPDPGroup group = null;
311 group = XACMLPapServlet.getPAPEngine().getGroup(groupId);
312 } catch (PAPException e) {
313 PolicyLogger.error("Exception occured While PUT operation is performing for PDP Group"+e);
316 String message = "Unknown groupId '" + groupId + "'";
317 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
318 loggingContext.transactionEnded();
319 PolicyLogger.audit("Transaction Failed - See Error.log");
320 response.addHeader("error", "UnknownGroup");
321 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
324 loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup");
325 if (policyName.contains("xml")) {
326 PolicyLogger.debug("The full file name including the extension was provided for policyName.. continue.");
328 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
329 + "policyName must be the full name of the file to be deleted including version and extension";
330 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... "
331 + "policyName must be the full name of the file to be deleted including version and extension");
332 response.addHeader("error", message);
333 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
336 RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group);
337 PDPPolicy policy = group.getPolicy(policyName);
338 if (policy != null) {
340 if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) {
341 if (preSafetyCheck(policy)) {
342 PolicyLogger.debug("Precheck Successful.");
346 removePolicy.prepareToRemove(policy);
347 EcompPDPGroup updatedGroup = removePolicy.getUpdatedObject();
348 responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext);
350 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.";
351 PolicyLogger.error(message);
352 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP.");
353 response.addHeader("error", message);
354 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
358 if (responseString.equals("success")) {
359 PolicyLogger.info("Policy successfully deleted!");
360 PolicyLogger.audit("Policy successfully deleted!");
361 response.setStatus(HttpServletResponse.SC_OK);
362 response.addHeader("successMapKey", "success");
363 response.addHeader("operation", "delete");
365 } else if (responseString.equals("No Group")) {
366 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input.";
367 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input.");
368 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
369 response.addHeader("error", "groupUpdate");
370 response.addHeader("message", message);
372 } else if (responseString.equals("DB Error")) {
373 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database");
374 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
375 response.addHeader("error", "deleteDB");
378 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
379 response.addHeader("error", "unknown");
380 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
385 private String deletePolicyFromPDPGroup (EcompPDPGroup group, ECOMPLoggingContext loggingContext){
386 PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction();
387 String response = null;
388 loggingContext.setServiceName("API:PAP.DeleteHandler");
389 EcompPDPGroup existingGroup = null;
391 existingGroup = XACMLPapServlet.getPAPEngine().getGroup(group.getId());
392 } catch (PAPException e1) {
393 PolicyLogger.error("Exception occured While Deleting Policy From PDP Group"+e1);
395 if (group == null || ! (group instanceof StdPDPGroup) || ! (group.getId().equals(existingGroup.getId()))) {
396 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingGroup.getId() + " objectFromJSON="+group);
397 loggingContext.transactionEnded();
398 PolicyLogger.audit("Transaction Failed - See Error.log");
399 response = "No Group";
402 // The Path on the PAP side is not carried on the RESTful interface with the AC
403 // (because it is local to the PAP)
404 // so we need to fill that in before submitting the group for update
405 ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory());
407 acPutTransaction.updateGroup(group, "XACMLPapServlet.doAPIDelete");
408 } catch(Exception e){
409 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
410 +"group="+existingGroup.getId());
411 response = "DB Error";
415 XACMLPapServlet.getPAPEngine().updateGroup(group);
416 } catch (PAPException e) {
417 PolicyLogger.error("Exception occured While Updating PDP Groups"+e);
418 response = "error in updateGroup method";
420 PolicyLogger.debug("Group '" + group.getId() + "' updated");
421 acPutTransaction.commitTransaction();
422 // Group changed, which might include changing the policies
424 newgroup = existingGroup;
425 } catch (Exception e) {
426 PolicyLogger.error("Exception occured in Group Change Method"+e);
427 response = "error in groupChanged method";
430 response = "success";
431 PolicyLogger.audit("Policy successfully deleted!");
432 PolicyLogger.audit("Transaction Ended Successfully");
434 loggingContext.transactionEnded();
435 PolicyLogger.audit("Transaction Ended");
439 public EcompPDPGroup getDeletedGroup(){
443 public boolean preSafetyCheck(PDPPolicy policy) {
447 public static DeleteHandler getInstance() {
449 Class<?> deleteHandler = Class.forName(XACMLProperties.getProperty("deletePolicy.impl.className", DeleteHandler.class.getName()));
450 DeleteHandler instance = (DeleteHandler) deleteHandler.newInstance();
452 } catch (Exception e) {
453 PolicyLogger.error(e.getMessage());