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.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;
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 PeCryptoUtils.decrypt(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
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);
354 session.persist(newPolicyDBDaoEntity);
355 session.getTransaction().commit();
356 } catch (Exception e) {
359 session.getTransaction().rollback();
360 } catch (Exception e2) {
362 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
363 "Could not add new PolicyDBDao to the database");
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]);
371 if (txt != null && !stringEquals(txt, foundPolicyDBDaoEntity.getPassword())) {
372 foundPolicyDBDaoEntity.setPassword(txt);
374 foundPolicyDBDaoEntity.preUpdate();
376 session.getTransaction().commit();
377 } catch (Exception e) {
380 session.getTransaction().rollback();
381 } catch (Exception e2) {
383 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
384 "Could not update PolicyDBDao in the database");
389 logger.debug("\nPolicyDBDao.register(). Success!!\n");
394 * This method is called during all pushPolicy transactions and makes sure the file system group
395 * is in sync with the database groupentity
397 public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup,
398 GroupEntity groupentity) throws PAPException, PolicyDBException {
400 HashMap<String, PDPPolicy> currentPolicyMap = new HashMap<>();
401 HashSet<String> newPolicyIdSet = new HashSet<>();
402 HashSet<PDPPolicy> newPolicySet = new HashSet<>();
404 for (PDPPolicy pdpPolicy : pdpGroup.getPolicies()) {
405 currentPolicyMap.put(pdpPolicy.getId(), pdpPolicy);
408 for (PolicyEntity policy : groupentity.getPolicies()) {
409 String pdpPolicyId = getPdpPolicyName(policy.getPolicyName(), policy.getScope());
410 newPolicyIdSet.add(pdpPolicyId);
412 if (currentPolicyMap.containsKey(pdpPolicyId)) {
413 newPolicySet.add(currentPolicyMap.get(pdpPolicyId));
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);
422 Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId)
424 StdPDPPolicy newPolicy = null;
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) {
434 "PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object "
440 for (String id : currentPolicyMap.keySet()) {
441 if (!newPolicyIdSet.contains(id)) {
443 Files.delete(Paths.get(currentPolicyMap.get(id).getLocation()));
444 } catch (Exception e) {
447 "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. "
454 "PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync");
455 pdpGroup.setPolicies(newPolicySet);
460 public String removeExtensionAndVersionFromPolicyName(String originalPolicyName)
461 throws PolicyDBException {
462 return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0];
466 * Splits apart the policy name and version from a policy file path
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
471 public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName)
472 throws PolicyDBException {
473 String policyName = originalPolicyName;
474 String[] nameAndVersion = new String[2];
476 policyName = removeFileExtension(policyName);
477 nameAndVersion[0] = policyName.substring(0, policyName.lastIndexOf('.'));
478 if (isNullOrEmpty(nameAndVersion[0])) {
479 throw new PolicyDBException();
481 } catch (Exception e) {
482 nameAndVersion[0] = originalPolicyName;
486 nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.') + 1);
487 if (isNullOrEmpty(nameAndVersion[1])) {
488 throw new PolicyDBException();
490 } catch (Exception e) {
491 nameAndVersion[1] = "1";
494 return nameAndVersion;
497 public String getPdpPolicyName(String name, String scope) {
498 String finalName = "";
501 finalName += removeFileExtension(name);
506 private String removeFileExtension(String fileName) {
507 return fileName.substring(0, fileName.lastIndexOf('.'));
510 public void auditLocalDatabase(PAPPolicyEngine papEngine2) {
511 logger.debug("PolicyDBDao.auditLocalDatabase() is called");
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);
522 public StdPDPGroup auditLocalFileSystem(StdPDPGroup group) {
524 logger.info("Starting Local File System group audit");
525 Session session = sessionfactory.openSession();
526 session.getTransaction().begin();
528 StdPDPGroup updatedGroup = null;
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);
538 "Group was updated during file system audit: " + updatedGroup.toString());
540 } catch (PAPException | PolicyDBException e) {
542 } catch (Exception 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");
550 session.getTransaction().commit();
557 * This method is called at startup to recreate config data from DB to the file system.
560 public void synchronizeConfigDataInFileSystem() {
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);
568 private <T> void syncConfigData(Class<T> cl, String type) {
569 Session session = sessionfactory.openSession();
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);
577 for (final T configData : configDataResult) {
578 String configName = null;
581 if (CONFIG.equalsIgnoreCase(type)) {
582 configName = ((ConfigurationDataEntity) configData).getConfigurationName();
584 (((ConfigurationDataEntity) configData).getConfigBody() != null)
585 ? ((ConfigurationDataEntity) configData).getConfigBody()
586 .getBytes(StandardCharsets.UTF_8)
589 configName = ((ActionBodyEntity) configData).getActionBodyName();
590 configBody = (((ActionBodyEntity) configData).getActionBody() != null)
591 ? ((ActionBodyEntity) configData).getActionBody()
592 .getBytes(StandardCharsets.UTF_8)
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());
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);
606 } catch (final Exception exception) {
607 logger.error("Unable to synchronizeConfigDataInFileSystem", exception);
612 public void deleteAllGroupTables() {
613 logger.debug("PolicyDBDao.deleteAllGroupTables() called");
614 Session session = sessionfactory.openSession();
615 session.getTransaction().begin();
617 Query deletePdpEntityEntityTableUpdate = session.getNamedQuery("PdpEntity.deleteAll");
618 deletePdpEntityEntityTableUpdate.executeUpdate();
620 Query deleteGroupEntityTableUpdate = session.getNamedQuery("GroupEntity.deleteAll");
621 deleteGroupEntityTableUpdate.executeUpdate();
623 session.getTransaction().commit();
627 @SuppressWarnings("unchecked")
628 public void auditGroups(PAPPolicyEngine papEngine2) {
629 logger.debug("PolicyDBDao.auditGroups() called");
631 Session session = sessionfactory.openSession();
632 session.getTransaction().begin();
633 final String AUDIT_STR = "Audit";
636 Set<OnapPDPGroup> groups = papEngine2.getOnapPDPGroups();
638 for (OnapPDPGroup grp : groups) {
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();
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);
661 Set<PDPPolicy> policies = grp.getPolicies();
663 for (PDPPolicy policy : policies) {
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");
671 List<PolicyEntity> policyEntityList;
672 Query getPolicyEntitiesQuery =
673 session.getNamedQuery("PolicyEntity.findByNameAndScope");
674 getPolicyEntitiesQuery.setParameter("name", stringArray[0]);
675 getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]);
677 policyEntityList = getPolicyEntitiesQuery.list();
678 PolicyEntity policyEntity = null;
679 if (!policyEntityList.isEmpty()) {
680 policyEntity = policyEntityList.get(0);
682 if (policyEntity != null) {
683 groupEntity.addPolicyToGroup(policyEntity);
685 } catch (Exception e2) {
686 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
687 "Exception auditGroups inner catch");
690 } catch (Exception e1) {
691 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, POLICYDBDAO_VAR,
692 "Exception auditGroups middle catch");
695 } catch (Exception e) {
696 session.getTransaction().rollback();
697 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
698 "Exception auditGroups outer catch");
703 session.getTransaction().commit();
708 public String getConfigFile(String filename, PolicyRestAdapter policy) {
709 if (policy == null) {
710 return getConfigFile(filename, (String) null);
712 return getConfigFile(filename, policy.getConfigType());
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;
721 "getConfigFile(String filename, String scope, String configType) as getConfigFile("
722 + filename + ", " + configType + ") called");
723 filename = FilenameUtils.removeExtension(filename);
724 String id = configType;
727 if (id.equals(ConfigPolicy.JSON_CONFIG) || id.contains("Firewall")) {
728 filename = filename + ".json";
730 if (id.equals(ConfigPolicy.XML_CONFIG)) {
731 filename = filename + ".xml";
733 if (id.equals(ConfigPolicy.PROPERTIES_CONFIG)) {
734 filename = filename + ".properties";
736 if (id.equals(ConfigPolicy.OTHER_CONFIG)) {
737 filename = filename + ".txt";
743 public String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
744 String[] splitByDots = fileName.split("\\.");
745 if (splitByDots.length < 3) {
748 String policyName = splitByDots[splitByDots.length - 3];
749 String version = splitByDots[splitByDots.length - 2];
750 // policy names now include version
752 for (int i = 0; i < splitByDots.length - 3; i++) {
753 scope += ".".concat(splitByDots[i]);
755 // remove the first dot
756 if (scope.length() > 0) {
757 scope = scope.substring(1);
759 String[] returnArray = new String[3];
760 returnArray[0] = policyName + "." + version + ".xml";
761 returnArray[2] = version;
762 returnArray[1] = scope;
766 public static String createNewPDPGroupId(String 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_");
789 * Checks if any of the given strings are empty or null
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
794 public static boolean isNullOrEmpty(String... strings) {
795 for (String s : strings) {
796 if (s == null || "".equals(s)) {
803 public List<?> getOtherServers() {
807 public void setOtherServers(List<?> otherServers) {
808 this.otherServers = otherServers;
811 public PAPPolicyEngine getPapEngine() {
816 public static boolean isJunit() {
820 public static void setJunit(boolean isJunit) {
821 PolicyDBDao.isJunit = isJunit;
824 public static PolicyDBDaoTestClass getPolicyDBDaoTestClass() {
825 return new PolicyDBDao().new PolicyDBDaoTestClass();
828 final class PolicyDBDaoTestClass {
829 String getConfigFile(String filename, String scope, PolicyRestAdapter policy) {
830 return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy);
833 String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName)
834 throws PolicyDBException {
835 return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName);
838 String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
839 return PolicyDBDao.this.getNameScopeAndVersionFromPdpPolicy(fileName);
842 String getPdpPolicyName(String name, String scope) {
843 return PolicyDBDao.this.getPdpPolicyName(name, scope);