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;
28 import java.io.ByteArrayInputStream;
29 import java.io.InputStream;
31 import java.nio.charset.StandardCharsets;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.LinkedList;
38 import java.util.List;
41 import javax.persistence.PersistenceException;
43 import org.apache.commons.io.FilenameUtils;
44 import org.hibernate.Criteria;
45 import org.hibernate.LockMode;
46 import org.hibernate.Query;
47 import org.hibernate.Session;
48 import org.hibernate.SessionFactory;
49 import org.hibernate.criterion.Restrictions;
50 import org.onap.policy.common.logging.eelf.MessageCodes;
51 import org.onap.policy.common.logging.eelf.PolicyLogger;
52 import org.onap.policy.common.logging.flexlogger.FlexLogger;
53 import org.onap.policy.common.logging.flexlogger.Logger;
54 import org.onap.policy.rest.XacmlRestProperties;
55 import org.onap.policy.rest.adapter.PolicyRestAdapter;
56 import org.onap.policy.rest.dao.PolicyDBException;
57 import org.onap.policy.rest.jpa.ActionBodyEntity;
58 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
59 import org.onap.policy.rest.jpa.DatabaseLockEntity;
60 import org.onap.policy.rest.jpa.GroupEntity;
61 import org.onap.policy.rest.jpa.PdpEntity;
62 import org.onap.policy.rest.jpa.PolicyDBDaoEntity;
63 import org.onap.policy.rest.jpa.PolicyEntity;
64 import org.onap.policy.utils.PeCryptoUtils;
65 import org.onap.policy.xacml.api.XACMLErrorConstants;
66 import org.onap.policy.xacml.api.pap.OnapPDP;
67 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
68 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
69 import org.onap.policy.xacml.std.pap.StdPDPGroup;
70 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
71 import org.springframework.beans.factory.annotation.Autowired;
72 import org.springframework.stereotype.Component;
75 public class PolicyDBDao {
76 private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class);
77 public static final String JSON_CONFIG = "JSON";
78 public static final String XML_CONFIG = "XML";
79 public static final String PROPERTIES_CONFIG = "PROPERTIES";
80 public static final String OTHER_CONFIG = "OTHER";
81 public static final String AUDIT_USER = "audit";
83 public static final String CONFIG = "Config";
84 public static final String ACTION = "Action";
85 public static final String GROUP_ID = "groupId";
86 public static final String DELETED = "deleted";
87 public static final String GROUPENTITY_SELECT =
88 "SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted";
89 public static final String PDPENTITY_SELECT =
90 "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted";
91 public static final String GROUP_NOT_FOUND = "The group could not be found with id ";
92 public static final String FOUND_IN_DB_NOT_DEL = " were found in the database that are not deleted";
93 public static final String MORE_THAN_ONE_PDP = "Somehow, more than one pdp with the same id ";
94 public static final String DELETED_STATUS_FOUND = " and deleted status were found in the database";
95 public static final String DUPLICATE_GROUPID = "Somehow, more than one group with the same id ";
96 public static final String PDP_ID = "pdpId";
97 public static final String QUERY_FAILED_FOR_GROUP = "Query failed trying to check for existing group";
98 public static final String QUERY_FAILED_GET_GROUP = "Query failed trying to get group ";
99 public static final String SCOPE = "scope";
100 public static final String POLICYDBDAO_VAR = "PolicyDBDao";
101 public static final String DUP_POLICYID = "Somehow, more than one policy with the id ";
102 public static final String FOUND_IN_DB = " were found in the database";
103 private static PolicyDBDao currentInstance = null;
104 private static boolean isJunit = false;
105 private static SessionFactory sessionfactory;
106 private List<?> otherServers;
107 private PAPPolicyEngine papEngine;
110 * Gets the current instance of PolicyDBDao.
112 * @return The instance of PolicyDBDao or throws exception if the given instance is null.
113 * @throws IllegalStateException if a PolicyDBDao instance is null. Call
114 * createPolicyDBDaoInstance (EntityManagerFactory emf) to get this.
116 public static PolicyDBDao getPolicyDBDaoInstance() {
117 logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called");
118 if (currentInstance != null) {
119 return currentInstance;
121 currentInstance = new PolicyDBDao("init");
123 return currentInstance;
126 public void setPapEngine(PAPPolicyEngine papEngine2) {
127 this.papEngine = papEngine2;
131 public PolicyDBDao(SessionFactory sessionFactory) {
132 PolicyDBDao.sessionfactory = sessionFactory;
135 public PolicyDBDao() {
136 // Default Constructor
139 public PolicyDBDao(String init) {
140 // not needed in this release
143 .error("This server's PolicyDBDao instance could not be registered and may not reveive updates");
146 otherServers = getRemotePolicyDBDaoList();
147 if (logger.isDebugEnabled()) {
148 logger.debug("Number of remote PolicyDBDao instances: " + otherServers.size());
150 if (otherServers.isEmpty()) {
151 logger.warn("List of PolicyDBDao servers is empty or could not be retrieved");
155 // not static because we are going to be using the instance's emf
156 // waitTime in ms to wait for lock, or -1 to wait forever (no)
157 @SuppressWarnings("deprecation")
158 public void startTransactionSynced(Session session, int waitTime) {
159 logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + "\n startTransactionSynced("
160 + session + "," + waitTime + ") called\n\n");
161 DatabaseLockEntity lock = null;
162 session.beginTransaction();
164 if (logger.isDebugEnabled()) {
165 logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" + "\n\n");
167 lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, LockMode.PESSIMISTIC_WRITE);
168 if (logger.isDebugEnabled()) {
169 logger.debug("\n\nstartTransactionSynced():" + "\n GOT the DB lock" + "\n\n");
171 } catch (Exception e) {
172 logger.error("Exception Occured" + e);
175 throw new IllegalStateException(
176 "The lock row does not exist in the table. Please create a primary key with value = 1.");
182 * Gets the list of other registered PolicyDBDaos from the database
184 * @return List (type PolicyDBDaoEntity) of other PolicyDBDaos
186 private List<?> getRemotePolicyDBDaoList() {
187 logger.debug("getRemotePolicyDBDaoList() as getRemotePolicyDBDaoList() called");
188 List<?> policyDBDaoEntityList = new LinkedList<>();
189 Session session = sessionfactory.openSession();
191 Criteria cr = session.createCriteria(PolicyDBDaoEntity.class);
192 policyDBDaoEntityList = cr.list();
193 } catch (Exception e) {
194 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
195 "Exception querying for other registered PolicyDBDaos");
196 logger.warn("List of remote PolicyDBDaos will be empty", e);
200 } catch (Exception e) {
201 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e);
204 return policyDBDaoEntityList;
207 public PolicyDBDaoTransaction getNewTransaction() {
208 logger.debug("getNewTransaction() as getNewTransaction() called");
209 return new PolicyDbDaoTransactionInstance("init");
213 * Because the normal transactions are not used in audits, we can use the same transaction
214 * mechanism to get a transaction and obtain the emlock and the DB lock. We just need to provide
215 * different transaction timeout values in ms because the audit will run longer than normal
218 public PolicyDBDaoTransaction getNewAuditTransaction() {
219 logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called");
220 // Use the standard transaction wait time in ms
221 int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT));
222 // Use the (extended) audit timeout time in ms
223 int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT));
224 return new PolicyDbDaoTransactionInstance(auditTimeoutMs, auditWaitMs);
228 * Checks if two strings are equal. Null strings ARE allowed.
230 * @param one A String or null to compare
231 * @param two A String or null to compare
233 public static boolean stringEquals(String one, String two) {
234 logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + ") called");
235 if (one == null && two == null) {
238 if (one == null || two == null) {
241 return one.equals(two);
245 * Returns the url of this local pap server, removing the username and password, if they are
248 * @return The url of this local pap server
250 public String[] getPapUrlUserPass() {
251 logger.debug("getPapUrl() as getPapUrl() called");
252 String url = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
256 return splitPapUrlUserPass(url);
259 public String[] splitPapUrlUserPass(String url) {
260 String[] urlUserPass = new String[3];
261 String[] commaSplit = url.split(",");
262 urlUserPass[0] = commaSplit[0];
263 if (commaSplit.length > 2) {
264 urlUserPass[1] = commaSplit[1];
265 urlUserPass[2] = commaSplit[2];
267 if (urlUserPass[1] == null || "".equals(urlUserPass[1])) {
268 String usernamePropertyValue = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID);
269 if (usernamePropertyValue != null) {
270 urlUserPass[1] = usernamePropertyValue;
273 if (urlUserPass[2] == null || "".equals(urlUserPass[2])) {
274 String passwordPropertyValue =
275 PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS));
276 if (passwordPropertyValue != null) {
277 urlUserPass[2] = passwordPropertyValue;
280 // if there is no comma, for some reason there is no user name and
281 // password, so don't try to cut them off
286 * Register the PolicyDBDao instance in the PolicyDBDaoEntity table
288 * @return Boolean, were we able to register?
290 private boolean register() {
291 logger.debug("register() as register() called");
292 String[] url = getPapUrlUserPass();
293 // --- check URL length
294 if (url == null || url.length < 3) {
297 Session session = sessionfactory.openSession();
299 startTransactionSynced(session, 1000);
300 } catch (IllegalStateException e) {
301 logger.debug("\nPolicyDBDao.register() caught an IllegalStateException: \n" + e + "\n");
302 DatabaseLockEntity lock;
303 lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1);
305 lock = new DatabaseLockEntity();
308 session.persist(lock);
310 session.getTransaction().commit();
312 } catch (Exception e2) {
313 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
314 "COULD NOT CREATE DATABASELOCK ROW. WILL TRY ONE MORE TIME");
317 session = sessionfactory.openSession();
319 startTransactionSynced(session, 1000);
320 } catch (Exception e3) {
321 String msg = "DATABASE LOCKING NOT WORKING. CONCURRENCY CONTROL NOT WORKING";
322 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e3, POLICYDBDAO_VAR, msg);
323 throw new IllegalStateException("msg" + "\n" + e3);
327 logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n");
328 PolicyDBDaoEntity foundPolicyDBDaoEntity = null;
329 Criteria cr = session.createCriteria(PolicyDBDaoEntity.class);
330 cr.add(Restrictions.eq("policyDBDaoUrl", url[0]));
331 List<?> data = cr.list();
332 if (!data.isEmpty()) {
333 foundPolicyDBDaoEntity = (PolicyDBDaoEntity) data.get(0);
336 // encrypt the password
337 String txt = PeCryptoUtils.encrypt(url[2]);
338 if (foundPolicyDBDaoEntity == null) {
339 PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity();
340 newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]);
341 newPolicyDBDaoEntity.setDescription("PAP server at " + url[0]);
342 newPolicyDBDaoEntity.setUsername(url[1]);
343 newPolicyDBDaoEntity.setPassword(txt);
345 session.persist(newPolicyDBDaoEntity);
346 session.getTransaction().commit();
347 } catch (Exception e) {
350 session.getTransaction().rollback();
351 } catch (Exception e2) {
353 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
354 "Could not add new PolicyDBDao to the database");
358 // just want to update in order to change modified date
359 if (url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())) {
360 foundPolicyDBDaoEntity.setUsername(url[1]);
362 if (txt != null && !stringEquals(txt, foundPolicyDBDaoEntity.getPassword())) {
363 foundPolicyDBDaoEntity.setPassword(txt);
365 foundPolicyDBDaoEntity.preUpdate();
367 session.getTransaction().commit();
368 } catch (Exception e) {
371 session.getTransaction().rollback();
372 } catch (Exception e2) {
374 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
375 "Could not update PolicyDBDao in the database");
380 logger.debug("\nPolicyDBDao.register(). Success!!\n");
385 * This method is called during all pushPolicy transactions and makes sure the file system group
386 * is in sync with the database groupentity
388 public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity)
389 throws PAPException, PolicyDBException {
391 HashMap<String, PDPPolicy> currentPolicyMap = new HashMap<>();
392 HashSet<String> newPolicyIdSet = new HashSet<>();
393 HashSet<PDPPolicy> newPolicySet = new HashSet<>();
395 for (PDPPolicy pdpPolicy : pdpGroup.getPolicies()) {
396 currentPolicyMap.put(pdpPolicy.getId(), pdpPolicy);
399 for (PolicyEntity policy : groupentity.getPolicies()) {
400 String pdpPolicyId = getPdpPolicyName(policy.getPolicyName(), policy.getScope());
401 newPolicyIdSet.add(pdpPolicyId);
403 if (currentPolicyMap.containsKey(pdpPolicyId)) {
404 newPolicySet.add(currentPolicyMap.get(pdpPolicyId));
406 // convert PolicyEntity object to PDPPolicy
407 String name = pdpPolicyId.replace(".xml", "");
408 name = name.substring(0, name.lastIndexOf('.'));
409 InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes());
410 pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream);
411 URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri();
412 StdPDPPolicy newPolicy = null;
414 newPolicy = new StdPDPPolicy(pdpPolicyId, true,
415 removeExtensionAndVersionFromPolicyName(pdpPolicyId), location);
416 newPolicySet.add(newPolicy);
417 logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() + ", Location - " + location);
418 } catch (Exception e) {
421 .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object "
427 for (String id : currentPolicyMap.keySet()) {
428 if (!newPolicyIdSet.contains(id)) {
430 Files.delete(Paths.get(currentPolicyMap.get(id).getLocation()));
431 } catch (Exception e) {
434 "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. "
440 logger.info("PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync");
441 pdpGroup.setPolicies(newPolicySet);
446 public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) throws PolicyDBException {
447 return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0];
451 * Splits apart the policy name and version from a policy file path
453 * @param originalPolicyName: a policy file name ex: Config_policy.2.xml
454 * @return An array [0]: The policy name, [1]: the policy version, as a string
456 public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException {
457 String policyName = originalPolicyName;
458 String[] nameAndVersion = new String[2];
460 policyName = removeFileExtension(policyName);
461 nameAndVersion[0] = policyName.substring(0, policyName.lastIndexOf('.'));
462 if (isNullOrEmpty(nameAndVersion[0])) {
463 throw new PolicyDBException();
465 } catch (Exception e) {
466 nameAndVersion[0] = originalPolicyName;
470 nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.') + 1);
471 if (isNullOrEmpty(nameAndVersion[1])) {
472 throw new PolicyDBException();
474 } catch (Exception e) {
475 nameAndVersion[1] = "1";
478 return nameAndVersion;
481 public String getPdpPolicyName(String name, String scope) {
482 String finalName = "";
485 finalName += removeFileExtension(name);
490 private String removeFileExtension(String fileName) {
491 return fileName.substring(0, fileName.lastIndexOf('.'));
494 public void auditLocalDatabase(PAPPolicyEngine papEngine2) {
495 logger.debug("PolicyDBDao.auditLocalDatabase() is called");
497 deleteAllGroupTables();
498 auditGroups(papEngine2);
499 } catch (Exception e) {
500 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "auditLocalDatabase() error");
501 logger.error("Exception Occured" + e);
505 public StdPDPGroup auditLocalFileSystem(StdPDPGroup group) {
507 logger.info("Starting Local File System group audit");
508 Session session = sessionfactory.openSession();
509 session.getTransaction().begin();
511 StdPDPGroup updatedGroup = null;
513 Query groupQuery = session.createQuery(GROUPENTITY_SELECT);
514 groupQuery.setParameter(GROUP_ID, group.getId());
515 groupQuery.setParameter(DELETED, false);
516 List<?> groupQueryList = groupQuery.list();
517 if (groupQueryList != null && !groupQueryList.isEmpty()) {
518 GroupEntity dbgroup = (GroupEntity) groupQueryList.get(0);
519 updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup);
520 logger.info("Group was updated during file system audit: " + updatedGroup.toString());
522 } catch (PAPException | PolicyDBException e) {
524 } catch (Exception e) {
526 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
527 "Caught Exception trying to check if group exists groupQuery.getResultList()");
528 throw new PersistenceException("Query failed trying to check if group " + group.getId() + " exists");
531 session.getTransaction().commit();
538 * This method is called at startup to recreate config data from DB to the file system.
541 public void synchronizeConfigDataInFileSystem() {
543 logger.info("Starting Local File System Config data Sync");
544 // sync both web apps Config and Action
545 syncConfigData(ConfigurationDataEntity.class, CONFIG);
546 syncConfigData(ActionBodyEntity.class, ACTION);
549 private <T> void syncConfigData(Class<T> cl, String type) {
550 Session session = sessionfactory.openSession();
552 final Criteria configDataQuery = session.createCriteria(cl.getName());
553 @SuppressWarnings("unchecked")
554 final List<T> configDataResult = configDataQuery.list();
555 Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), type);
557 for (final T configData : configDataResult) {
558 String configName = null;
561 if (CONFIG.equalsIgnoreCase(type)) {
562 configName = ((ConfigurationDataEntity) configData).getConfigurationName();
564 (((ConfigurationDataEntity) configData).getConfigBody() != null)
565 ? ((ConfigurationDataEntity) configData).getConfigBody()
566 .getBytes(StandardCharsets.UTF_8)
569 configName = ((ActionBodyEntity) configData).getActionBodyName();
570 configBody = (((ActionBodyEntity) configData).getActionBody() != null)
571 ? ((ActionBodyEntity) configData).getActionBody().getBytes(StandardCharsets.UTF_8)
574 Path filePath = Paths.get(webappsPath.toString(), configName);
575 if (!filePath.toFile().exists()) {
576 Files.write(filePath, configBody);
577 logger.info("Created Config File from DB - " + filePath.toString());
579 } catch (Exception e) {
580 // log and keep going
581 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
582 "Exception occured while creating Configuration File - " + configName);
585 } catch (final Exception exception) {
586 logger.error("Unable to synchronizeConfigDataInFileSystem", exception);
591 public void deleteAllGroupTables() {
592 logger.debug("PolicyDBDao.deleteAllGroupTables() called");
593 Session session = sessionfactory.openSession();
594 session.getTransaction().begin();
596 Query deletePdpEntityEntityTableUpdate = session.getNamedQuery("PdpEntity.deleteAll");
597 deletePdpEntityEntityTableUpdate.executeUpdate();
599 Query deleteGroupEntityTableUpdate = session.getNamedQuery("GroupEntity.deleteAll");
600 deleteGroupEntityTableUpdate.executeUpdate();
602 session.getTransaction().commit();
606 @SuppressWarnings("unchecked")
607 public void auditGroups(PAPPolicyEngine papEngine2) {
608 logger.debug("PolicyDBDao.auditGroups() called");
610 Session session = sessionfactory.openSession();
611 session.getTransaction().begin();
612 final String AUDIT_STR = "Audit";
615 Set<OnapPDPGroup> groups = papEngine2.getOnapPDPGroups();
617 for (OnapPDPGroup grp : groups) {
619 GroupEntity groupEntity = new GroupEntity();
620 groupEntity.setGroupName(grp.getName());
621 groupEntity.setDescription(grp.getDescription());
622 groupEntity.setDefaultGroup(grp.isDefaultGroup());
623 groupEntity.setCreatedBy(AUDIT_STR);
624 groupEntity.setGroupId(createNewPDPGroupId(grp.getId()));
625 groupEntity.setModifiedBy(AUDIT_STR);
626 session.persist(groupEntity);
627 Set<OnapPDP> pdps = grp.getOnapPdps();
629 for (OnapPDP pdp : pdps) {
630 PdpEntity pdpEntity = new PdpEntity();
631 pdpEntity.setGroup(groupEntity);
632 pdpEntity.setJmxPort(pdp.getJmxPort());
633 pdpEntity.setPdpId(pdp.getId());
634 pdpEntity.setPdpName(pdp.getName());
635 pdpEntity.setModifiedBy(AUDIT_STR);
636 pdpEntity.setCreatedBy(AUDIT_STR);
637 session.persist(pdpEntity);
640 Set<PDPPolicy> policies = grp.getPolicies();
642 for (PDPPolicy policy : policies) {
644 String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId());
645 if (stringArray == null) {
646 throw new IllegalArgumentException(
647 "Invalid input - policyID must contain name, scope and version");
649 List<PolicyEntity> policyEntityList;
650 Query getPolicyEntitiesQuery = session.getNamedQuery("PolicyEntity.findByNameAndScope");
651 getPolicyEntitiesQuery.setParameter("name", stringArray[0]);
652 getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]);
654 policyEntityList = getPolicyEntitiesQuery.list();
655 PolicyEntity policyEntity = null;
656 if (!policyEntityList.isEmpty()) {
657 policyEntity = policyEntityList.get(0);
659 if (policyEntity != null) {
660 groupEntity.addPolicyToGroup(policyEntity);
662 } catch (Exception e2) {
663 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR,
664 "Exception auditGroups inner catch");
667 } catch (Exception e1) {
668 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, POLICYDBDAO_VAR,
669 "Exception auditGroups middle catch");
672 } catch (Exception e) {
673 session.getTransaction().rollback();
674 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception auditGroups outer catch");
679 session.getTransaction().commit();
684 public String getConfigFile(String filename, PolicyRestAdapter policy) {
685 if (policy == null) {
686 return getConfigFile(filename, (String) null);
688 return getConfigFile(filename, policy.getConfigType());
691 // copied from ConfigPolicy.java and modified
692 // Here we are adding the extension for the configurations file based on the
693 // config type selection for saving.
694 public String getConfigFile(String inputFilename, String configType) {
695 String filename = inputFilename;
696 logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile(" + filename
697 + ", " + configType + ") called");
698 filename = FilenameUtils.removeExtension(filename);
699 String id = configType;
702 if (id.equals(ConfigPolicy.JSON_CONFIG) || id.contains("Firewall")) {
703 filename = filename + ".json";
705 if (id.equals(ConfigPolicy.XML_CONFIG)) {
706 filename = filename + ".xml";
708 if (id.equals(ConfigPolicy.PROPERTIES_CONFIG)) {
709 filename = filename + ".properties";
711 if (id.equals(ConfigPolicy.OTHER_CONFIG)) {
712 filename = filename + ".txt";
718 public String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
719 String[] splitByDots = fileName.split("\\.");
720 if (splitByDots.length < 3) {
723 String policyName = splitByDots[splitByDots.length - 3];
724 String version = splitByDots[splitByDots.length - 2];
725 // policy names now include version
727 for (int i = 0; i < splitByDots.length - 3; i++) {
728 scope += ".".concat(splitByDots[i]);
730 // remove the first dot
731 if (scope.length() > 0) {
732 scope = scope.substring(1);
734 String[] returnArray = new String[3];
735 returnArray[0] = policyName + "." + version + ".xml";
736 returnArray[2] = version;
737 returnArray[1] = scope;
741 public static String createNewPDPGroupId(String name) {
743 // replace "bad" characters with sequences that will be ok for file
744 // names and properties keys.
745 id = id.replace(" ", "_sp_");
746 id = id.replace("\t", "_tab_");
747 id = id.replace("\\", "_bksl_");
748 id = id.replace("/", "_sl_");
749 id = id.replace(":", "_col_");
750 id = id.replace("*", "_ast_");
751 id = id.replace("?", "_q_");
752 id = id.replace("\"", "_quo_");
753 id = id.replace("<", "_lt_");
754 id = id.replace(">", "_gt_");
755 id = id.replace("|", "_bar_");
756 id = id.replace("=", "_eq_");
757 id = id.replace(",", "_com_");
758 id = id.replace(";", "_scom_");
764 * Checks if any of the given strings are empty or null
766 * @param strings One or more Strings (or nulls) to check if they are null or empty
767 * @return true if one or more of the given strings are empty or null
769 public static boolean isNullOrEmpty(String... strings) {
770 for (String s : strings) {
771 if (s == null || "".equals(s)) {
778 public List<?> getOtherServers() {
782 public void setOtherServers(List<?> otherServers) {
783 this.otherServers = otherServers;
786 public PAPPolicyEngine getPapEngine() {
790 public static boolean isJunit() {
794 public static void setJunit(boolean isJunit) {
795 PolicyDBDao.isJunit = isJunit;
798 public static PolicyDBDaoTestClass getPolicyDBDaoTestClass() {
799 return new PolicyDBDao().new PolicyDBDaoTestClass();
802 final class PolicyDBDaoTestClass {
803 String getConfigFile(String filename, String scope, PolicyRestAdapter policy) {
804 return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy);
807 String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException {
808 return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName);
811 String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
812 return PolicyDBDao.this.getNameScopeAndVersionFromPdpPolicy(fileName);
815 String getPdpPolicyName(String name, String scope) {
816 return PolicyDBDao.this.getPdpPolicyName(name, scope);