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