2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.pap.xacml.rest.components;
23 import com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.api.pap.PDPPolicy;
25 import com.att.research.xacml.util.XACMLProperties;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.StringReader;
32 import java.nio.file.InvalidPathException;
33 import java.nio.file.Paths;
34 import java.util.Date;
35 import java.util.HashSet;
36 import java.util.Iterator;
37 import java.util.List;
39 import javax.persistence.PersistenceException;
40 import javax.persistence.RollbackException;
41 import javax.xml.parsers.DocumentBuilder;
42 import javax.xml.parsers.DocumentBuilderFactory;
43 import javax.xml.xpath.XPath;
44 import javax.xml.xpath.XPathFactory;
45 import org.apache.commons.io.FilenameUtils;
46 import org.apache.commons.io.IOUtils;
47 import org.hibernate.Query;
48 import org.hibernate.Session;
49 import org.hibernate.SessionFactory;
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.GroupEntity;
60 import org.onap.policy.rest.jpa.PdpEntity;
61 import org.onap.policy.rest.jpa.PolicyEntity;
62 import org.onap.policy.xacml.api.pap.OnapPDP;
63 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
64 import org.onap.policy.xacml.std.pap.StdPDPGroup;
65 import org.onap.policy.xacml.util.XACMLPolicyWriter;
66 import org.springframework.beans.factory.annotation.Autowired;
67 import org.springframework.stereotype.Component;
68 import org.w3c.dom.Document;
69 import org.xml.sax.InputSource;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
75 public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
77 private static final Logger logger = FlexLogger.getLogger(PolicyDbDaoTransactionInstance.class);
79 private final Object emLock = new Object();
84 private boolean operationRun = false;
85 private Thread transactionTimer;
86 private static final String POLICY_NOTIFICATION = "policy";
87 private static final String PDP_NOTIFICATION = "pdp";
88 private static final String GROUP_NOTIFICATION = "group";
91 private static final String DECISIONMS_MODEL = "MicroService_Model";
92 public static boolean isJunit = false;
96 * Instantiates a new policy DB dao transaction instance.
98 * @param test the test
100 public PolicyDbDaoTransactionInstance(String test) {
101 // call the constructor with arguments
102 this(Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)),
103 Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)));
106 public PolicyDbDaoTransactionInstance() {
107 // Default Constructor
111 public PolicyDbDaoTransactionInstance(SessionFactory sessionfactory) {
112 PolicyDbDaoTransactionInstance.sessionfactory = sessionfactory;
115 private static SessionFactory sessionfactory;
119 * Instantiates a new policy DB dao transaction instance.
121 * @param transactionTimeout the transaction timeout is how long the transaction can sit before
123 * @param transactionWaitTime the transaction wait time is how long to wait for the transaction
126 public PolicyDbDaoTransactionInstance(int transactionTimeout, int transactionWaitTime) {
127 logger.info("\n\nPolicyDBDaoTransactionInstance() as PolicyDBDaoTransactionInstance() called:"
128 + "\n transactionTimeout = " + transactionTimeout + "\n transactionWaitTime = "
129 + transactionWaitTime + "\n\n");
135 synchronized (emLock) {
136 session = sessionfactory.openSession();
138 PolicyDBDao.getPolicyDBDaoInstance().startTransactionSynced(session, transactionWaitTime);
139 } catch (Exception e) {
140 logger.error("Could not lock transaction within " + transactionWaitTime + " milliseconds" + e);
141 throw new PersistenceException(
142 "Could not lock transaction within " + transactionWaitTime + " milliseconds");
145 class TransactionTimer implements Runnable {
147 private int sleepTime;
149 public TransactionTimer(int timeout) {
150 this.sleepTime = timeout;
155 if (logger.isDebugEnabled()) {
156 Date date = new java.util.Date();
157 logger.debug("\n\nTransactionTimer.run() - SLEEPING: " + "\n sleepTime (ms) = " + sleepTime
158 + "\n TimeStamp = " + date.getTime() + "\n\n");
161 Thread.sleep(sleepTime);
162 } catch (InterruptedException e) {
163 // probably, the transaction was completed, the last thing
164 // we want to do is roll back
165 if (logger.isDebugEnabled()) {
166 Date date = new java.util.Date();
167 logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: " + "\n TimeStamp = "
168 + date.getTime() + "\n\n");
170 Thread.currentThread().interrupt();
173 if (logger.isDebugEnabled()) {
174 Date date = new java.util.Date();
175 logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " + "\n TimeStamp = " + date.getTime()
178 logger.warn("PolicyDBDaoTransactionInstance - TransactionTimer - Rolling back transaction.");
179 rollbackTransaction();
184 transactionTimer = new Thread(new TransactionTimer(transactionTimeout), "transactionTimerThread");
185 transactionTimer.start();
189 private void checkBeforeOperationRun() {
190 checkBeforeOperationRun(false);
193 private void checkBeforeOperationRun(boolean justCheckOpen) {
194 if (!isTransactionOpen()) {
195 PolicyLogger.warn("checkBeforeOperationRun - There is no transaction currently open");
196 throw new IllegalStateException("There is no transaction currently open");
198 if (operationRun && !justCheckOpen) {
199 PolicyLogger.warn("checkBeforeOperationRun - "
200 + "An operation has already been performed and the current transaction should be committed");
201 throw new IllegalStateException(
202 "An operation has already been performed and the current transaction should be committed");
208 public void commitTransaction() {
209 synchronized (emLock) {
210 NotifyOtherPaps otherPaps = new NotifyOtherPaps();
211 logger.debug("commitTransaction() as commitTransaction() called");
212 if (!isTransactionOpen()) {
214 "There is no open transaction to commit - PolicyId - " + policyId + ", GroupId - " + groupId);
217 } catch (Exception e) {
218 logger.error("Exception Occured" + e);
223 session.getTransaction().commit();
224 } catch (RollbackException e) {
225 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
226 "Caught RollbackException on em.getTransaction().commit()");
227 throw new PersistenceException("The commit failed. Message:\n" + e.getMessage());
232 if (newGroupId != null) {
234 otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION, newGroupId);
235 } catch (Exception e) {
236 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
237 "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ","
242 otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION);
243 } catch (Exception e) {
244 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
245 "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ")");
250 // we don't want commit to fail just because this does
251 if (newGroupId != null) {
253 otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION, newGroupId);
254 } catch (Exception e) {
255 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
256 "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ","
261 otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION);
262 } catch (Exception e) {
263 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
264 "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ")");
269 // we don't want commit to fail just because this does
271 otherPaps.notifyOthers(pdpId, PDP_NOTIFICATION);
272 } catch (Exception e) {
273 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
274 "Caught Exception on notifyOthers(" + pdpId + "," + PDP_NOTIFICATION + ")");
278 if (transactionTimer != null) {
279 transactionTimer.interrupt();
284 public void rollbackTransaction() {
285 logger.debug("rollbackTransaction() as rollbackTransaction() called");
286 synchronized (emLock) {
287 if (isTransactionOpen()) {
289 session.getTransaction().rollback();
290 } catch (Exception e) {
291 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
292 "Could not rollback transaction");
296 } catch (Exception e) {
297 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
298 "Could not close Hibernate Session.");
304 } catch (Exception e) {
305 logger.warn("Could not close already closed transaction", e);
309 if (transactionTimer != null) {
310 transactionTimer.interrupt();
314 private void createPolicy(PolicyRestAdapter policy, String username, String policyScope, String inputPolicyName,
315 String policyDataString) {
316 String policyName = inputPolicyName;
317 logger.debug("createPolicy(PolicyRestAdapter policy, String username, String policyScope,"
318 + " String policyName, String policyDataString) as createPolicy(" + policy + ", " + username + ", "
319 + policyScope + ", " + policyName + ", " + policyDataString + ") called");
320 synchronized (emLock) {
321 PolicyDBDao policyDbDao = new PolicyDBDao();
322 checkBeforeOperationRun();
323 String configName = policyName;
324 if (policyName.contains("Config_")) {
325 policyName = policyName.replace(".Config_", ":Config_");
326 } else if (policyName.contains("Action_")) {
327 policyName = policyName.replace(".Action_", ":Action_");
328 } else if (policyName.contains("Decision_MS_")) {
329 policyName = policyName.replace(".Decision_MS_", ":Decision_MS_");
330 } else if (policyName.contains("Decision_")) {
331 policyName = policyName.replace(".Decision_", ":Decision_");
333 policyName = policyName.split(":")[1];
334 Query createPolicyQuery = session
335 .createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
336 createPolicyQuery.setParameter(PolicyDBDao.SCOPE, policyScope);
337 createPolicyQuery.setParameter("policyName", policyName);
338 List<?> createPolicyQueryList = createPolicyQuery.list();
339 PolicyEntity newPolicyEntity;
341 if (createPolicyQueryList.isEmpty()) {
342 newPolicyEntity = new PolicyEntity();
344 } else if (createPolicyQueryList.size() > 1) {
345 PolicyLogger.error("Somehow, more than one policy with the same "
346 + "scope, name, and deleted status were found in the database");
347 throw new PersistenceException("Somehow, more than one policy with the same"
348 + " scope, name, and deleted status were found in the database");
350 newPolicyEntity = (PolicyEntity) createPolicyQueryList.get(0);
354 ActionBodyEntity newActionBodyEntity = null;
355 if (policy.getPolicyType().equals(PolicyDBDao.ACTION)) {
356 boolean abupdate = false;
357 if (newPolicyEntity.getActionBodyEntity() == null) {
358 newActionBodyEntity = new ActionBodyEntity();
360 newActionBodyEntity = (ActionBodyEntity) session.get(ActionBodyEntity.class,
361 newPolicyEntity.getActionBodyEntity().getActionBodyId());
365 if (newActionBodyEntity != null) {
366 // build the file path
367 // trim the .xml off the end
368 String policyNameClean = FilenameUtils.removeExtension(configName);
369 String actionBodyName = policyNameClean + ".json";
371 // get the action body
372 String actionBodyString = policy.getActionBody();
373 if (actionBodyString == null) {
374 actionBodyString = "{}";
376 newActionBodyEntity.setActionBody(actionBodyString);
377 newActionBodyEntity.setActionBodyName(actionBodyName);
378 newActionBodyEntity.setModifiedBy("PolicyDBDao.createPolicy()");
379 newActionBodyEntity.setDeleted(false);
381 newActionBodyEntity.setCreatedBy("PolicyDBDao.createPolicy()");
383 if (logger.isDebugEnabled()) {
384 logger.debug("\nPolicyDBDao.createPolicy" + "\n newActionBodyEntity.getActionBody() = "
385 + newActionBodyEntity.getActionBody()
386 + "\n newActionBodyEntity.getActionBodyName() = "
387 + newActionBodyEntity.getActionBodyName()
388 + "\n newActionBodyEntity.getModifiedBy() = " + newActionBodyEntity.getModifiedBy()
389 + "\n newActionBodyEntity.getCreatedBy() = " + newActionBodyEntity.getCreatedBy()
390 + "\n newActionBodyEntity.isDeleted() = " + newActionBodyEntity.isDeleted()
391 + "\n FLUSHING to DB");
393 // push the actionBodyEntity to the DB
395 newActionBodyEntity.prePersist();
398 session.persist(newActionBodyEntity);
401 // newActionBodyEntity == null
402 // We have a actionBody in the policy but we found no
403 // actionBody in the DB
404 String msg = "\n\nPolicyDBDao.createPolicy - Incoming Action policy had an "
405 + "actionBody, but it could not be found in the DB for update." + "\n policyScope = "
406 + policyScope + "\n policyName = " + policyName + "\n\n";
407 PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, "
408 + "but it could not be found in the DB for update: policyName = " + policyName);
409 throw new IllegalArgumentException(msg);
413 ConfigurationDataEntity newConfigurationDataEntity;
414 if (PolicyDBDao.CONFIG.equals(policy.getPolicyType())
415 || DECISIONMS_MODEL.equals(policy.getRuleProvider())) {
416 boolean configUpdate;
417 if (newPolicyEntity.getConfigurationData() == null) {
418 newConfigurationDataEntity = new ConfigurationDataEntity();
419 configUpdate = false;
421 newConfigurationDataEntity = (ConfigurationDataEntity) session.get(ConfigurationDataEntity.class,
422 newPolicyEntity.getConfigurationData().getConfigurationDataId());
426 if (newConfigurationDataEntity != null) {
427 if (!PolicyDBDao.stringEquals(newConfigurationDataEntity.getConfigurationName(),
428 policyDbDao.getConfigFile(configName, policy))) {
429 newConfigurationDataEntity.setConfigurationName(policyDbDao.getConfigFile(configName, policy));
431 if (newConfigurationDataEntity.getConfigType() == null
432 || !newConfigurationDataEntity.getConfigType().equals(policy.getConfigType())) {
433 newConfigurationDataEntity.setConfigType(policy.getConfigType());
436 newConfigurationDataEntity.setCreatedBy(username);
438 if (newConfigurationDataEntity.getModifiedBy() == null
439 || !newConfigurationDataEntity.getModifiedBy().equals(username)) {
440 newConfigurationDataEntity.setModifiedBy(username);
442 if (newConfigurationDataEntity.getDescription() == null
443 || !newConfigurationDataEntity.getDescription().equals("")) {
444 newConfigurationDataEntity.setDescription("");
446 if (newConfigurationDataEntity.getConfigBody() == null
447 || newConfigurationDataEntity.getConfigBody().isEmpty()
448 || (!newConfigurationDataEntity.getConfigBody().equals(policy.getConfigBodyData()))) {
449 // hopefully one of these won't be null
450 if (policy.getConfigBodyData() == null || policy.getConfigBodyData().isEmpty()) {
451 newConfigurationDataEntity.setConfigBody(policy.getJsonBody());
453 newConfigurationDataEntity.setConfigBody(policy.getConfigBodyData());
456 if (newConfigurationDataEntity.isDeleted()) {
457 newConfigurationDataEntity.setDeleted(false);
460 newConfigurationDataEntity.prePersist();
463 session.persist(newConfigurationDataEntity);
466 // We have a configurationData body in the policy but we
467 // found no configurationData body in the DB
468 String msg = "\n\nPolicyDBDao.createPolicy - Incoming Config policy had a "
469 + "configurationData body, but it could not be found in the DB for update."
470 + "\n policyScope = " + policyScope + "\n policyName = " + policyName + "\n\n";
472 .error("PolicyDBDao.createPolicy - Incoming Config policy had a configurationData body, "
473 + "but it could not be found in the DB for update: policyName = " + policyName);
474 throw new IllegalArgumentException(msg);
478 newConfigurationDataEntity = null;
480 policyId = newPolicyEntity.getPolicyId();
482 if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) {
483 newPolicyEntity.setPolicyName(policyName);
485 if (!PolicyDBDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) {
486 newPolicyEntity.setCreatedBy(username);
488 if (!PolicyDBDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) {
489 newPolicyEntity.setDescription(policy.getPolicyDescription());
491 if (!PolicyDBDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) {
492 newPolicyEntity.setModifiedBy(username);
494 if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) {
495 newPolicyEntity.setPolicyData(policyDataString);
497 if (!PolicyDBDao.stringEquals(newPolicyEntity.getScope(), policyScope)) {
498 newPolicyEntity.setScope(policyScope);
500 if (newPolicyEntity.isDeleted()) {
501 newPolicyEntity.setDeleted(false);
503 newPolicyEntity.setConfigurationData(newConfigurationDataEntity);
504 newPolicyEntity.setActionBodyEntity(newActionBodyEntity);
506 newPolicyEntity.prePersist();
509 session.persist(newPolicyEntity);
512 this.policyId = newPolicyEntity.getPolicyId();
518 public void createPolicy(Policy policy, String username) {
519 InputStream policyXmlStream = null;
521 logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + policy + ","
522 + username + ") called");
523 String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, ".");
524 // Does not need to be XACMLPolicyWriterWithPapNotify since it is
525 // already in the PAP
526 // and this transaction is intercepted up stream.
527 String policyDataString;
530 if (policy.policyAdapter.getData() instanceof PolicySetType) {
531 policyXmlStream = XACMLPolicyWriter
532 .getPolicySetXmlAsInputStream((PolicySetType) policy.getCorrectPolicyDataObject());
534 policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policy.getCorrectPolicyDataObject());
536 policyDataString = IOUtils.toString(policyXmlStream);
537 } catch (IOException e) {
538 policyDataString = "could not read";
539 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
540 "Caught IOException on IOUtils.toString(" + policyXmlStream + ")");
541 throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter.");
544 IOUtils.closeQuietly(policyXmlStream);
545 if (PolicyDBDao.isJunit) {
546 // Using parentPath object to set policy data.
547 policyDataString = policy.policyAdapter.getParentPath();
549 String configPath = "";
550 if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
551 configPath = evaluateXPath(
552 "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
554 } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
555 configPath = evaluateXPath(
556 "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, "
557 + policy.policyAdapter.getActionAttribute()
558 + ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()",
560 } else if (DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
561 configPath = evaluateXPath(
562 "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
566 String prefix = null;
567 if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())
568 || DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
569 prefix = configPath.substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(),
570 configPath.lastIndexOf(policy.policyAdapter.getPolicyName()));
571 if (PolicyDBDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) {
572 String configData = "";
574 String newConfigPath = configPath;
576 newConfigPath = processConfigPath(newConfigPath);
577 } catch (Exception e2) {
578 logger.error("Could not process config path: " + newConfigPath, e2);
580 configData = readConfigFile(newConfigPath);
581 } catch (Exception e) {
582 logger.error("Could not read config body data for " + configPath, e);
584 policy.policyAdapter.setConfigBodyData(configData);
586 } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
588 } else if ("Decision".equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
589 prefix = "Decision_";
592 if (!(policy.policyAdapter.getData() instanceof PolicyType)
593 && !(policy.policyAdapter.getData() instanceof PolicySetType)) {
594 PolicyLogger.error("The data field is not an instance of PolicyType");
595 throw new IllegalArgumentException("The data field is not an instance of PolicyType");
597 String finalName = policyScope + "." + prefix + policy.policyAdapter.getPolicyName() + "."
598 + policy.policyAdapter.getHighestVersion() + ".xml";
599 if (policy.policyAdapter.getConfigType() == null || "".equals(policy.policyAdapter.getConfigType())) {
600 // get the config file extension
602 if (configPath != null && !"".equalsIgnoreCase(configPath)) {
603 ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());;
606 if (ext.contains("txt")) {
607 policy.policyAdapter.setConfigType(PolicyDBDao.OTHER_CONFIG);
608 } else if (ext.contains("json")) {
609 policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG);
610 } else if (ext.contains("xml")) {
611 policy.policyAdapter.setConfigType(PolicyDBDao.XML_CONFIG);
612 } else if (ext.contains("properties")) {
613 policy.policyAdapter.setConfigType(PolicyDBDao.PROPERTIES_CONFIG);
615 if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDBDao.ACTION)) {
616 policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG);
621 createPolicy(policy.policyAdapter, username, policyScope, finalName, policyDataString);
623 if (policyXmlStream != null) {
625 policyXmlStream.close();
626 } catch (IOException e) {
627 logger.error("Exception Occured while closing input stream" + e);
634 public PolicyEntity getPolicy(int policyId) {
635 return getPolicy(policyId, null, null);
638 public PolicyEntity getPolicy(String policyName, String scope) {
639 return getPolicy(-1, policyName, scope);
642 private PolicyEntity getPolicy(int policyIdVar, String policyName, String scope) {
643 logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar + "," + policyName
645 if (policyIdVar < 0 && PolicyDBDao.isNullOrEmpty(policyName, scope)) {
646 throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank");
649 synchronized (emLock) {
650 checkBeforeOperationRun(true);
651 // check if group exists
654 if (!PolicyDBDao.isNullOrEmpty(policyName, scope)) {
655 policyId = policyName;
657 session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope");
658 policyQuery.setParameter("name", policyId);
659 policyQuery.setParameter("scope", scope);
661 policyId = String.valueOf(policyIdVar);
662 policyQuery = session.getNamedQuery("PolicyEntity.FindById");
663 policyQuery.setParameter("id", policyId);
665 List<?> policyQueryList;
667 policyQueryList = policyQuery.list();
668 } catch (Exception e) {
669 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
670 "Caught Exception trying to get policy with policyQuery.getResultList()");
671 throw new PersistenceException("Query failed trying to get policy " + policyId);
674 if (policyQueryList.isEmpty()) {
675 PolicyLogger.error("Policy does not exist with id " + policyId);
676 throw new PersistenceException("Group policy is being added to does not exist with id " + policyId);
677 } else if (policyQueryList.size() > 1) {
678 PolicyLogger.error(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB);
679 throw new PersistenceException(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB);
681 return (PolicyEntity) policyQueryList.get(0);
686 public GroupEntity getGroup(long groupKey) {
687 logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + ") called");
689 throw new IllegalArgumentException("groupKey must be at least 0");
691 synchronized (emLock) {
692 checkBeforeOperationRun(true);
693 // check if group exists
694 Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey");
695 groupQuery.setParameter("groupKey", groupKey);
696 List<?> groupQueryList;
698 groupQueryList = groupQuery.list();
699 } catch (Exception e) {
700 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
701 "Caught Exception trying to get group with groupQuery.getResultList()");
702 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupKey);
704 if (groupQueryList.isEmpty()) {
705 PolicyLogger.error("Group does not exist with groupKey " + groupKey);
706 throw new PersistenceException("Group does not exist with groupKey " + groupKey);
707 } else if (groupQueryList.size() > 1) {
709 .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB);
710 throw new PersistenceException(
711 "Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB);
713 return (GroupEntity) groupQueryList.get(0);
718 public GroupEntity getGroup(String groupId) {
719 logger.debug("getGroup(String groupId) as getGroup(" + groupId + ") called");
720 if (PolicyDBDao.isNullOrEmpty(groupId)) {
721 throw new IllegalArgumentException("groupId must not be null or empty");
723 synchronized (emLock) {
724 checkBeforeOperationRun(true);
725 // check if group exists
726 Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId");
727 groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId);
728 List<?> groupQueryList;
730 groupQueryList = groupQuery.list();
731 } catch (Exception e) {
732 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
733 "Caught Exception trying to get group with groupQuery.getResultList()");
734 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupId);
736 if (groupQueryList.isEmpty()) {
737 PolicyLogger.error("Group does not exist with id " + groupId);
738 throw new PersistenceException("Group does not exist with id " + groupId);
739 } else if (groupQueryList.size() > 1) {
740 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB);
741 throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB);
743 return (GroupEntity) groupQueryList.get(0);
748 public List<?> getPdpsInGroup(long groupKey) {
749 logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + ") called");
751 throw new IllegalArgumentException("groupId must not be < 0");
753 synchronized (emLock) {
754 checkBeforeOperationRun(true);
755 Query pdpsQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group");
756 pdpsQuery.setParameter("group", getGroup(groupKey));
757 return pdpsQuery.list();
762 public PdpEntity getPdp(long pdpKey) {
763 logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + ") called");
765 throw new IllegalArgumentException("pdpKey must be at least 0");
767 synchronized (emLock) {
768 checkBeforeOperationRun(true);
769 // check if group exists
770 Query pdpQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey");
771 pdpQuery.setParameter("pdpKey", pdpKey);
772 List<?> pdpQueryList;
774 pdpQueryList = pdpQuery.list();
775 } catch (Exception e) {
776 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
777 "Caught Exception trying to get pdp with pdpQuery.getResultList()");
778 throw new PersistenceException("Query failed trying to get pdp " + pdpKey);
780 if (pdpQueryList.isEmpty()) {
781 PolicyLogger.error("Pdp does not exist with pdpKey " + pdpKey);
782 throw new PersistenceException("Pdp does not exist with pdpKey " + pdpKey);
783 } else if (pdpQueryList.size() > 1) {
784 PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB);
785 throw new PersistenceException(
786 "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB);
788 return (PdpEntity) pdpQueryList.get(0);
793 public boolean isTransactionOpen() {
794 logger.debug("isTransactionOpen() as isTransactionOpen() called");
795 synchronized (emLock) {
796 return session.isOpen() && session.getTransaction().isActive();
800 private String processConfigPath(String inputConfigPath) {
801 String configPath = inputConfigPath;
802 String webappsPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS);
803 if (webappsPath == null) {
804 logger.error("Webapps property does not exist");
805 throw new IllegalArgumentException("Webapps property does not exist");
807 configPath = configPath.replace("$URL", webappsPath);
808 // make sure the correct slashes are in
810 configPath = Paths.get(configPath).toString();
811 } catch (InvalidPathException e) {
812 logger.error("Invalid config path: " + configPath, e);
813 throw new IllegalArgumentException("Invalid config path: " + configPath);
818 private String readConfigFile(String configPath) {
819 String configDataString = null;
820 InputStream configContentStream = null;
822 configContentStream = new FileInputStream(configPath);
823 configDataString = IOUtils.toString(configContentStream);
824 } catch (FileNotFoundException e) {
825 logger.error("Caught FileNotFoundException on new FileInputStream(" + configPath + ")", e);
826 throw new IllegalArgumentException("The config file path does not exist");
827 } catch (IOException e2) {
828 logger.error("Caught IOException on newIOUtils.toString(" + configContentStream + ")", e2);
829 throw new IllegalArgumentException("The config file path cannot be read");
831 IOUtils.closeQuietly(configContentStream);
833 if (configDataString == null) {
834 throw new IllegalArgumentException("The config file path cannot be read");
836 return configDataString;
841 public void close() {
842 synchronized (emLock) {
843 if (session.isOpen()) {
844 if (session.getTransaction().isActive()) {
845 session.getTransaction().rollback();
849 if (transactionTimer != null) {
850 transactionTimer.interrupt();
856 public void createGroup(String groupId, String groupName, String inputGroupDescription, String username) {
857 String groupDescription = inputGroupDescription;
858 logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + groupName + ", "
859 + groupDescription + ") called");
860 if (PolicyDBDao.isNullOrEmpty(groupId, groupName, username)) {
861 throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty");
863 if (groupDescription == null) {
864 groupDescription = "";
867 synchronized (emLock) {
868 checkBeforeOperationRun();
869 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
870 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId);
871 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
872 List<?> checkGroupQueryList;
874 checkGroupQueryList = checkGroupQuery.list();
875 } catch (Exception e) {
876 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
877 "Caught Exception on checkGroupQuery.getResultList()");
878 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
880 if (!checkGroupQueryList.isEmpty()) {
881 PolicyLogger.error("The group being added already exists with id " + groupId);
882 throw new PersistenceException("The group being added already exists with id " + groupId);
884 GroupEntity newGroup = new GroupEntity();
885 newGroup.setCreatedBy(username);
886 newGroup.setModifiedBy(username);
887 newGroup.setGroupName(groupName);
888 newGroup.setGroupId(groupId);
889 newGroup.setDescription(groupDescription);
891 newGroup.prePersist();
893 session.persist(newGroup);
895 this.groupId = newGroup.getGroupKey();
900 public void updateGroup(OnapPDPGroup group, String requestType, String username) {
901 logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + "," + requestType + ","
902 + username + ") called");
904 throw new IllegalArgumentException("PDPGroup group must not be null");
906 if (PolicyDBDao.isNullOrEmpty(group.getId(), requestType)) {
907 throw new IllegalArgumentException("group.getId() and username must not be null or empty");
910 synchronized (emLock) {
911 PolicyDBDao policyDbDaoVar = new PolicyDBDao();
912 checkBeforeOperationRun();
913 Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
914 getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
915 getGroupQuery.setParameter(PolicyDBDao.DELETED, false);
916 List<?> getGroupQueryList;
918 getGroupQueryList = getGroupQuery.list();
919 } catch (Exception e) {
920 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
921 "Caught Exception on getGroupQuery.getResultList()");
922 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing");
924 if (getGroupQueryList.isEmpty()) {
925 PolicyLogger.error("The group cannot be found to update with id " + group.getId());
926 throw new PersistenceException("The group cannot be found to update with id " + group.getId());
927 } else if (getGroupQueryList.size() > 1) {
928 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
929 throw new PersistenceException(
930 PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
932 GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0);
933 if (!PolicyDBDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) {
934 groupToUpdateInDb.setModifiedBy(requestType);
936 if (group.getDescription() != null
937 && !PolicyDBDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) {
938 groupToUpdateInDb.setDescription(group.getDescription());
940 // let's find out what policies have been deleted
941 StdPDPGroup oldGroup = null;
943 oldGroup = (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getId());
944 } catch (PAPException e1) {
945 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR,
946 "We cannot get the group from the papEngine to delete policies");
948 if (oldGroup == null) {
949 PolicyLogger.error("We cannot get the group from the papEngine to delete policies");
951 Set<String> newPolicySet = new HashSet<>(group.getPolicies().size());
952 // a multiple of n runtime is faster than n^2, so I am using a
953 // hashset to do the comparison
954 for (PDPPolicy pol : group.getPolicies()) {
955 newPolicySet.add(pol.getId());
957 for (PDPPolicy pol : oldGroup.getPolicies()) {
958 // should be fast since getPolicies uses a HashSet in
960 if (!newPolicySet.contains(pol.getId())) {
961 String[] scopeAndName = policyDbDaoVar.getNameScopeAndVersionFromPdpPolicy(pol.getId());
962 PolicyEntity policyToDelete = null;
964 if (scopeAndName != null) {
965 policyToDelete = getPolicy(scopeAndName[0], scopeAndName[1]);
966 if ("XACMLPapServlet.doDelete".equals(requestType)) {
967 Iterator<PolicyEntity> dbPolicyIt = groupToUpdateInDb.getPolicies().iterator();
968 String policyName = policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
969 policyToDelete.getPolicyName())[0];
971 logger.info("PolicyDBDao: delete policy from GroupEntity");
973 while (dbPolicyIt.hasNext()) {
974 PolicyEntity dbpolicy = dbPolicyIt.next();
975 if (policyToDelete.getScope().equals(dbpolicy.getScope())
976 && policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
977 dbpolicy.getPolicyName())[0].equals(policyName)) {
979 logger.info("PolicyDBDao: deleting policy from the existing group:\n "
980 + "policyName is " + policyToDelete.getScope() + "."
981 + policyToDelete.getPolicyName() + "\n" + "group is "
982 + groupToUpdateInDb.getGroupId());
985 } catch (Exception e) {
987 PolicyLogger.error("Could not delete policy with name: "
988 + policyToDelete.getScope() + "." + policyToDelete.getPolicyName()
989 + "\n ID: " + policyToDelete.getPolicyId());
993 } catch (Exception e) {
994 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
995 "Could not get policy to remove: " + pol.getId());
996 throw new PersistenceException("Could not get policy to remove: " + pol.getId());
1002 if (group.getName() != null
1003 && !PolicyDBDao.stringEquals(group.getName(), groupToUpdateInDb.getgroupName())) {
1004 // we need to check if the new id exists in the database
1005 String newGrpId = PolicyDBDao.createNewPDPGroupId(group.getName());
1006 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1007 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, newGrpId);
1008 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1009 List<?> checkGroupQueryList;
1011 checkGroupQueryList = checkGroupQuery.list();
1012 } catch (Exception e) {
1013 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1014 "Caught Exception on checkGroupQuery.getResultList()");
1015 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
1017 if (!checkGroupQueryList.isEmpty()) {
1018 PolicyLogger.error("The new group name already exists, group id " + newGrpId);
1019 throw new PersistenceException("The new group name already exists, group id " + newGrpId);
1021 groupToUpdateInDb.setGroupId(newGrpId);
1022 groupToUpdateInDb.setGroupName(group.getName());
1023 this.newGroupId = group.getId();
1026 this.groupId = groupToUpdateInDb.getGroupKey();
1031 public void addPdpToGroup(String pdpId, String groupIdVar, String pdpName, String pdpDescription, int pdpJmxPort,
1033 logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, "
1034 + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + pdpId + ", "
1035 + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + username
1037 if (PolicyDBDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) {
1038 throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty");
1040 synchronized (emLock) {
1041 checkBeforeOperationRun();
1042 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1043 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar);
1044 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1045 List<?> checkGroupQueryList;
1047 checkGroupQueryList = checkGroupQuery.list();
1048 } catch (Exception e) {
1049 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1050 "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()");
1051 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
1053 if (checkGroupQueryList.size() != 1) {
1054 PolicyLogger.error("The group does not exist");
1055 throw new PersistenceException("The group does not exist");
1057 Query checkDuplicateQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1058 checkDuplicateQuery.setParameter(PolicyDBDao.PDP_ID, pdpId);
1059 checkDuplicateQuery.setParameter(PolicyDBDao.DELETED, false);
1060 List<?> checkDuplicateList;
1062 checkDuplicateList = checkDuplicateQuery.list();
1063 } catch (Exception e) {
1064 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1065 "Caught Exception trying to check for duplicate PDP " + pdpId
1066 + " on checkDuplicateQuery.getResultList()");
1067 throw new PersistenceException("Query failed trying to check for duplicate PDP " + pdpId);
1070 if (!checkDuplicateList.isEmpty()) {
1071 logger.warn("PDP already exists with id " + pdpId);
1072 newPdp = (PdpEntity) checkDuplicateList.get(0);
1074 newPdp = new PdpEntity();
1077 newPdp.setCreatedBy(username);
1078 newPdp.setDeleted(false);
1079 newPdp.setDescription(pdpDescription);
1080 newPdp.setGroup((GroupEntity) checkGroupQueryList.get(0));
1081 newPdp.setJmxPort(pdpJmxPort);
1082 newPdp.setModifiedBy(username);
1083 newPdp.setPdpId(pdpId);
1084 newPdp.setPdpName(pdpName);
1086 newPdp.prePersist();
1088 session.persist(newPdp);
1090 this.pdpId = newPdp.getPdpKey();
1095 public void updatePdp(OnapPDP pdp, String username) {
1096 logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + ") called");
1098 throw new IllegalArgumentException("PDP pdp must not be null");
1100 if (PolicyDBDao.isNullOrEmpty(pdp.getId(), username)) {
1101 throw new IllegalArgumentException("pdp.getId() and username must not be null or empty");
1104 synchronized (emLock) {
1105 checkBeforeOperationRun();
1106 Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1107 getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId());
1108 getPdpQuery.setParameter(PolicyDBDao.DELETED, false);
1109 List<?> getPdpQueryList;
1111 getPdpQueryList = getPdpQuery.list();
1112 } catch (Exception e) {
1113 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1114 "Caught Exception on getPdpQuery.getResultList()");
1115 throw new PersistenceException("Query failed trying to get PDP " + pdp.getId());
1117 if (getPdpQueryList.isEmpty()) {
1118 PolicyLogger.error("The pdp cannot be found to update with id " + pdp.getId());
1119 throw new PersistenceException("The pdp cannot be found to update with id " + pdp.getId());
1120 } else if (getPdpQueryList.size() > 1) {
1121 PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1122 throw new PersistenceException(
1123 PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1125 PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1126 if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1127 pdpToUpdate.setModifiedBy(username);
1129 if (pdp.getDescription() != null
1130 && !PolicyDBDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) {
1131 pdpToUpdate.setDescription(pdp.getDescription());
1133 if (pdp.getName() != null && !PolicyDBDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) {
1134 pdpToUpdate.setPdpName(pdp.getName());
1136 if (pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())) {
1137 pdpToUpdate.setJmxPort(pdp.getJmxPort());
1141 this.pdpId = pdpToUpdate.getPdpKey();
1146 public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) {
1147 logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + "," + group + ","
1148 + username + ") called");
1149 if (pdp == null || group == null) {
1150 throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null");
1152 if (PolicyDBDao.isNullOrEmpty(username, pdp.getId(), group.getId())) {
1153 throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty");
1156 synchronized (emLock) {
1157 checkBeforeOperationRun();
1158 // check if pdp exists
1159 Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1160 getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId());
1161 getPdpQuery.setParameter(PolicyDBDao.DELETED, false);
1162 List<?> getPdpQueryList;
1164 getPdpQueryList = getPdpQuery.list();
1165 } catch (Exception e) {
1166 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1167 "Caught Exception on getPdpQuery.getResultList()");
1168 throw new PersistenceException("Query failed trying to get pdp to move with id " + pdp.getId());
1170 if (getPdpQueryList.isEmpty()) {
1171 PolicyLogger.error("The pdp cannot be found to move with id " + pdp.getId());
1172 throw new PersistenceException("The pdp cannot be found to move with id " + pdp.getId());
1173 } else if (getPdpQueryList.size() > 1) {
1174 PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1175 throw new PersistenceException(
1176 PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1179 // check if new group exists
1180 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1181 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1182 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1183 List<?> checkGroupQueryList;
1185 checkGroupQueryList = checkGroupQuery.list();
1186 } catch (Exception e) {
1187 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1188 "Caught Exception trying to get group on checkGroupQuery.getResultList()");
1189 throw new PersistenceException("Query failed trying to get new group " + group.getId());
1191 if (checkGroupQueryList.size() != 1) {
1192 PolicyLogger.error("The group " + group.getId() + " does not exist");
1193 throw new PersistenceException("The group " + group.getId() + " does not exist");
1195 GroupEntity groupToMoveInto = (GroupEntity) checkGroupQueryList.get(0);
1196 PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1197 pdpToUpdate.setGroup(groupToMoveInto);
1198 if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1199 pdpToUpdate.setModifiedBy(username);
1203 this.pdpId = pdpToUpdate.getPdpKey();
1208 public void changeDefaultGroup(OnapPDPGroup group, String username) {
1209 logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + ","
1210 + username + ") called");
1211 if (group == null) {
1212 throw new IllegalArgumentException("PDPGroup group must not be null");
1214 if (PolicyDBDao.isNullOrEmpty(group.getId(), username)) {
1215 throw new IllegalArgumentException("group.getId() and username must not be null or empty");
1218 synchronized (emLock) {
1219 checkBeforeOperationRun();
1220 Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1221 getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1222 getGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1223 List<?> getGroupQueryList;
1225 getGroupQueryList = getGroupQuery.list();
1226 } catch (Exception e) {
1227 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1228 "Caught Exception on getGroupQuery.getResultList()");
1229 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId());
1231 if (getGroupQueryList.isEmpty()) {
1232 PolicyLogger.error("The group cannot be found to set default with id " + group.getId());
1233 throw new PersistenceException("The group cannot be found to set default with id " + group.getId());
1234 } else if (getGroupQueryList.size() > 1) {
1235 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1236 throw new PersistenceException(
1237 PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1239 GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0);
1240 newDefaultGroup.setDefaultGroup(true);
1241 if (!PolicyDBDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) {
1242 newDefaultGroup.setModifiedBy(username);
1246 this.groupId = newDefaultGroup.getGroupKey();
1247 Query setAllGroupsNotDefault = session.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup "
1248 + "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey");
1249 // not going to set modified by for all groups
1250 setAllGroupsNotDefault.setParameter("defaultGroup", false);
1251 setAllGroupsNotDefault.setParameter(PolicyDBDao.DELETED, false);
1252 setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey());
1254 logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default");
1255 } catch (Exception e) {
1256 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1257 "Caught Exception on setAllGroupsNotDefault.executeUpdate()");
1258 throw new PersistenceException("Could not set all other groups default to false");
1265 public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDBException {
1266 logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup(" + group + ", "
1267 + moveToGroup + "," + username + ") called");
1268 if (group == null) {
1269 throw new IllegalArgumentException("PDPGroup group cannot be null");
1271 if (PolicyDBDao.isNullOrEmpty(username, group.getId())) {
1272 throw new IllegalArgumentException("group.getId() and and username must not be null or empty");
1275 if (group.isDefaultGroup()) {
1276 PolicyLogger.error("The default group " + group.getId() + " was attempted to be deleted. It cannot be.");
1277 throw new PolicyDBException("You cannot delete the default group.");
1279 synchronized (emLock) {
1280 checkBeforeOperationRun();
1281 Query deleteGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1282 deleteGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1283 deleteGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1284 List<?> deleteGroupQueryList;
1286 deleteGroupQueryList = deleteGroupQuery.list();
1287 } catch (Exception e) {
1288 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1289 "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()");
1290 throw new PersistenceException("Query failed trying to check if group exists");
1292 if (deleteGroupQueryList.isEmpty()) {
1293 logger.warn(PolicyDBDao.GROUP_NOT_FOUND + group.getId());
1295 } else if (deleteGroupQueryList.size() > 1) {
1296 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1297 throw new PersistenceException(
1298 PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1301 Query pdpsInGroupQuery =
1302 session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted");
1303 pdpsInGroupQuery.setParameter("group", (deleteGroupQueryList.get(0)));
1304 pdpsInGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1305 List<?> pdpsInGroupList;
1307 pdpsInGroupList = pdpsInGroupQuery.list();
1308 } catch (Exception e) {
1309 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1310 "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()");
1311 throw new PersistenceException("Query failed trying to get PDPs in group");
1313 if (!pdpsInGroupList.isEmpty()) {
1314 if (moveToGroup != null) {
1315 Query checkMoveToGroupQuery = session
1316 .createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted");
1317 checkMoveToGroupQuery.setParameter(PolicyDBDao.GROUP_ID, moveToGroup.getId());
1318 checkMoveToGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1319 List<?> checkMoveToGroupList;
1321 checkMoveToGroupList = checkMoveToGroupQuery.list();
1322 } catch (Exception e) {
1323 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1324 "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList");
1325 throw new PersistenceException("Query failed trying to check if group exists");
1327 if (checkMoveToGroupList.isEmpty()) {
1328 PolicyLogger.error(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId());
1329 throw new PersistenceException(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId());
1330 } else if (checkMoveToGroupList.size() > 1) {
1332 PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1333 throw new PersistenceException(
1334 PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1336 GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0);
1337 for (Object pdpObject : pdpsInGroupList) {
1338 PdpEntity pdp = (PdpEntity) pdpObject;
1339 pdp.setGroup(newGroup);
1340 if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) {
1341 pdp.setModifiedBy(username);
1345 this.newGroupId = newGroup.getGroupId();
1346 } catch (PersistenceException e) {
1347 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1348 "Caught PersistenceException trying to set pdp group to null on em.flush()");
1349 throw new PersistenceException("Query failed trying to set pdp group to ");
1354 PolicyLogger.error("Group " + group.getId()
1355 + " is trying to be delted with PDPs. No group was provided to move them to");
1356 throw new PolicyDBException("Group has PDPs. Must provide a group for them to move to");
1360 // delete group here
1361 GroupEntity groupToDelete = (GroupEntity) deleteGroupQueryList.get(0);
1362 groupToDelete.setDeleted(true);
1363 if (!PolicyDBDao.stringEquals(groupToDelete.getModifiedBy(), username)) {
1364 groupToDelete.setModifiedBy(username);
1367 this.groupId = groupToDelete.getGroupKey();
1372 public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, String username)
1373 throws PolicyDBException {
1375 "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup("
1376 + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + ") called");
1377 if (PolicyDBDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) {
1378 throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty");
1380 synchronized (emLock) {
1381 checkBeforeOperationRun();
1382 // check if group exists
1383 Query groupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1384 groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar);
1385 groupQuery.setParameter(PolicyDBDao.DELETED, false);
1386 List<?> groupQueryList;
1388 groupQueryList = groupQuery.list();
1389 } catch (Exception e) {
1390 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1391 "Caught Exception trying to check if group exists groupQuery.getResultList()");
1392 throw new PersistenceException("Query failed trying to check if group " + groupIdVar + " exists");
1394 if (groupQueryList.isEmpty()) {
1395 PolicyLogger.error("Group policy is being added to does not exist with id " + groupIdVar);
1396 throw new PersistenceException("Group policy is being added to does not exist with id " + groupIdVar);
1397 } else if (groupQueryList.size() > 1) {
1398 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1399 throw new PersistenceException(
1400 PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1403 // we need to convert the form of the policy id that is used groups
1404 // into the form that is used
1405 // for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml)
1406 PolicyDBDao policyDbDao = new PolicyDBDao();
1407 String[] policyNameScopeAndVersion = policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar);
1408 if (policyNameScopeAndVersion == null) {
1409 throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version");
1411 Query policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName "
1412 + "AND p.scope=:scope AND p.deleted=:deleted");
1413 policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]);
1414 policyQuery.setParameter(PolicyDBDao.SCOPE, policyNameScopeAndVersion[1]);
1415 policyQuery.setParameter(PolicyDBDao.DELETED, false);
1416 List<?> policyQueryList;
1418 policyQueryList = policyQuery.list();
1419 } catch (Exception e) {
1421 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1422 "Caught Exception trying to check if policy exists policyQuery.getResultList()");
1423 throw new PersistenceException(
1424 "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + " exists");
1426 if (policyQueryList.isEmpty()) {
1427 PolicyLogger.error("Policy being added to the group does not exist with policy id "
1428 + policyNameScopeAndVersion[0]);
1429 throw new PersistenceException("Policy being added to the group does not exist with policy id "
1430 + policyNameScopeAndVersion[0]);
1431 } else if (policyQueryList.size() > 1) {
1433 PolicyDBDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1434 throw new PersistenceException(
1435 PolicyDBDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1437 logger.info("PolicyDBDao: Getting group and policy from database");
1438 GroupEntity group = (GroupEntity) groupQueryList.get(0);
1439 PolicyEntity policy = (PolicyEntity) policyQueryList.get(0);
1440 Iterator<PolicyEntity> policyIt = group.getPolicies().iterator();
1441 String policyName = policyDbDao.getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0];
1443 logger.info("PolicyDBDao: policyName retrieved is " + policyName);
1445 while (policyIt.hasNext()) {
1446 PolicyEntity pol = policyIt.next();
1447 if (policy.getScope().equals(pol.getScope())
1448 && policyDbDao.getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0]
1449 .equals(policyName)) {
1453 } catch (Exception e) {
1455 PolicyLogger.error("Could not delete old versions for policy " + policy.getPolicyName() + ", ID: "
1456 + policy.getPolicyId());
1458 group.addPolicyToGroup(policy);
1461 // After adding policy to the db group we need to make sure the
1462 // filesytem group is in sync with the db group
1464 StdPDPGroup pdpGroup =
1465 (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getGroupId());
1466 return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group);
1467 } catch (PAPException e) {
1469 PolicyLogger.error("PolicyDBDao: Could not synchronize the filesystem group with the database group. "
1476 // this means delete pdp not just remove from group
1478 public void removePdpFromGroup(String pdpId, String username) {
1479 logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpId + "," + username
1481 if (PolicyDBDao.isNullOrEmpty(pdpId, username)) {
1482 throw new IllegalArgumentException("pdpID and username must not be null or empty");
1484 synchronized (emLock) {
1485 checkBeforeOperationRun();
1486 Query pdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1487 pdpQuery.setParameter(PolicyDBDao.PDP_ID, pdpId);
1488 pdpQuery.setParameter(PolicyDBDao.DELETED, false);
1491 pdpList = pdpQuery.list();
1492 } catch (Exception e) {
1493 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1494 "Caught Exception trying to check if pdp exists pdpQuery.getResultList()");
1495 throw new PersistenceException("Query failed trying to check if pdp " + pdpId + " exists");
1497 if (pdpList.size() > 1) {
1498 PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1499 throw new PersistenceException(
1500 "Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1501 } else if (pdpList.isEmpty()) {
1502 PolicyLogger.error("Pdp being removed does not exist with id " + pdpId);
1505 PdpEntity pdp = (PdpEntity) pdpList.get(0);
1510 if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) {
1511 pdp.setModifiedBy(username);
1513 pdp.setDeleted(true);
1516 this.pdpId = pdp.getPdpKey();
1520 private static String evaluateXPath(String expression, String xml) {
1521 InputSource source = new InputSource(new StringReader(xml));
1523 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1524 String description = "";
1526 DocumentBuilder db = dbf.newDocumentBuilder();
1527 Document document = db.parse(source);
1529 XPathFactory xpathFactory = XPathFactory.newInstance();
1530 XPath xpath = xpathFactory.newXPath();
1532 description = xpath.evaluate(expression, document);
1533 } catch (Exception e) {
1534 logger.error("Exception Occured while evaluating path" + e);