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