Merge "use hibernate and breakup dbdao and papservlet"
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / HandleIncomingNotifications.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2019 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
21 package org.onap.policy.pap.xacml.rest.components;
22
23 import com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.api.pap.PDPPolicy;
25 import com.att.research.xacml.util.XACMLProperties;
26 import java.io.ByteArrayInputStream;
27 import java.io.File;
28 import java.io.FileWriter;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.List;
37 import javax.persistence.PersistenceException;
38 import org.apache.commons.io.FilenameUtils;
39 import org.hibernate.Query;
40 import org.hibernate.Session;
41 import org.hibernate.SessionFactory;
42 import org.onap.policy.common.logging.eelf.MessageCodes;
43 import org.onap.policy.common.logging.eelf.PolicyLogger;
44 import org.onap.policy.common.logging.flexlogger.FlexLogger;
45 import org.onap.policy.common.logging.flexlogger.Logger;
46 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
47 import org.onap.policy.rest.XACMLRestProperties;
48 import org.onap.policy.rest.dao.PolicyDBException;
49 import org.onap.policy.rest.jpa.GroupEntity;
50 import org.onap.policy.rest.jpa.PdpEntity;
51 import org.onap.policy.rest.jpa.PolicyEntity;
52 import org.onap.policy.xacml.api.pap.OnapPDP;
53 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
54 import org.onap.policy.xacml.std.pap.StdPDPGroup;
55 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.stereotype.Component;
58
59 @Component
60 public class HandleIncomingNotifications {
61
62     private static final Logger logger = FlexLogger.getLogger(HandleIncomingNotifications.class);
63
64     private static final String POLICY_NOTIFICATION = "policy";
65     private static final String PDP_NOTIFICATION = "pdp";
66     private static final String GROUP_NOTIFICATION = "group";
67     public static final String JSON_CONFIG = "JSON";
68     public static final String XML_CONFIG = "XML";
69     public static final String PROPERTIES_CONFIG = "PROPERTIES";
70     public static final String OTHER_CONFIG = "OTHER";
71     public static final String AUDIT_USER = "audit";
72
73
74     private static SessionFactory sessionfactory;
75
76     @Autowired
77     public HandleIncomingNotifications(SessionFactory sessionfactory) {
78         HandleIncomingNotifications.sessionfactory = sessionfactory;
79     }
80
81     public HandleIncomingNotifications() {
82         // Default Constructor
83     }
84
85     public void handleIncomingHttpNotification(String url, String entityId, String entityType, String extraData,
86             XACMLPapServlet xacmlPapServlet) {
87         logger.info("DBDao url: " + url + " has reported an update on " + entityType + " entity " + entityId);
88         PolicyDBDaoTransaction transaction = PolicyDBDao.getPolicyDBDaoInstance().getNewTransaction();
89         // although its named retries, this is the total number of tries
90         int retries;
91         try {
92             retries = Integer
93                     .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INCOMINGNOTIFICATION_TRIES));
94         } catch (Exception e) {
95             logger.error("xacml.rest.pap.incomingnotification.tries property not set, using a default of 3." + e);
96             retries = 3;
97         }
98         // if someone sets it to some dumb value, we need to make sure it will
99         // try at least once
100         if (retries < 1) {
101             retries = 1;
102         }
103         int pauseBetweenRetries = 1000;
104         switch (entityType) {
105
106             case POLICY_NOTIFICATION:
107                 for (int i = 0; i < retries; i++) {
108                     try {
109                         handleIncomingPolicyChange(entityId);
110                         break;
111                     } catch (Exception e) {
112                         logger.debug(e);
113                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
114                                 "Caught exception on handleIncomingPolicyChange(" + url + ", " + entityId + ", "
115                                         + extraData + ")");
116                     }
117                     try {
118                         Thread.sleep(pauseBetweenRetries);
119                     } catch (InterruptedException ie) {
120                         Thread.currentThread().interrupt();
121                         break;
122                     }
123                 }
124                 break;
125             case PDP_NOTIFICATION:
126                 for (int i = 0; i < retries; i++) {
127                     try {
128                         handleIncomingPdpChange(entityId, transaction);
129                         break;
130                     } catch (Exception e) {
131                         logger.debug(e);
132                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
133                                 "Caught exception on handleIncomingPdpChange(" + url + ", " + entityId + ", "
134                                         + transaction + ")");
135                     }
136                     try {
137                         Thread.sleep(pauseBetweenRetries);
138                     } catch (InterruptedException ie) {
139                         Thread.currentThread().interrupt();
140                         break;
141                     }
142                 }
143                 break;
144             case GROUP_NOTIFICATION:
145                 for (int i = 0; i < retries; i++) {
146                     try {
147                         handleIncomingGroupChange(entityId, extraData, transaction);
148                         break;
149                     } catch (Exception e) {
150                         logger.debug(e);
151                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
152                                 "Caught exception on handleIncomingGroupChange(" + url + ", " + entityId + ", "
153                                         + extraData + ", " + transaction + ", " + xacmlPapServlet + ")");
154                     }
155                     try {
156                         Thread.sleep(pauseBetweenRetries);
157                     } catch (InterruptedException ie) {
158                         Thread.currentThread().interrupt();
159                         break;
160                     }
161                 }
162                 break;
163         }
164         // no changes should be being made in this function, we still need to
165         // close
166         transaction.rollbackTransaction();
167     }
168
169     private void handleIncomingGroupChange(String groupId, String extraData, PolicyDBDaoTransaction transaction)
170             throws PAPException, PolicyDBException {
171         GroupEntity groupRecord = null;
172         long groupIdLong = -1;
173         try {
174             groupIdLong = Long.parseLong(groupId);
175         } catch (NumberFormatException e) {
176             throw new IllegalArgumentException("groupId " + groupId + " cannot be parsed into a long");
177         }
178         try {
179             groupRecord = transaction.getGroup(groupIdLong);
180         } catch (Exception e) {
181             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
182                     "Caught Exception trying to get pdp group record with transaction.getGroup(" + groupIdLong + ");");
183             throw new PAPException("Could not get local group " + groupIdLong);
184         }
185         if (groupRecord == null) {
186             throw new PersistenceException("The group record returned is null");
187         }
188         // compare to local fs
189         // does group folder exist
190         OnapPDPGroup localGroup = null;
191         try {
192             localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId());
193         } catch (Exception e) {
194             logger.warn("Caught PAPException trying to get local pdp group with papEngine.getGroup(" + groupId + ");",
195                     e);
196         }
197         if (localGroup == null && extraData != null) {
198             // here we can try to load an old group id from the extraData
199             try {
200                 localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(extraData);
201             } catch (Exception e) {
202                 logger.warn(
203                         "Caught PAPException trying to get local pdp group with papEngine.getGroup(" + extraData + ");",
204                         e);
205             }
206         }
207         if (localGroup != null && groupRecord.isDeleted()) {
208             OnapPDPGroup newLocalGroup = null;
209             if (extraData != null) {
210                 try {
211                     newLocalGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(extraData);
212                 } catch (PAPException e) {
213                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
214                             "Caught PAPException trying to get new pdp group with papEngine.getGroup(" + extraData
215                                     + ");");
216                 }
217             }
218             try {
219                 PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().removeGroup(localGroup, newLocalGroup);
220             } catch (NullPointerException | PAPException e) {
221                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
222                         "Caught PAPException trying to get remove pdp group with papEngine.removeGroup(" + localGroup
223                                 + ", " + newLocalGroup + ");");
224                 throw new PAPException("Could not remove group " + groupId);
225             }
226         } else if (localGroup == null) {
227             // creating a new group
228             try {
229                 PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newGroup(groupRecord.getgroupName(),
230                         groupRecord.getDescription());
231             } catch (NullPointerException | PAPException e) {
232                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
233                         "Caught PAPException trying to create pdp group with papEngine.newGroup(groupRecord.getgroupName(), groupRecord.getDescription());");
234                 throw new PAPException("Could not create group " + groupRecord);
235             }
236             try {
237                 localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId());
238             } catch (PAPException e1) {
239                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR,
240                         "Caught PAPException trying to get pdp group we just created with papEngine.getGroup(groupRecord.getGroupId());\nAny PDPs or policies in the new group may not have been added");
241                 return;
242             }
243             // add possible pdps to group
244             List<?> pdpsInGroup = transaction.getPdpsInGroup(Long.parseLong(groupRecord.getGroupId()));
245             for (Object pdpO : pdpsInGroup) {
246                 PdpEntity pdp = (PdpEntity) pdpO;
247                 try {
248                     PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newPDP(pdp.getPdpId(), localGroup,
249                             pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());
250                 } catch (NullPointerException | PAPException e) {
251                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
252                             "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());");
253                     throw new PAPException("Could not create pdp " + pdp);
254                 }
255             }
256             // add possible policies to group (file system only, apparently)
257         } else {
258             if (!(localGroup instanceof StdPDPGroup)) {
259                 throw new PAPException("group is not a StdPDPGroup");
260             }
261             // clone the object
262             // because it will be comparing the new group to its own version
263             StdPDPGroup localGroupClone = new StdPDPGroup(localGroup.getId(), localGroup.isDefaultGroup(),
264                     localGroup.getName(), localGroup.getDescription(), ((StdPDPGroup) localGroup).getDirectory());
265             localGroupClone.setOnapPdps(localGroup.getOnapPdps());
266             localGroupClone.setPipConfigs(localGroup.getPipConfigs());
267             localGroupClone.setStatus(localGroup.getStatus());
268             // we are updating a group or adding a policy or changing default
269             // set default if it should be
270             if (!localGroupClone.isDefaultGroup() && groupRecord.isDefaultGroup()) {
271                 try {
272                     PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().setDefaultGroup(localGroup);
273                     return;
274                 } catch (PAPException e) {
275                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
276                             "Caught PAPException trying to set default group with papEngine.SetDefaultGroup("
277                                     + localGroupClone + ");");
278                     throw new PAPException("Could not set default group to " + localGroupClone);
279                 }
280             }
281             boolean needToUpdate = false;
282             if (updateGroupPoliciesInFileSystem(localGroupClone, localGroup, groupRecord, transaction)) {
283                 needToUpdate = true;
284             }
285             if (!PolicyDBDao.stringEquals(localGroupClone.getId(), groupRecord.getGroupId())
286                     || !PolicyDBDao.stringEquals(localGroupClone.getName(), groupRecord.getgroupName())) {
287                 // changing ids
288                 // we do not want to change the id, the papEngine will do this
289                 // for us, it needs to know the old id
290                 localGroupClone.setName(groupRecord.getgroupName());
291                 needToUpdate = true;
292             }
293             if (!PolicyDBDao.stringEquals(localGroupClone.getDescription(), groupRecord.getDescription())) {
294                 localGroupClone.setDescription(groupRecord.getDescription());
295                 needToUpdate = true;
296             }
297             if (needToUpdate) {
298                 try {
299                     PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().updateGroup(localGroupClone);
300                 } catch (PAPException e) {
301                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
302                             "Caught PAPException trying to update group with papEngine.updateGroup(" + localGroupClone
303                                     + ");");
304                     throw new PAPException("Could not update group " + localGroupClone);
305                 }
306             }
307         }
308     }
309
310     // this will also handle removes, since incoming pdpGroup has no policies
311     // internally, we are just going to add them all in from the db
312     private boolean updateGroupPoliciesInFileSystem(OnapPDPGroup pdpGroup, OnapPDPGroup oldPdpGroup,
313             GroupEntity groupRecord, PolicyDBDaoTransaction transaction) throws PAPException, PolicyDBException {
314         if (!(pdpGroup instanceof StdPDPGroup)) {
315             throw new PAPException("group is not a StdPDPGroup");
316         }
317         StdPDPGroup group = (StdPDPGroup) pdpGroup;
318         // this must always be true since we don't explicitly know when a delete
319         // is occuring
320         boolean didUpdate = true;
321         HashMap<String, PDPPolicy> currentPolicySet = new HashMap<>(oldPdpGroup.getPolicies().size());
322         HashSet<PDPPolicy> newPolicySet = new HashSet<>();
323         for (PDPPolicy pdpPolicy : oldPdpGroup.getPolicies()) {
324             currentPolicySet.put(pdpPolicy.getId(), pdpPolicy);
325         }
326         for (PolicyEntity policy : groupRecord.getPolicies()) {
327             String pdpPolicyName =
328                     PolicyDBDao.getPolicyDBDaoInstance().getPdpPolicyName(policy.getPolicyName(), policy.getScope());
329             if (group.getPolicy(pdpPolicyName) == null) {
330                 didUpdate = true;
331                 if (currentPolicySet.containsKey(pdpPolicyName)) {
332                     newPolicySet.add(currentPolicySet.get(pdpPolicyName));
333                 } else {
334                     logger.info(
335                             "PolicyDBDao: Adding the new policy to the PDP group after notification: " + pdpPolicyName);
336                     InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes());
337                     group.copyPolicyToFile(pdpPolicyName, policyStream);
338                     ((StdPDPPolicy) (group.getPolicy(pdpPolicyName))).setName(PolicyDBDao.getPolicyDBDaoInstance()
339                             .removeExtensionAndVersionFromPolicyName(pdpPolicyName));
340                     try {
341                         policyStream.close();
342                     } catch (IOException e) {
343                         didUpdate = false;
344                         PolicyLogger.error(e.getMessage() + e);
345                     }
346                 }
347             }
348         }
349         logger.info("PolicyDBDao: Adding updated policies to group after notification.");
350         if (didUpdate) {
351             newPolicySet.addAll(group.getPolicies());
352             group.setPolicies(newPolicySet);
353         }
354         return didUpdate;
355     }
356
357     private void handleIncomingPdpChange(String pdpId, PolicyDBDaoTransaction transaction) throws PAPException {
358         // get pdp
359         long pdpIdLong = -1;
360         try {
361             pdpIdLong = Long.parseLong(pdpId);
362         } catch (NumberFormatException e) {
363             throw new IllegalArgumentException("pdpId " + pdpId + " cannot be parsed into a long");
364         }
365         PdpEntity pdpRecord = null;
366         try {
367             pdpRecord = transaction.getPdp(pdpIdLong);
368         } catch (Exception e) {
369             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
370                     "Caught Exception trying to get pdp record with transaction.getPdp(" + pdpIdLong + ");");
371             throw new PAPException("Could not get local pdp " + pdpIdLong);
372         }
373         if (pdpRecord == null) {
374             throw new PersistenceException("The pdpRecord returned is null");
375         }
376         OnapPDP localPdp = null;
377         try {
378             localPdp = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getPDP(pdpRecord.getPdpId());
379         } catch (PAPException e) {
380             logger.warn("Caught PAPException trying to get local pdp  with papEngine.getPDP(" + pdpId + ");", e);
381         }
382         if (localPdp != null && pdpRecord.isDeleted()) {
383             try {
384                 PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().removePDP(localPdp);
385             } catch (PAPException e) {
386                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
387                         "Caught PAPException trying to get remove pdp with papEngine.removePDP(" + localPdp + ");");
388                 throw new PAPException("Could not remove pdp " + pdpId);
389             }
390         } else if (localPdp == null) {
391             // add new pdp
392             // get group
393             OnapPDPGroup localGroup = null;
394             try {
395                 localGroup =
396                         PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(pdpRecord.getGroup().getGroupId());
397             } catch (PAPException e1) {
398                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR,
399                         "Caught PAPException trying to get local group to add pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());");
400                 throw new PAPException("Could not get local group");
401             }
402             try {
403                 PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newPDP(pdpRecord.getPdpId(), localGroup,
404                         pdpRecord.getPdpName(), pdpRecord.getDescription(), pdpRecord.getJmxPort());
405             } catch (NullPointerException | PAPException e) {
406                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
407                         "Caught PAPException trying to create pdp with papEngine.newPDP(" + pdpRecord.getPdpId() + ", "
408                                 + localGroup + ", " + pdpRecord.getPdpName() + ", " + pdpRecord.getDescription() + ", "
409                                 + pdpRecord.getJmxPort() + ");");
410                 throw new PAPException("Could not create pdp " + pdpRecord);
411             }
412         } else {
413             boolean needToUpdate = false;
414             if (!PolicyDBDao.stringEquals(localPdp.getId(), pdpRecord.getPdpId())
415                     || !PolicyDBDao.stringEquals(localPdp.getName(), pdpRecord.getPdpName())) {
416                 // again, we don't want to change the id, the papEngine will do
417                 // this
418                 localPdp.setName(pdpRecord.getPdpName());
419                 needToUpdate = true;
420             }
421             if (!PolicyDBDao.stringEquals(localPdp.getDescription(), pdpRecord.getDescription())) {
422                 localPdp.setDescription(pdpRecord.getDescription());
423                 needToUpdate = true;
424             }
425             String localPdpGroupId = null;
426             try {
427                 localPdpGroupId = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getPDPGroup(localPdp).getId();
428             } catch (PAPException e) {
429                 // could be null or something, just warn at this point
430                 logger.warn(
431                         "Caught PAPException trying to get id of local group that pdp is in with localPdpGroupId = papEngine.getPDPGroup(localPdp).getId();",
432                         e);
433             }
434             if (!PolicyDBDao.stringEquals(localPdpGroupId, pdpRecord.getGroup().getGroupId())) {
435                 OnapPDPGroup newPdpGroup = null;
436                 try {
437                     newPdpGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine()
438                             .getGroup(pdpRecord.getGroup().getGroupId());
439                 } catch (PAPException e) {
440                     // ok, now we have an issue. Time to stop things
441                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
442                             "Caught PAPException trying to get id of local group to move pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());");
443                     throw new PAPException("Could not get local group");
444                 }
445                 try {
446                     PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().movePDP(localPdp, newPdpGroup);
447                 } catch (PAPException e) {
448                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
449                             "Caught PAPException trying to move pdp with papEngine.movePDP(localPdp, newPdpGroup);");
450                     throw new PAPException("Could not move pdp " + localPdp);
451                 }
452             }
453             if (localPdp.getJmxPort() != pdpRecord.getJmxPort()) {
454                 localPdp.setJmxPort(pdpRecord.getJmxPort());
455                 needToUpdate = true;
456             }
457             if (needToUpdate) {
458                 try {
459                     PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().updatePDP(localPdp);
460                 } catch (PAPException e) {
461                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
462                             "Caught PAPException trying to update pdp with papEngine.updatePdp(" + localPdp + ");");
463                     throw new PAPException("Could not update pdp " + localPdp);
464                 }
465             }
466         }
467         // compare to local situation
468         // call command to update
469     }
470
471     private void handleIncomingPolicyChange(String policyId) {
472         String policyName = null;
473         Session session = sessionfactory.openSession();
474         Query getPolicyEntityQuery = session.getNamedQuery("PolicyEntity.FindById");
475         getPolicyEntityQuery.setParameter("id", Long.valueOf(policyId));
476
477         @SuppressWarnings("unchecked")
478         List<PolicyEntity> policies = getPolicyEntityQuery.list();
479         PolicyEntity policy = null;
480         if (!policies.isEmpty()) {
481             policy = policies.get(0);
482         }
483         String action = "unknown action";
484         try {
485             if (policy != null) {
486                 policyName = policy.getPolicyName();
487                 logger.info("Deleting old Policy Config File for " + policy.getPolicyName());
488                 action = "delete";
489                 Path subFile = null;
490
491                 if (policy.getConfigurationData() != null) {
492                     subFile =
493                             getPolicySubFile(policy.getConfigurationData().getConfigurationName(), PolicyDBDao.CONFIG);
494                 } else if (policy.getActionBodyEntity() != null) {
495                     subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), PolicyDBDao.ACTION);
496                 }
497
498                 if (subFile != null) {
499                     Files.deleteIfExists(subFile);
500                 }
501                 if (policy.getConfigurationData() != null) {
502                     writePolicySubFile(policy, PolicyDBDao.CONFIG);
503                 } else if (policy.getActionBodyEntity() != null) {
504                     writePolicySubFile(policy, action);
505                 }
506             }
507         } catch (IOException e1) {
508             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR,
509                     "Error occurred while performing [" + action + "] of Policy File: " + policyName);
510         } finally {
511             session.close();
512         }
513     }
514
515     private boolean writePolicySubFile(PolicyEntity policy, String policyType) {
516         logger.info("writePolicySubFile with policyName[" + policy.getPolicyName() + "] and policyType[" + policyType
517                 + "]");
518         String type = null;
519         String subTypeName = null;
520         String subTypeBody = null;
521         if (PolicyDBDao.CONFIG.equalsIgnoreCase(policyType)) {
522             type = PolicyDBDao.CONFIG;
523             subTypeName = FilenameUtils.removeExtension(policy.getConfigurationData().getConfigurationName());
524             subTypeBody = policy.getConfigurationData().getConfigBody();
525
526             String configType = policy.getConfigurationData().getConfigType();
527
528             if (configType != null) {
529                 if (configType.equals(JSON_CONFIG)) {
530                     subTypeName = subTypeName + ".json";
531                 }
532                 if (configType.equals(XML_CONFIG)) {
533                     subTypeName = subTypeName + ".xml";
534                 }
535                 if (configType.equals(PROPERTIES_CONFIG)) {
536                     subTypeName = subTypeName + ".properties";
537                 }
538                 if (configType.equals(OTHER_CONFIG)) {
539                     subTypeName = subTypeName + ".txt";
540                 }
541             }
542         } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policyType)) {
543             type = PolicyDBDao.ACTION;
544             subTypeName = policy.getActionBodyEntity().getActionBodyName();
545             subTypeBody = policy.getActionBodyEntity().getActionBody();
546         }
547         Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), type);
548
549         if (subTypeBody == null) {
550             subTypeBody = "";
551         }
552         boolean success = false;
553         try {
554             Files.deleteIfExists(Paths.get(filePath.toString(), subTypeName));
555             File file = Paths.get(filePath.toString(), subTypeName).toFile();
556             boolean value = file.createNewFile();
557             logger.debug("New file created successfully" + value);
558             try (FileWriter fileWriter = new FileWriter(file, false)) {
559                 // false to overwrite
560                 fileWriter.write(subTypeBody);
561                 fileWriter.close();
562                 success = true;
563             }
564         } catch (Exception e) {
565             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
566                     "Exception occured while creating Configuration File for Policy : " + policy.getPolicyName());
567         }
568         return success;
569     }
570
571     Path getPolicySubFile(String inputFileName, String subFileType) {
572         String filename = inputFileName;
573         logger.info("getPolicySubFile(" + filename + ", " + subFileType + ")");
574         Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), subFileType);
575         File file = null;
576
577         filename = FilenameUtils.removeExtension(filename);
578
579         for (File tmpFile : filePath.toFile().listFiles()) {
580             if (FilenameUtils.removeExtension(tmpFile.getName()).equals(filename)) {
581                 file = tmpFile;
582             }
583         }
584
585         Path finalPath = null;
586         if (file != null) {
587             finalPath = Paths.get(file.getAbsolutePath());
588         }
589
590         logger.info("end of getPolicySubFile: " + finalPath);
591         return finalPath;
592     }
593 }