2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.policy.pap.xacml.rest.components;
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;
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;
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;
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";
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;
111 * Gets the current instance of PolicyDBDao.
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.
117 public static PolicyDBDao getPolicyDBDaoInstance() {
118 logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called");
119 if (currentInstance != null) {
120 return currentInstance;
122 currentInstance = new PolicyDBDao("init");
124 return currentInstance;
127 public void setPapEngine(PAPPolicyEngine papEngine2) {
128 this.papEngine = papEngine2;
132 public PolicyDBDao(SessionFactory sessionFactory) {
133 PolicyDBDao.sessionfactory = sessionFactory;
136 public PolicyDBDao() {
137 // Default Constructor
140 public PolicyDBDao(String init) {
141 // not needed in this release
144 "This server's PolicyDBDao instance could not be registered and may not reveive updates");
147 otherServers = getRemotePolicyDBDaoList();
148 if (logger.isDebugEnabled()) {
149 logger.debug("Number of remote PolicyDBDao instances: " + otherServers.size());
151 if (otherServers.isEmpty()) {
152 logger.warn("List of PolicyDBDao servers is empty or could not be retrieved");
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();
165 if (logger.isDebugEnabled()) {
166 logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock"
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");
174 } catch (Exception e) {
175 logger.error("Exception Occured" + e);
178 throw new IllegalStateException(
179 "The lock row does not exist in the table. Please create a primary key with value = 1.");
185 * Gets the list of other registered PolicyDBDaos from the database
187 * @return List (type PolicyDBDaoEntity) of other PolicyDBDaos
189 private List<?> getRemotePolicyDBDaoList() {
190 logger.debug("getRemotePolicyDBDaoList() as getRemotePolicyDBDaoList() called");
191 List<?> policyDBDaoEntityList = new LinkedList<>();
192 Session session = sessionfactory.openSession();
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);
203 } catch (Exception e) {
204 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
205 + "Error While Closing Connection/Statement" + e);
208 return policyDBDaoEntityList;
211 public PolicyDBDaoTransaction getNewTransaction() {
212 logger.debug("getNewTransaction() as getNewTransaction() called");
213 return new PolicyDbDaoTransactionInstance("init");
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
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);
234 * Checks if two strings are equal. Null strings ARE allowed.
236 * @param one A String or null to compare
237 * @param two A String or null to compare
239 public static boolean stringEquals(String one, String two) {
240 logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two
242 if (one == null && two == null) {
245 if (one == null || two == null) {
248 return one.equals(two);
252 * Returns the url of this local pap server, removing the username and password, if they are
255 * @return The url of this local pap server
257 public String[] getPapUrlUserPass() {
258 logger.debug("getPapUrl() as getPapUrl() called");
259 String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
263 return splitPapUrlUserPass(url);
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];
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;
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;
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
294 * Register the PolicyDBDao instance in the PolicyDBDaoEntity table
296 * @return Boolean, were we able to register?
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) {
305 Session session = sessionfactory.openSession();
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);
313 lock = new DatabaseLockEntity();
316 session.persist(lock);
318 session.getTransaction().commit();
320 } catch (Exception e2) {
321 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
322 "COULD NOT CREATE DATABASELOCK ROW. WILL TRY ONE MORE TIME");
325 session = sessionfactory.openSession();
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);
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);
345 // encrypt the password
348 txt = CryptoUtils.encryptTxt(url[2].getBytes(StandardCharsets.UTF_8));
349 } catch (Exception e) {
351 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
352 "Could not encrypt PAP password");
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);
361 session.persist(newPolicyDBDaoEntity);
362 session.getTransaction().commit();
363 } catch (Exception e) {
366 session.getTransaction().rollback();
367 } catch (Exception e2) {
369 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
370 "Could not add new PolicyDBDao to the database");
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]);
378 if (txt != null && !stringEquals(txt, foundPolicyDBDaoEntity.getPassword())) {
379 foundPolicyDBDaoEntity.setPassword(txt);
381 foundPolicyDBDaoEntity.preUpdate();
383 session.getTransaction().commit();
384 } catch (Exception e) {
387 session.getTransaction().rollback();
388 } catch (Exception e2) {
390 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
391 "Could not update PolicyDBDao in the database");
396 logger.debug("\nPolicyDBDao.register(). Success!!\n");
401 * This method is called during all pushPolicy transactions and makes sure the file system group
402 * is in sync with the database groupentity
404 public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup,
405 GroupEntity groupentity) throws PAPException, PolicyDBException {
407 HashMap<String, PDPPolicy> currentPolicyMap = new HashMap<>();
408 HashSet<String> newPolicyIdSet = new HashSet<>();
409 HashSet<PDPPolicy> newPolicySet = new HashSet<>();
411 for (PDPPolicy pdpPolicy : pdpGroup.getPolicies()) {
412 currentPolicyMap.put(pdpPolicy.getId(), pdpPolicy);
415 for (PolicyEntity policy : groupentity.getPolicies()) {
416 String pdpPolicyId = getPdpPolicyName(policy.getPolicyName(), policy.getScope());
417 newPolicyIdSet.add(pdpPolicyId);
419 if (currentPolicyMap.containsKey(pdpPolicyId)) {
420 newPolicySet.add(currentPolicyMap.get(pdpPolicyId));
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);
429 Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId)
431 StdPDPPolicy newPolicy = null;
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) {
441 "PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object "
447 for (String id : currentPolicyMap.keySet()) {
448 if (!newPolicyIdSet.contains(id)) {
450 Files.delete(Paths.get(currentPolicyMap.get(id).getLocation()));
451 } catch (Exception e) {
454 "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. "
461 "PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync");
462 pdpGroup.setPolicies(newPolicySet);
467 public String removeExtensionAndVersionFromPolicyName(String originalPolicyName)
468 throws PolicyDBException {
469 return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0];
473 * Splits apart the policy name and version from a policy file path
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
478 public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName)
479 throws PolicyDBException {
480 String policyName = originalPolicyName;
481 String[] nameAndVersion = new String[2];
483 policyName = removeFileExtension(policyName);
484 nameAndVersion[0] = policyName.substring(0, policyName.lastIndexOf('.'));
485 if (isNullOrEmpty(nameAndVersion[0])) {
486 throw new PolicyDBException();
488 } catch (Exception e) {
489 nameAndVersion[0] = originalPolicyName;
493 nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.') + 1);
494 if (isNullOrEmpty(nameAndVersion[1])) {
495 throw new PolicyDBException();
497 } catch (Exception e) {
498 nameAndVersion[1] = "1";
501 return nameAndVersion;
504 public String getPdpPolicyName(String name, String scope) {
505 String finalName = "";
508 finalName += removeFileExtension(name);
513 private String removeFileExtension(String fileName) {
514 return fileName.substring(0, fileName.lastIndexOf('.'));
517 public void auditLocalDatabase(PAPPolicyEngine papEngine2) {
518 logger.debug("PolicyDBDao.auditLocalDatabase() is called");
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);
529 public StdPDPGroup auditLocalFileSystem(StdPDPGroup group) {
531 logger.info("Starting Local File System group audit");
532 Session session = sessionfactory.openSession();
533 session.getTransaction().begin();
535 StdPDPGroup updatedGroup = null;
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);
545 "Group was updated during file system audit: " + updatedGroup.toString());
547 } catch (PAPException | PolicyDBException e) {
549 } catch (Exception 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");
557 session.getTransaction().commit();
564 * This method is called at startup to recreate config data from DB to the file system.
567 public void synchronizeConfigDataInFileSystem() {
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);
575 private <T> void syncConfigData(Class<T> cl, String type) {
576 Session session = sessionfactory.openSession();
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);
584 for (final T configData : configDataResult) {
585 String configName = null;
588 if (CONFIG.equalsIgnoreCase(type)) {
589 configName = ((ConfigurationDataEntity) configData).getConfigurationName();
591 (((ConfigurationDataEntity) configData).getConfigBody() != null)
592 ? ((ConfigurationDataEntity) configData).getConfigBody()
593 .getBytes(StandardCharsets.UTF_8)
596 configName = ((ActionBodyEntity) configData).getActionBodyName();
597 configBody = (((ActionBodyEntity) configData).getActionBody() != null)
598 ? ((ActionBodyEntity) configData).getActionBody()
599 .getBytes(StandardCharsets.UTF_8)
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());
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);
613 } catch (final Exception exception) {
614 logger.error("Unable to synchronizeConfigDataInFileSystem", exception);
619 public void deleteAllGroupTables() {
620 logger.debug("PolicyDBDao.deleteAllGroupTables() called");
621 Session session = sessionfactory.openSession();
622 session.getTransaction().begin();
624 Query deletePdpEntityEntityTableUpdate = session.getNamedQuery("PdpEntity.deleteAll");
625 deletePdpEntityEntityTableUpdate.executeUpdate();
627 Query deleteGroupEntityTableUpdate = session.getNamedQuery("GroupEntity.deleteAll");
628 deleteGroupEntityTableUpdate.executeUpdate();
630 session.getTransaction().commit();
634 @SuppressWarnings("unchecked")
635 public void auditGroups(PAPPolicyEngine papEngine2) {
636 logger.debug("PolicyDBDao.auditGroups() called");
638 Session session = sessionfactory.openSession();
639 session.getTransaction().begin();
640 final String AUDIT_STR = "Audit";
643 Set<OnapPDPGroup> groups = papEngine2.getOnapPDPGroups();
645 for (OnapPDPGroup grp : groups) {
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();
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);
668 Set<PDPPolicy> policies = grp.getPolicies();
670 for (PDPPolicy policy : policies) {
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");
678 List<PolicyEntity> policyEntityList;
679 Query getPolicyEntitiesQuery =
680 session.getNamedQuery("PolicyEntity.findByNameAndScope");
681 getPolicyEntitiesQuery.setParameter("name", stringArray[0]);
682 getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]);
684 policyEntityList = getPolicyEntitiesQuery.list();
685 PolicyEntity policyEntity = null;
686 if (!policyEntityList.isEmpty()) {
687 policyEntity = policyEntityList.get(0);
689 if (policyEntity != null) {
690 groupEntity.addPolicyToGroup(policyEntity);
692 } catch (Exception e2) {
693 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
694 "Exception auditGroups inner catch");
697 } catch (Exception e1) {
698 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, POLICYDBDAO_VAR,
699 "Exception auditGroups middle catch");
702 } catch (Exception e) {
703 session.getTransaction().rollback();
704 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
705 "Exception auditGroups outer catch");
710 session.getTransaction().commit();
715 public String getConfigFile(String filename, PolicyRestAdapter policy) {
716 if (policy == null) {
717 return getConfigFile(filename, (String) null);
719 return getConfigFile(filename, policy.getConfigType());
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;
728 "getConfigFile(String filename, String scope, String configType) as getConfigFile("
729 + filename + ", " + configType + ") called");
730 filename = FilenameUtils.removeExtension(filename);
731 String id = configType;
734 if (id.equals(ConfigPolicy.JSON_CONFIG) || id.contains("Firewall")) {
735 filename = filename + ".json";
737 if (id.equals(ConfigPolicy.XML_CONFIG)) {
738 filename = filename + ".xml";
740 if (id.equals(ConfigPolicy.PROPERTIES_CONFIG)) {
741 filename = filename + ".properties";
743 if (id.equals(ConfigPolicy.OTHER_CONFIG)) {
744 filename = filename + ".txt";
750 public String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
751 String[] splitByDots = fileName.split("\\.");
752 if (splitByDots.length < 3) {
755 String policyName = splitByDots[splitByDots.length - 3];
756 String version = splitByDots[splitByDots.length - 2];
757 // policy names now include version
759 for (int i = 0; i < splitByDots.length - 3; i++) {
760 scope += ".".concat(splitByDots[i]);
762 // remove the first dot
763 if (scope.length() > 0) {
764 scope = scope.substring(1);
766 String[] returnArray = new String[3];
767 returnArray[0] = policyName + "." + version + ".xml";
768 returnArray[2] = version;
769 returnArray[1] = scope;
773 public static String createNewPDPGroupId(String 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_");
796 * Checks if any of the given strings are empty or null
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
801 public static boolean isNullOrEmpty(String... strings) {
802 for (String s : strings) {
803 if (s == null || "".equals(s)) {
810 public List<?> getOtherServers() {
814 public void setOtherServers(List<?> otherServers) {
815 this.otherServers = otherServers;
818 public PAPPolicyEngine getPapEngine() {
823 public static boolean isJunit() {
827 public static void setJunit(boolean isJunit) {
828 PolicyDBDao.isJunit = isJunit;
831 public static PolicyDBDaoTestClass getPolicyDBDaoTestClass() {
832 return new PolicyDBDao().new PolicyDBDaoTestClass();
835 final class PolicyDBDaoTestClass {
836 String getConfigFile(String filename, String scope, PolicyRestAdapter policy) {
837 return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy);
840 String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName)
841 throws PolicyDBException {
842 return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName);
845 String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
846 return PolicyDBDao.this.getNameScopeAndVersionFromPdpPolicy(fileName);
849 String getPdpPolicyName(String name, String scope) {
850 return PolicyDBDao.this.getPdpPolicyName(name, scope);