Upgrade to drools 7.28.0.Final
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / PolicyDBDao.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
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.InputStream;
30 import java.net.URI;
31 import java.nio.charset.StandardCharsets;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.LinkedList;
38 import java.util.List;
39 import java.util.Set;
40
41 import javax.persistence.PersistenceException;
42
43 import org.apache.commons.io.FilenameUtils;
44 import org.hibernate.Criteria;
45 import org.hibernate.LockMode;
46 import org.hibernate.Query;
47 import org.hibernate.Session;
48 import org.hibernate.SessionFactory;
49 import org.hibernate.criterion.Restrictions;
50 import org.onap.policy.common.logging.eelf.MessageCodes;
51 import org.onap.policy.common.logging.eelf.PolicyLogger;
52 import org.onap.policy.common.logging.flexlogger.FlexLogger;
53 import org.onap.policy.common.logging.flexlogger.Logger;
54 import org.onap.policy.rest.XacmlRestProperties;
55 import org.onap.policy.rest.adapter.PolicyRestAdapter;
56 import org.onap.policy.rest.dao.PolicyDBException;
57 import org.onap.policy.rest.jpa.ActionBodyEntity;
58 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
59 import org.onap.policy.rest.jpa.DatabaseLockEntity;
60 import org.onap.policy.rest.jpa.GroupEntity;
61 import org.onap.policy.rest.jpa.PdpEntity;
62 import org.onap.policy.rest.jpa.PolicyDBDaoEntity;
63 import org.onap.policy.rest.jpa.PolicyEntity;
64 import org.onap.policy.utils.PeCryptoUtils;
65 import org.onap.policy.xacml.api.XACMLErrorConstants;
66 import org.onap.policy.xacml.api.pap.OnapPDP;
67 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
68 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
69 import org.onap.policy.xacml.std.pap.StdPDPGroup;
70 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
71 import org.springframework.beans.factory.annotation.Autowired;
72 import org.springframework.stereotype.Component;
73
74 @Component
75 public class PolicyDBDao {
76     private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class);
77     public static final String JSON_CONFIG = "JSON";
78     public static final String XML_CONFIG = "XML";
79     public static final String PROPERTIES_CONFIG = "PROPERTIES";
80     public static final String OTHER_CONFIG = "OTHER";
81     public static final String AUDIT_USER = "audit";
82
83     public static final String CONFIG = "Config";
84     public static final String ACTION = "Action";
85     public static final String GROUP_ID = "groupId";
86     public static final String DELETED = "deleted";
87     public static final String GROUPENTITY_SELECT =
88             "SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted";
89     public static final String PDPENTITY_SELECT =
90             "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted";
91     public static final String GROUP_NOT_FOUND = "The group could not be found with id ";
92     public static final String FOUND_IN_DB_NOT_DEL = " were found in the database that are not deleted";
93     public static final String MORE_THAN_ONE_PDP = "Somehow, more than one pdp with the same id ";
94     public static final String DELETED_STATUS_FOUND = " and deleted status were found in the database";
95     public static final String DUPLICATE_GROUPID = "Somehow, more than one group with the same id ";
96     public static final String PDP_ID = "pdpId";
97     public static final String QUERY_FAILED_FOR_GROUP = "Query failed trying to check for existing group";
98     public static final String QUERY_FAILED_GET_GROUP = "Query failed trying to get group ";
99     public static final String SCOPE = "scope";
100     public static final String POLICYDBDAO_VAR = "PolicyDBDao";
101     public static final String DUP_POLICYID = "Somehow, more than one policy with the id ";
102     public static final String FOUND_IN_DB = " were found in the database";
103     private static PolicyDBDao currentInstance = null;
104     private static boolean isJunit = false;
105     private static SessionFactory sessionfactory;
106     private List<?> otherServers;
107     private PAPPolicyEngine papEngine;
108
109     /**
110      * Gets the current instance of PolicyDBDao.
111      *
112      * @return The instance of PolicyDBDao or throws exception if the given instance is null.
113      * @throws IllegalStateException if a PolicyDBDao instance is null. Call
114      *         createPolicyDBDaoInstance (EntityManagerFactory emf) to get this.
115      */
116     public static PolicyDBDao getPolicyDBDaoInstance() {
117         logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called");
118         if (currentInstance != null) {
119             return currentInstance;
120         } else {
121             currentInstance = new PolicyDBDao("init");
122         }
123         return currentInstance;
124     }
125
126     public void setPapEngine(PAPPolicyEngine papEngine2) {
127         this.papEngine = papEngine2;
128     }
129
130     @Autowired
131     public PolicyDBDao(SessionFactory sessionFactory) {
132         PolicyDBDao.sessionfactory = sessionFactory;
133     }
134
135     public PolicyDBDao() {
136         // Default Constructor
137     }
138
139     public PolicyDBDao(String init) {
140         // not needed in this release
141         if (!register()) {
142             PolicyLogger
143                     .error("This server's PolicyDBDao instance could not be registered and may not reveive updates");
144         }
145
146         otherServers = getRemotePolicyDBDaoList();
147         if (logger.isDebugEnabled()) {
148             logger.debug("Number of remote PolicyDBDao instances: " + otherServers.size());
149         }
150         if (otherServers.isEmpty()) {
151             logger.warn("List of PolicyDBDao servers is empty or could not be retrieved");
152         }
153     }
154
155     // not static because we are going to be using the instance's emf
156     // waitTime in ms to wait for lock, or -1 to wait forever (no)
157     @SuppressWarnings("deprecation")
158     public void startTransactionSynced(Session session, int waitTime) {
159         logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + "\n   startTransactionSynced("
160                 + session + "," + waitTime + ") called\n\n");
161         DatabaseLockEntity lock = null;
162         session.beginTransaction();
163         try {
164             if (logger.isDebugEnabled()) {
165                 logger.debug("\n\nstartTransactionSynced():" + "\n   ATTEMPT to get the DB lock" + "\n\n");
166             }
167             lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, LockMode.PESSIMISTIC_WRITE);
168             if (logger.isDebugEnabled()) {
169                 logger.debug("\n\nstartTransactionSynced():" + "\n   GOT the DB lock" + "\n\n");
170             }
171         } catch (Exception e) {
172             logger.error("Exception Occured" + e);
173         }
174         if (lock == null) {
175             throw new IllegalStateException(
176                     "The lock row does not exist in the table. Please create a primary key with value = 1.");
177         }
178
179     }
180
181     /**
182      * Gets the list of other registered PolicyDBDaos from the database
183      *
184      * @return List (type PolicyDBDaoEntity) of other PolicyDBDaos
185      */
186     private List<?> getRemotePolicyDBDaoList() {
187         logger.debug("getRemotePolicyDBDaoList() as getRemotePolicyDBDaoList() called");
188         List<?> policyDBDaoEntityList = new LinkedList<>();
189         Session session = sessionfactory.openSession();
190         try {
191             Criteria cr = session.createCriteria(PolicyDBDaoEntity.class);
192             policyDBDaoEntityList = cr.list();
193         } catch (Exception e) {
194             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
195                     "Exception querying for other registered PolicyDBDaos");
196             logger.warn("List of remote PolicyDBDaos will be empty", e);
197         } finally {
198             try {
199                 session.close();
200             } catch (Exception e) {
201                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e);
202             }
203         }
204         return policyDBDaoEntityList;
205     }
206
207     public PolicyDBDaoTransaction getNewTransaction() {
208         logger.debug("getNewTransaction() as getNewTransaction() called");
209         return new PolicyDbDaoTransactionInstance("init");
210     }
211
212     /*
213      * Because the normal transactions are not used in audits, we can use the same transaction
214      * mechanism to get a transaction and obtain the emlock and the DB lock. We just need to provide
215      * different transaction timeout values in ms because the audit will run longer than normal
216      * transactions.
217      */
218     public PolicyDBDaoTransaction getNewAuditTransaction() {
219         logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called");
220         // Use the standard transaction wait time in ms
221         int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT));
222         // Use the (extended) audit timeout time in ms
223         int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT));
224         return new PolicyDbDaoTransactionInstance(auditTimeoutMs, auditWaitMs);
225     }
226
227     /**
228      * Checks if two strings are equal. Null strings ARE allowed.
229      *
230      * @param one A String or null to compare
231      * @param two A String or null to compare
232      */
233     public static boolean stringEquals(String one, String two) {
234         logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + ") called");
235         if (one == null && two == null) {
236             return true;
237         }
238         if (one == null || two == null) {
239             return false;
240         }
241         return one.equals(two);
242     }
243
244     /**
245      * Returns the url of this local pap server, removing the username and password, if they are
246      * present
247      *
248      * @return The url of this local pap server
249      */
250     public String[] getPapUrlUserPass() {
251         logger.debug("getPapUrl() as getPapUrl() called");
252         String url = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
253         if (url == null) {
254             return null;
255         }
256         return splitPapUrlUserPass(url);
257     }
258
259     public String[] splitPapUrlUserPass(String url) {
260         String[] urlUserPass = new String[3];
261         String[] commaSplit = url.split(",");
262         urlUserPass[0] = commaSplit[0];
263         if (commaSplit.length > 2) {
264             urlUserPass[1] = commaSplit[1];
265             urlUserPass[2] = commaSplit[2];
266         }
267         if (urlUserPass[1] == null || "".equals(urlUserPass[1])) {
268             String usernamePropertyValue = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID);
269             if (usernamePropertyValue != null) {
270                 urlUserPass[1] = usernamePropertyValue;
271             }
272         }
273         if (urlUserPass[2] == null || "".equals(urlUserPass[2])) {
274             String passwordPropertyValue =
275                     PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS));
276             if (passwordPropertyValue != null) {
277                 urlUserPass[2] = passwordPropertyValue;
278             }
279         }
280         // if there is no comma, for some reason there is no user name and
281         // password, so don't try to cut them off
282         return urlUserPass;
283     }
284
285     /**
286      * Register the PolicyDBDao instance in the PolicyDBDaoEntity table
287      *
288      * @return Boolean, were we able to register?
289      */
290     private boolean register() {
291         logger.debug("register() as register() called");
292         String[] url = getPapUrlUserPass();
293         // --- check URL length
294         if (url == null || url.length < 3) {
295             return false;
296         }
297         Session session = sessionfactory.openSession();
298         try {
299             startTransactionSynced(session, 1000);
300         } catch (IllegalStateException e) {
301             logger.debug("\nPolicyDBDao.register() caught an IllegalStateException: \n" + e + "\n");
302             DatabaseLockEntity lock;
303             lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1);
304             if (lock == null) {
305                 lock = new DatabaseLockEntity();
306                 lock.setKey(1);
307                 try {
308                     session.persist(lock);
309                     session.flush();
310                     session.getTransaction().commit();
311                     session.close();
312                 } catch (Exception e2) {
313                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
314                             "COULD NOT CREATE DATABASELOCK ROW.  WILL TRY ONE MORE TIME");
315                 }
316
317                 session = sessionfactory.openSession();
318                 try {
319                     startTransactionSynced(session, 1000);
320                 } catch (Exception e3) {
321                     String msg = "DATABASE LOCKING NOT WORKING. CONCURRENCY CONTROL NOT WORKING";
322                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e3, POLICYDBDAO_VAR, msg);
323                     throw new IllegalStateException("msg" + "\n" + e3);
324                 }
325             }
326         }
327         logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n");
328         PolicyDBDaoEntity foundPolicyDBDaoEntity = null;
329         Criteria cr = session.createCriteria(PolicyDBDaoEntity.class);
330         cr.add(Restrictions.eq("policyDBDaoUrl", url[0]));
331         List<?> data = cr.list();
332         if (!data.isEmpty()) {
333             foundPolicyDBDaoEntity = (PolicyDBDaoEntity) data.get(0);
334         }
335
336         // encrypt the password
337         String txt = PeCryptoUtils.encrypt(url[2]);
338         if (foundPolicyDBDaoEntity == null) {
339             PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity();
340             newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]);
341             newPolicyDBDaoEntity.setDescription("PAP server at " + url[0]);
342             newPolicyDBDaoEntity.setUsername(url[1]);
343             newPolicyDBDaoEntity.setPassword(txt);
344             try {
345                 session.persist(newPolicyDBDaoEntity);
346                 session.getTransaction().commit();
347             } catch (Exception e) {
348                 logger.debug(e);
349                 try {
350                     session.getTransaction().rollback();
351                 } catch (Exception e2) {
352                     logger.debug(e2);
353                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
354                             "Could not add new PolicyDBDao to the database");
355                 }
356             }
357         } else {
358             // just want to update in order to change modified date
359             if (url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())) {
360                 foundPolicyDBDaoEntity.setUsername(url[1]);
361             }
362             if (txt != null && !stringEquals(txt, foundPolicyDBDaoEntity.getPassword())) {
363                 foundPolicyDBDaoEntity.setPassword(txt);
364             }
365             foundPolicyDBDaoEntity.preUpdate();
366             try {
367                 session.getTransaction().commit();
368             } catch (Exception e) {
369                 logger.debug(e);
370                 try {
371                     session.getTransaction().rollback();
372                 } catch (Exception e2) {
373                     logger.debug(e2);
374                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
375                             "Could not update PolicyDBDao in the database");
376                 }
377             }
378         }
379         session.close();
380         logger.debug("\nPolicyDBDao.register(). Success!!\n");
381         return true;
382     }
383
384     /*
385      * This method is called during all pushPolicy transactions and makes sure the file system group
386      * is in sync with the database groupentity
387      */
388     public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity)
389             throws PAPException, PolicyDBException {
390
391         HashMap<String, PDPPolicy> currentPolicyMap = new HashMap<>();
392         HashSet<String> newPolicyIdSet = new HashSet<>();
393         HashSet<PDPPolicy> newPolicySet = new HashSet<>();
394
395         for (PDPPolicy pdpPolicy : pdpGroup.getPolicies()) {
396             currentPolicyMap.put(pdpPolicy.getId(), pdpPolicy);
397         }
398
399         for (PolicyEntity policy : groupentity.getPolicies()) {
400             String pdpPolicyId = getPdpPolicyName(policy.getPolicyName(), policy.getScope());
401             newPolicyIdSet.add(pdpPolicyId);
402
403             if (currentPolicyMap.containsKey(pdpPolicyId)) {
404                 newPolicySet.add(currentPolicyMap.get(pdpPolicyId));
405             } else {
406                 // convert PolicyEntity object to PDPPolicy
407                 String name = pdpPolicyId.replace(".xml", "");
408                 name = name.substring(0, name.lastIndexOf('.'));
409                 InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes());
410                 pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream);
411                 URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri();
412                 StdPDPPolicy newPolicy = null;
413                 try {
414                     newPolicy = new StdPDPPolicy(pdpPolicyId, true,
415                             removeExtensionAndVersionFromPolicyName(pdpPolicyId), location);
416                     newPolicySet.add(newPolicy);
417                     logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() + ", Location - " + location);
418                 } catch (Exception e) {
419                     logger.debug(e);
420                     PolicyLogger
421                             .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object "
422                                     + e.getMessage());
423                 }
424             }
425         }
426
427         for (String id : currentPolicyMap.keySet()) {
428             if (!newPolicyIdSet.contains(id)) {
429                 try {
430                     Files.delete(Paths.get(currentPolicyMap.get(id).getLocation()));
431                 } catch (Exception e) {
432                     logger.debug(e);
433                     PolicyLogger.error(
434                             "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. "
435                                     + e.getMessage());
436                 }
437             }
438         }
439
440         logger.info("PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync");
441         pdpGroup.setPolicies(newPolicySet);
442
443         return pdpGroup;
444     }
445
446     public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) throws PolicyDBException {
447         return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0];
448     }
449
450     /**
451      * Splits apart the policy name and version from a policy file path
452      *
453      * @param originalPolicyName: a policy file name ex: Config_policy.2.xml
454      * @return An array [0]: The policy name, [1]: the policy version, as a string
455      */
456     public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException {
457         String policyName = originalPolicyName;
458         String[] nameAndVersion = new String[2];
459         try {
460             policyName = removeFileExtension(policyName);
461             nameAndVersion[0] = policyName.substring(0, policyName.lastIndexOf('.'));
462             if (isNullOrEmpty(nameAndVersion[0])) {
463                 throw new PolicyDBException();
464             }
465         } catch (Exception e) {
466             nameAndVersion[0] = originalPolicyName;
467             logger.debug(e);
468         }
469         try {
470             nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.') + 1);
471             if (isNullOrEmpty(nameAndVersion[1])) {
472                 throw new PolicyDBException();
473             }
474         } catch (Exception e) {
475             nameAndVersion[1] = "1";
476             logger.debug(e);
477         }
478         return nameAndVersion;
479     }
480
481     public String getPdpPolicyName(String name, String scope) {
482         String finalName = "";
483         finalName += scope;
484         finalName += ".";
485         finalName += removeFileExtension(name);
486         finalName += ".xml";
487         return finalName;
488     }
489
490     private String removeFileExtension(String fileName) {
491         return fileName.substring(0, fileName.lastIndexOf('.'));
492     }
493
494     public void auditLocalDatabase(PAPPolicyEngine papEngine2) {
495         logger.debug("PolicyDBDao.auditLocalDatabase() is called");
496         try {
497             deleteAllGroupTables();
498             auditGroups(papEngine2);
499         } catch (Exception e) {
500             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "auditLocalDatabase() error");
501             logger.error("Exception Occured" + e);
502         }
503     }
504
505     public StdPDPGroup auditLocalFileSystem(StdPDPGroup group) {
506
507         logger.info("Starting Local File System group audit");
508         Session session = sessionfactory.openSession();
509         session.getTransaction().begin();
510
511         StdPDPGroup updatedGroup = null;
512         try {
513             Query groupQuery = session.createQuery(GROUPENTITY_SELECT);
514             groupQuery.setParameter(GROUP_ID, group.getId());
515             groupQuery.setParameter(DELETED, false);
516             List<?> groupQueryList = groupQuery.list();
517             if (groupQueryList != null && !groupQueryList.isEmpty()) {
518                 GroupEntity dbgroup = (GroupEntity) groupQueryList.get(0);
519                 updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup);
520                 logger.info("Group was updated during file system audit: " + updatedGroup.toString());
521             }
522         } catch (PAPException | PolicyDBException e) {
523             logger.error(e);
524         } catch (Exception e) {
525             logger.error(e);
526             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
527                     "Caught Exception trying to check if group exists groupQuery.getResultList()");
528             throw new PersistenceException("Query failed trying to check if group " + group.getId() + " exists");
529         }
530
531         session.getTransaction().commit();
532         session.close();
533
534         return updatedGroup;
535     }
536
537     /*
538      * This method is called at startup to recreate config data from DB to the file system.
539      *
540      */
541     public void synchronizeConfigDataInFileSystem() {
542
543         logger.info("Starting Local File System Config data Sync");
544         // sync both web apps Config and Action
545         syncConfigData(ConfigurationDataEntity.class, CONFIG);
546         syncConfigData(ActionBodyEntity.class, ACTION);
547     }
548
549     private <T> void syncConfigData(Class<T> cl, String type) {
550         Session session = sessionfactory.openSession();
551         try {
552             final Criteria configDataQuery = session.createCriteria(cl.getName());
553             @SuppressWarnings("unchecked")
554             final List<T> configDataResult = configDataQuery.list();
555             Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), type);
556
557             for (final T configData : configDataResult) {
558                 String configName = null;
559                 byte[] configBody;
560                 try {
561                     if (CONFIG.equalsIgnoreCase(type)) {
562                         configName = ((ConfigurationDataEntity) configData).getConfigurationName();
563                         configBody =
564                                 (((ConfigurationDataEntity) configData).getConfigBody() != null)
565                                         ? ((ConfigurationDataEntity) configData).getConfigBody()
566                                                 .getBytes(StandardCharsets.UTF_8)
567                                         : "".getBytes();
568                     } else {
569                         configName = ((ActionBodyEntity) configData).getActionBodyName();
570                         configBody = (((ActionBodyEntity) configData).getActionBody() != null)
571                                 ? ((ActionBodyEntity) configData).getActionBody().getBytes(StandardCharsets.UTF_8)
572                                 : "".getBytes();
573                     }
574                     Path filePath = Paths.get(webappsPath.toString(), configName);
575                     if (!filePath.toFile().exists()) {
576                         Files.write(filePath, configBody);
577                         logger.info("Created Config File from DB - " + filePath.toString());
578                     }
579                 } catch (Exception e) {
580                     // log and keep going
581                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
582                             "Exception occured while creating Configuration File - " + configName);
583                 }
584             }
585         } catch (final Exception exception) {
586             logger.error("Unable to synchronizeConfigDataInFileSystem", exception);
587         }
588         session.close();
589     }
590
591     public void deleteAllGroupTables() {
592         logger.debug("PolicyDBDao.deleteAllGroupTables() called");
593         Session session = sessionfactory.openSession();
594         session.getTransaction().begin();
595
596         Query deletePdpEntityEntityTableUpdate = session.getNamedQuery("PdpEntity.deleteAll");
597         deletePdpEntityEntityTableUpdate.executeUpdate();
598
599         Query deleteGroupEntityTableUpdate = session.getNamedQuery("GroupEntity.deleteAll");
600         deleteGroupEntityTableUpdate.executeUpdate();
601
602         session.getTransaction().commit();
603         session.close();
604     }
605
606     @SuppressWarnings("unchecked")
607     public void auditGroups(PAPPolicyEngine papEngine2) {
608         logger.debug("PolicyDBDao.auditGroups() called");
609
610         Session session = sessionfactory.openSession();
611         session.getTransaction().begin();
612         final String AUDIT_STR = "Audit";
613         try {
614
615             Set<OnapPDPGroup> groups = papEngine2.getOnapPDPGroups();
616
617             for (OnapPDPGroup grp : groups) {
618                 try {
619                     GroupEntity groupEntity = new GroupEntity();
620                     groupEntity.setGroupName(grp.getName());
621                     groupEntity.setDescription(grp.getDescription());
622                     groupEntity.setDefaultGroup(grp.isDefaultGroup());
623                     groupEntity.setCreatedBy(AUDIT_STR);
624                     groupEntity.setGroupId(createNewPDPGroupId(grp.getId()));
625                     groupEntity.setModifiedBy(AUDIT_STR);
626                     session.persist(groupEntity);
627                     Set<OnapPDP> pdps = grp.getOnapPdps();
628
629                     for (OnapPDP pdp : pdps) {
630                         PdpEntity pdpEntity = new PdpEntity();
631                         pdpEntity.setGroup(groupEntity);
632                         pdpEntity.setJmxPort(pdp.getJmxPort());
633                         pdpEntity.setPdpId(pdp.getId());
634                         pdpEntity.setPdpName(pdp.getName());
635                         pdpEntity.setModifiedBy(AUDIT_STR);
636                         pdpEntity.setCreatedBy(AUDIT_STR);
637                         session.persist(pdpEntity);
638                     }
639
640                     Set<PDPPolicy> policies = grp.getPolicies();
641
642                     for (PDPPolicy policy : policies) {
643                         try {
644                             String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId());
645                             if (stringArray == null) {
646                                 throw new IllegalArgumentException(
647                                         "Invalid input - policyID must contain name, scope and version");
648                             }
649                             List<PolicyEntity> policyEntityList;
650                             Query getPolicyEntitiesQuery = session.getNamedQuery("PolicyEntity.findByNameAndScope");
651                             getPolicyEntitiesQuery.setParameter("name", stringArray[0]);
652                             getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]);
653
654                             policyEntityList = getPolicyEntitiesQuery.list();
655                             PolicyEntity policyEntity = null;
656                             if (!policyEntityList.isEmpty()) {
657                                 policyEntity = policyEntityList.get(0);
658                             }
659                             if (policyEntity != null) {
660                                 groupEntity.addPolicyToGroup(policyEntity);
661                             }
662                         } catch (Exception e2) {
663                             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
664                                     "Exception auditGroups inner catch");
665                         }
666                     }
667                 } catch (Exception e1) {
668                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, POLICYDBDAO_VAR,
669                             "Exception auditGroups middle catch");
670                 }
671             }
672         } catch (Exception e) {
673             session.getTransaction().rollback();
674             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception auditGroups outer catch");
675             session.close();
676             return;
677         }
678
679         session.getTransaction().commit();
680         session.close();
681
682     }
683
684     public String getConfigFile(String filename, PolicyRestAdapter policy) {
685         if (policy == null) {
686             return getConfigFile(filename, (String) null);
687         }
688         return getConfigFile(filename, policy.getConfigType());
689     }
690
691     // copied from ConfigPolicy.java and modified
692     // Here we are adding the extension for the configurations file based on the
693     // config type selection for saving.
694     public String getConfigFile(String inputFilename, String configType) {
695         String filename = inputFilename;
696         logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile(" + filename
697                 + ", " + configType + ") called");
698         filename = FilenameUtils.removeExtension(filename);
699         String id = configType;
700
701         if (id != null) {
702             if (id.equals(ConfigPolicy.JSON_CONFIG) || id.contains("Firewall")) {
703                 filename = filename + ".json";
704             }
705             if (id.equals(ConfigPolicy.XML_CONFIG)) {
706                 filename = filename + ".xml";
707             }
708             if (id.equals(ConfigPolicy.PROPERTIES_CONFIG)) {
709                 filename = filename + ".properties";
710             }
711             if (id.equals(ConfigPolicy.OTHER_CONFIG)) {
712                 filename = filename + ".txt";
713             }
714         }
715         return filename;
716     }
717
718     public String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
719         String[] splitByDots = fileName.split("\\.");
720         if (splitByDots.length < 3) {
721             return null;
722         }
723         String policyName = splitByDots[splitByDots.length - 3];
724         String version = splitByDots[splitByDots.length - 2];
725         // policy names now include version
726         String scope = "";
727         for (int i = 0; i < splitByDots.length - 3; i++) {
728             scope += ".".concat(splitByDots[i]);
729         }
730         // remove the first dot
731         if (scope.length() > 0) {
732             scope = scope.substring(1);
733         }
734         String[] returnArray = new String[3];
735         returnArray[0] = policyName + "." + version + ".xml";
736         returnArray[2] = version;
737         returnArray[1] = scope;
738         return returnArray;
739     }
740
741     public static String createNewPDPGroupId(String name) {
742         String id = name;
743         // replace "bad" characters with sequences that will be ok for file
744         // names and properties keys.
745         id = id.replace(" ", "_sp_");
746         id = id.replace("\t", "_tab_");
747         id = id.replace("\\", "_bksl_");
748         id = id.replace("/", "_sl_");
749         id = id.replace(":", "_col_");
750         id = id.replace("*", "_ast_");
751         id = id.replace("?", "_q_");
752         id = id.replace("\"", "_quo_");
753         id = id.replace("<", "_lt_");
754         id = id.replace(">", "_gt_");
755         id = id.replace("|", "_bar_");
756         id = id.replace("=", "_eq_");
757         id = id.replace(",", "_com_");
758         id = id.replace(";", "_scom_");
759
760         return id;
761     }
762
763     /**
764      * Checks if any of the given strings are empty or null
765      *
766      * @param strings One or more Strings (or nulls) to check if they are null or empty
767      * @return true if one or more of the given strings are empty or null
768      */
769     public static boolean isNullOrEmpty(String... strings) {
770         for (String s : strings) {
771             if (s == null || "".equals(s)) {
772                 return true;
773             }
774         }
775         return false;
776     }
777
778     public List<?> getOtherServers() {
779         return otherServers;
780     }
781
782     public void setOtherServers(List<?> otherServers) {
783         this.otherServers = otherServers;
784     }
785
786     public PAPPolicyEngine getPapEngine() {
787         return papEngine;
788     }
789
790     public static boolean isJunit() {
791         return isJunit;
792     }
793
794     public static void setJunit(boolean isJunit) {
795         PolicyDBDao.isJunit = isJunit;
796     }
797
798     public static PolicyDBDaoTestClass getPolicyDBDaoTestClass() {
799         return new PolicyDBDao().new PolicyDBDaoTestClass();
800     }
801
802     final class PolicyDBDaoTestClass {
803         String getConfigFile(String filename, String scope, PolicyRestAdapter policy) {
804             return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy);
805         }
806
807         String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException {
808             return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName);
809         }
810
811         String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
812             return PolicyDBDao.this.getNameScopeAndVersionFromPdpPolicy(fileName);
813         }
814
815         String getPdpPolicyName(String name, String scope) {
816             return PolicyDBDao.this.getPdpPolicyName(name, scope);
817         }
818     }
819
820 }