Fix sonar new bugs and vulnerabilities
[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.CryptoUtils;
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                     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 = null;
347         try {
348             txt = CryptoUtils.encryptTxt(url[2].getBytes(StandardCharsets.UTF_8));
349         } catch (Exception e) {
350             logger.debug(e);
351             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
352                     "Could not encrypt PAP password");
353         }
354         if (foundPolicyDBDaoEntity == null) {
355             PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity();
356             newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]);
357             newPolicyDBDaoEntity.setDescription("PAP server at " + url[0]);
358             newPolicyDBDaoEntity.setUsername(url[1]);
359             newPolicyDBDaoEntity.setPassword(txt);
360             try {
361                 session.persist(newPolicyDBDaoEntity);
362                 session.getTransaction().commit();
363             } catch (Exception e) {
364                 logger.debug(e);
365                 try {
366                     session.getTransaction().rollback();
367                 } catch (Exception e2) {
368                     logger.debug(e2);
369                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
370                             "Could not add new PolicyDBDao to the database");
371                 }
372             }
373         } else {
374             // just want to update in order to change modified date
375             if (url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())) {
376                 foundPolicyDBDaoEntity.setUsername(url[1]);
377             }
378             if (txt != null && !stringEquals(txt, foundPolicyDBDaoEntity.getPassword())) {
379                 foundPolicyDBDaoEntity.setPassword(txt);
380             }
381             foundPolicyDBDaoEntity.preUpdate();
382             try {
383                 session.getTransaction().commit();
384             } catch (Exception e) {
385                 logger.debug(e);
386                 try {
387                     session.getTransaction().rollback();
388                 } catch (Exception e2) {
389                     logger.debug(e2);
390                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
391                             "Could not update PolicyDBDao in the database");
392                 }
393             }
394         }
395         session.close();
396         logger.debug("\nPolicyDBDao.register(). Success!!\n");
397         return true;
398     }
399
400     /*
401      * This method is called during all pushPolicy transactions and makes sure the file system group
402      * is in sync with the database groupentity
403      */
404     public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup,
405             GroupEntity groupentity) throws PAPException, PolicyDBException {
406
407         HashMap<String, PDPPolicy> currentPolicyMap = new HashMap<>();
408         HashSet<String> newPolicyIdSet = new HashSet<>();
409         HashSet<PDPPolicy> newPolicySet = new HashSet<>();
410
411         for (PDPPolicy pdpPolicy : pdpGroup.getPolicies()) {
412             currentPolicyMap.put(pdpPolicy.getId(), pdpPolicy);
413         }
414
415         for (PolicyEntity policy : groupentity.getPolicies()) {
416             String pdpPolicyId = getPdpPolicyName(policy.getPolicyName(), policy.getScope());
417             newPolicyIdSet.add(pdpPolicyId);
418
419             if (currentPolicyMap.containsKey(pdpPolicyId)) {
420                 newPolicySet.add(currentPolicyMap.get(pdpPolicyId));
421             } else {
422                 // convert PolicyEntity object to PDPPolicy
423                 String name = pdpPolicyId.replace(".xml", "");
424                 name = name.substring(0, name.lastIndexOf('.'));
425                 InputStream policyStream =
426                         new ByteArrayInputStream(policy.getPolicyData().getBytes());
427                 pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream);
428                 URI location =
429                         Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId)
430                                 .toUri();
431                 StdPDPPolicy newPolicy = null;
432                 try {
433                     newPolicy = new StdPDPPolicy(pdpPolicyId, true,
434                             removeExtensionAndVersionFromPolicyName(pdpPolicyId), location);
435                     newPolicySet.add(newPolicy);
436                     logger.info("Adding new policy to PDPGroup - " + newPolicy.getId()
437                             + ", Location - " + location);
438                 } catch (Exception e) {
439                     logger.debug(e);
440                     PolicyLogger.error(
441                             "PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object "
442                                     + e.getMessage());
443                 }
444             }
445         }
446
447         for (String id : currentPolicyMap.keySet()) {
448             if (!newPolicyIdSet.contains(id)) {
449                 try {
450                     Files.delete(Paths.get(currentPolicyMap.get(id).getLocation()));
451                 } catch (Exception e) {
452                     logger.debug(e);
453                     PolicyLogger.error(
454                             "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. "
455                                     + e.getMessage());
456                 }
457             }
458         }
459
460         logger.info(
461                 "PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync");
462         pdpGroup.setPolicies(newPolicySet);
463
464         return pdpGroup;
465     }
466
467     public String removeExtensionAndVersionFromPolicyName(String originalPolicyName)
468             throws PolicyDBException {
469         return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0];
470     }
471
472     /**
473      * Splits apart the policy name and version from a policy file path
474      *
475      * @param originalPolicyName: a policy file name ex: Config_policy.2.xml
476      * @return An array [0]: The policy name, [1]: the policy version, as a string
477      */
478     public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName)
479             throws PolicyDBException {
480         String policyName = originalPolicyName;
481         String[] nameAndVersion = new String[2];
482         try {
483             policyName = removeFileExtension(policyName);
484             nameAndVersion[0] = policyName.substring(0, policyName.lastIndexOf('.'));
485             if (isNullOrEmpty(nameAndVersion[0])) {
486                 throw new PolicyDBException();
487             }
488         } catch (Exception e) {
489             nameAndVersion[0] = originalPolicyName;
490             logger.debug(e);
491         }
492         try {
493             nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.') + 1);
494             if (isNullOrEmpty(nameAndVersion[1])) {
495                 throw new PolicyDBException();
496             }
497         } catch (Exception e) {
498             nameAndVersion[1] = "1";
499             logger.debug(e);
500         }
501         return nameAndVersion;
502     }
503
504     public String getPdpPolicyName(String name, String scope) {
505         String finalName = "";
506         finalName += scope;
507         finalName += ".";
508         finalName += removeFileExtension(name);
509         finalName += ".xml";
510         return finalName;
511     }
512
513     private String removeFileExtension(String fileName) {
514         return fileName.substring(0, fileName.lastIndexOf('.'));
515     }
516
517     public void auditLocalDatabase(PAPPolicyEngine papEngine2) {
518         logger.debug("PolicyDBDao.auditLocalDatabase() is called");
519         try {
520             deleteAllGroupTables();
521             auditGroups(papEngine2);
522         } catch (Exception e) {
523             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
524                     "auditLocalDatabase() error");
525             logger.error("Exception Occured" + e);
526         }
527     }
528
529     public StdPDPGroup auditLocalFileSystem(StdPDPGroup group) {
530
531         logger.info("Starting Local File System group audit");
532         Session session = sessionfactory.openSession();
533         session.getTransaction().begin();
534
535         StdPDPGroup updatedGroup = null;
536         try {
537             Query groupQuery = session.createQuery(GROUPENTITY_SELECT);
538             groupQuery.setParameter(GROUP_ID, group.getId());
539             groupQuery.setParameter(DELETED, false);
540             List<?> groupQueryList = groupQuery.list();
541             if (groupQueryList != null && !groupQueryList.isEmpty()) {
542                 GroupEntity dbgroup = (GroupEntity) groupQueryList.get(0);
543                 updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup);
544                 logger.info(
545                         "Group was updated during file system audit: " + updatedGroup.toString());
546             }
547         } catch (PAPException | PolicyDBException e) {
548             logger.error(e);
549         } catch (Exception e) {
550             logger.error(e);
551             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
552                     "Caught Exception trying to check if group exists groupQuery.getResultList()");
553             throw new PersistenceException(
554                     "Query failed trying to check if group " + group.getId() + " exists");
555         }
556
557         session.getTransaction().commit();
558         session.close();
559
560         return updatedGroup;
561     }
562
563     /*
564      * This method is called at startup to recreate config data from DB to the file system.
565      *
566      */
567     public void synchronizeConfigDataInFileSystem() {
568
569         logger.info("Starting Local File System Config data Sync");
570         // sync both web apps Config and Action
571         syncConfigData(ConfigurationDataEntity.class, CONFIG);
572         syncConfigData(ActionBodyEntity.class, ACTION);
573     }
574
575     private <T> void syncConfigData(Class<T> cl, String type) {
576         Session session = sessionfactory.openSession();
577         try {
578             final Criteria configDataQuery = session.createCriteria(cl.getName());
579             @SuppressWarnings("unchecked")
580             final List<T> configDataResult = configDataQuery.list();
581             Path webappsPath = Paths
582                     .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), type);
583
584             for (final T configData : configDataResult) {
585                 String configName = null;
586                 byte[] configBody;
587                 try {
588                     if (CONFIG.equalsIgnoreCase(type)) {
589                         configName = ((ConfigurationDataEntity) configData).getConfigurationName();
590                         configBody =
591                                 (((ConfigurationDataEntity) configData).getConfigBody() != null)
592                                         ? ((ConfigurationDataEntity) configData).getConfigBody()
593                                                 .getBytes(StandardCharsets.UTF_8)
594                                         : "".getBytes();
595                     } else {
596                         configName = ((ActionBodyEntity) configData).getActionBodyName();
597                         configBody = (((ActionBodyEntity) configData).getActionBody() != null)
598                                 ? ((ActionBodyEntity) configData).getActionBody()
599                                         .getBytes(StandardCharsets.UTF_8)
600                                 : "".getBytes();
601                     }
602                     Path filePath = Paths.get(webappsPath.toString(), configName);
603                     if (!filePath.toFile().exists()) {
604                         Files.write(filePath, configBody);
605                         logger.info("Created Config File from DB - " + filePath.toString());
606                     }
607                 } catch (Exception e) {
608                     // log and keep going
609                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
610                             "Exception occured while creating Configuration File - " + configName);
611                 }
612             }
613         } catch (final Exception exception) {
614             logger.error("Unable to synchronizeConfigDataInFileSystem", exception);
615         }
616         session.close();
617     }
618
619     public void deleteAllGroupTables() {
620         logger.debug("PolicyDBDao.deleteAllGroupTables() called");
621         Session session = sessionfactory.openSession();
622         session.getTransaction().begin();
623
624         Query deletePdpEntityEntityTableUpdate = session.getNamedQuery("PdpEntity.deleteAll");
625         deletePdpEntityEntityTableUpdate.executeUpdate();
626
627         Query deleteGroupEntityTableUpdate = session.getNamedQuery("GroupEntity.deleteAll");
628         deleteGroupEntityTableUpdate.executeUpdate();
629
630         session.getTransaction().commit();
631         session.close();
632     }
633
634     @SuppressWarnings("unchecked")
635     public void auditGroups(PAPPolicyEngine papEngine2) {
636         logger.debug("PolicyDBDao.auditGroups() called");
637
638         Session session = sessionfactory.openSession();
639         session.getTransaction().begin();
640         final String AUDIT_STR = "Audit";
641         try {
642
643             Set<OnapPDPGroup> groups = papEngine2.getOnapPDPGroups();
644
645             for (OnapPDPGroup grp : groups) {
646                 try {
647                     GroupEntity groupEntity = new GroupEntity();
648                     groupEntity.setGroupName(grp.getName());
649                     groupEntity.setDescription(grp.getDescription());
650                     groupEntity.setDefaultGroup(grp.isDefaultGroup());
651                     groupEntity.setCreatedBy(AUDIT_STR);
652                     groupEntity.setGroupId(createNewPDPGroupId(grp.getId()));
653                     groupEntity.setModifiedBy(AUDIT_STR);
654                     session.persist(groupEntity);
655                     Set<OnapPDP> pdps = grp.getOnapPdps();
656
657                     for (OnapPDP pdp : pdps) {
658                         PdpEntity pdpEntity = new PdpEntity();
659                         pdpEntity.setGroup(groupEntity);
660                         pdpEntity.setJmxPort(pdp.getJmxPort());
661                         pdpEntity.setPdpId(pdp.getId());
662                         pdpEntity.setPdpName(pdp.getName());
663                         pdpEntity.setModifiedBy(AUDIT_STR);
664                         pdpEntity.setCreatedBy(AUDIT_STR);
665                         session.persist(pdpEntity);
666                     }
667
668                     Set<PDPPolicy> policies = grp.getPolicies();
669
670                     for (PDPPolicy policy : policies) {
671                         try {
672                             String[] stringArray =
673                                     getNameScopeAndVersionFromPdpPolicy(policy.getId());
674                             if (stringArray == null) {
675                                 throw new IllegalArgumentException(
676                                         "Invalid input - policyID must contain name, scope and version");
677                             }
678                             List<PolicyEntity> policyEntityList;
679                             Query getPolicyEntitiesQuery =
680                                     session.getNamedQuery("PolicyEntity.findByNameAndScope");
681                             getPolicyEntitiesQuery.setParameter("name", stringArray[0]);
682                             getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]);
683
684                             policyEntityList = getPolicyEntitiesQuery.list();
685                             PolicyEntity policyEntity = null;
686                             if (!policyEntityList.isEmpty()) {
687                                 policyEntity = policyEntityList.get(0);
688                             }
689                             if (policyEntity != null) {
690                                 groupEntity.addPolicyToGroup(policyEntity);
691                             }
692                         } catch (Exception e2) {
693                             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
694                                     "Exception auditGroups inner catch");
695                         }
696                     }
697                 } catch (Exception e1) {
698                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, POLICYDBDAO_VAR,
699                             "Exception auditGroups middle catch");
700                 }
701             }
702         } catch (Exception e) {
703             session.getTransaction().rollback();
704             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
705                     "Exception auditGroups outer catch");
706             session.close();
707             return;
708         }
709
710         session.getTransaction().commit();
711         session.close();
712
713     }
714
715     public String getConfigFile(String filename, PolicyRestAdapter policy) {
716         if (policy == null) {
717             return getConfigFile(filename, (String) null);
718         }
719         return getConfigFile(filename, policy.getConfigType());
720     }
721
722     // copied from ConfigPolicy.java and modified
723     // Here we are adding the extension for the configurations file based on the
724     // config type selection for saving.
725     public String getConfigFile(String inputFilename, String configType) {
726         String filename = inputFilename;
727         logger.debug(
728                 "getConfigFile(String filename, String scope, String configType) as getConfigFile("
729                         + filename + ", " + configType + ") called");
730         filename = FilenameUtils.removeExtension(filename);
731         String id = configType;
732
733         if (id != null) {
734             if (id.equals(ConfigPolicy.JSON_CONFIG) || id.contains("Firewall")) {
735                 filename = filename + ".json";
736             }
737             if (id.equals(ConfigPolicy.XML_CONFIG)) {
738                 filename = filename + ".xml";
739             }
740             if (id.equals(ConfigPolicy.PROPERTIES_CONFIG)) {
741                 filename = filename + ".properties";
742             }
743             if (id.equals(ConfigPolicy.OTHER_CONFIG)) {
744                 filename = filename + ".txt";
745             }
746         }
747         return filename;
748     }
749
750     public String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
751         String[] splitByDots = fileName.split("\\.");
752         if (splitByDots.length < 3) {
753             return null;
754         }
755         String policyName = splitByDots[splitByDots.length - 3];
756         String version = splitByDots[splitByDots.length - 2];
757         // policy names now include version
758         String scope = "";
759         for (int i = 0; i < splitByDots.length - 3; i++) {
760             scope += ".".concat(splitByDots[i]);
761         }
762         // remove the first dot
763         if (scope.length() > 0) {
764             scope = scope.substring(1);
765         }
766         String[] returnArray = new String[3];
767         returnArray[0] = policyName + "." + version + ".xml";
768         returnArray[2] = version;
769         returnArray[1] = scope;
770         return returnArray;
771     }
772
773     public static String createNewPDPGroupId(String name) {
774         String id = name;
775         // replace "bad" characters with sequences that will be ok for file
776         // names and properties keys.
777         id = id.replace(" ", "_sp_");
778         id = id.replace("\t", "_tab_");
779         id = id.replace("\\", "_bksl_");
780         id = id.replace("/", "_sl_");
781         id = id.replace(":", "_col_");
782         id = id.replace("*", "_ast_");
783         id = id.replace("?", "_q_");
784         id = id.replace("\"", "_quo_");
785         id = id.replace("<", "_lt_");
786         id = id.replace(">", "_gt_");
787         id = id.replace("|", "_bar_");
788         id = id.replace("=", "_eq_");
789         id = id.replace(",", "_com_");
790         id = id.replace(";", "_scom_");
791
792         return id;
793     }
794
795     /**
796      * Checks if any of the given strings are empty or null
797      *
798      * @param strings One or more Strings (or nulls) to check if they are null or empty
799      * @return true if one or more of the given strings are empty or null
800      */
801     public static boolean isNullOrEmpty(String... strings) {
802         for (String s : strings) {
803             if (s == null || "".equals(s)) {
804                 return true;
805             }
806         }
807         return false;
808     }
809
810     public List<?> getOtherServers() {
811         return otherServers;
812     }
813
814     public void setOtherServers(List<?> otherServers) {
815         this.otherServers = otherServers;
816     }
817
818     public PAPPolicyEngine getPapEngine() {
819         return papEngine;
820     }
821
822
823     public static boolean isJunit() {
824         return isJunit;
825     }
826
827     public static void setJunit(boolean isJunit) {
828         PolicyDBDao.isJunit = isJunit;
829     }
830
831     public static PolicyDBDaoTestClass getPolicyDBDaoTestClass() {
832         return new PolicyDBDao().new PolicyDBDaoTestClass();
833     }
834
835     final class PolicyDBDaoTestClass {
836         String getConfigFile(String filename, String scope, PolicyRestAdapter policy) {
837             return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy);
838         }
839
840         String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName)
841                 throws PolicyDBException {
842             return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName);
843         }
844
845         String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
846             return PolicyDBDao.this.getNameScopeAndVersionFromPdpPolicy(fileName);
847         }
848
849         String getPdpPolicyName(String name, String scope) {
850             return PolicyDBDao.this.getPdpPolicyName(name, scope);
851         }
852     }
853
854 }