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 oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
47 import org.apache.commons.io.FilenameUtils;
48 import org.apache.commons.io.IOUtils;
49 import org.hibernate.Query;
50 import org.hibernate.Session;
51 import org.hibernate.SessionFactory;
52 import org.onap.policy.common.logging.eelf.MessageCodes;
53 import org.onap.policy.common.logging.eelf.PolicyLogger;
54 import org.onap.policy.common.logging.flexlogger.FlexLogger;
55 import org.onap.policy.common.logging.flexlogger.Logger;
56 import org.onap.policy.rest.XACMLRestProperties;
57 import org.onap.policy.rest.adapter.PolicyRestAdapter;
58 import org.onap.policy.rest.dao.PolicyDBException;
59 import org.onap.policy.rest.jpa.ActionBodyEntity;
60 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
61 import org.onap.policy.rest.jpa.GroupEntity;
62 import org.onap.policy.rest.jpa.PdpEntity;
63 import org.onap.policy.rest.jpa.PolicyEntity;
64 import org.onap.policy.xacml.api.pap.OnapPDP;
65 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
66 import org.onap.policy.xacml.std.pap.StdPDPGroup;
67 import org.onap.policy.xacml.util.XACMLPolicyWriter;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.stereotype.Component;
70 import org.w3c.dom.Document;
71 import org.xml.sax.InputSource;
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 private 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
103 .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)),
105 XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)));
108 public PolicyDbDaoTransactionInstance() {
109 // Default Constructor
113 public PolicyDbDaoTransactionInstance(SessionFactory sessionfactory) {
114 PolicyDbDaoTransactionInstance.sessionfactory = sessionfactory;
117 private static SessionFactory sessionfactory;
121 * Instantiates a new policy DB dao transaction instance.
123 * @param transactionTimeout the transaction timeout is how long the transaction can sit before
125 * @param transactionWaitTime the transaction wait time is how long to wait for the transaction
128 public PolicyDbDaoTransactionInstance(int transactionTimeout, int transactionWaitTime) {
130 "\n\nPolicyDBDaoTransactionInstance() as PolicyDBDaoTransactionInstance() called:"
131 + "\n transactionTimeout = " + transactionTimeout
132 + "\n transactionWaitTime = " + transactionWaitTime + "\n\n");
138 synchronized (emLock) {
139 session = sessionfactory.openSession();
141 PolicyDBDao.getPolicyDBDaoInstance().startTransactionSynced(session,
142 transactionWaitTime);
143 } catch (Exception e) {
144 logger.error("Could not lock transaction within " + transactionWaitTime
145 + " milliseconds" + e);
146 throw new PersistenceException("Could not lock transaction within "
147 + transactionWaitTime + " milliseconds");
150 class TransactionTimer implements Runnable {
152 private int sleepTime;
154 public TransactionTimer(int timeout) {
155 this.sleepTime = timeout;
160 if (logger.isDebugEnabled()) {
161 Date date = new java.util.Date();
163 "\n\nTransactionTimer.run() - SLEEPING: " + "\n sleepTime (ms) = "
164 + sleepTime + "\n TimeStamp = " + date.getTime() + "\n\n");
167 Thread.sleep(sleepTime);
168 } catch (InterruptedException e) {
169 // probably, the transaction was completed, the last thing
170 // we want to do is roll back
171 if (logger.isDebugEnabled()) {
172 Date date = new java.util.Date();
173 logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: "
174 + "\n TimeStamp = " + date.getTime() + "\n\n");
176 Thread.currentThread().interrupt();
179 if (logger.isDebugEnabled()) {
180 Date date = new java.util.Date();
181 logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " + "\n TimeStamp = "
182 + date.getTime() + "\n\n");
185 "PolicyDBDaoTransactionInstance - TransactionTimer - Rolling back transaction.");
186 rollbackTransaction();
192 new Thread(new TransactionTimer(transactionTimeout), "transactionTimerThread");
193 transactionTimer.start();
197 private void checkBeforeOperationRun() {
198 checkBeforeOperationRun(false);
201 private void checkBeforeOperationRun(boolean justCheckOpen) {
202 if (!isTransactionOpen()) {
203 PolicyLogger.warn("checkBeforeOperationRun - There is no transaction currently open");
204 throw new IllegalStateException("There is no transaction currently open");
206 if (operationRun && !justCheckOpen) {
207 PolicyLogger.warn("checkBeforeOperationRun - "
208 + "An operation has already been performed and the current transaction should be committed");
209 throw new IllegalStateException(
210 "An operation has already been performed and the current transaction should be committed");
216 public void commitTransaction() {
217 synchronized (emLock) {
218 NotifyOtherPaps otherPaps = new NotifyOtherPaps();
219 logger.debug("commitTransaction() as commitTransaction() called");
220 if (!isTransactionOpen()) {
221 logger.warn("There is no open transaction to commit - PolicyId - " + policyId
222 + ", GroupId - " + groupId);
225 } catch (Exception e) {
226 logger.error("Exception Occured" + e);
231 session.getTransaction().commit();
232 } catch (RollbackException e) {
233 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
234 "Caught RollbackException on em.getTransaction().commit()");
235 throw new PersistenceException("The commit failed. Message:\n" + e.getMessage());
240 if (newGroupId != null) {
242 otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION, newGroupId);
243 } catch (Exception e) {
244 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e,
245 PolicyDBDao.POLICYDBDAO_VAR,
246 "Caught Exception on notifyOthers(" + policyId + ","
247 + POLICY_NOTIFICATION + "," + newGroupId + ")");
251 otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION);
252 } catch (Exception e) {
253 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e,
254 PolicyDBDao.POLICYDBDAO_VAR, "Caught Exception on notifyOthers("
255 + policyId + "," + POLICY_NOTIFICATION + ")");
260 // we don't want commit to fail just because this does
261 if (newGroupId != null) {
263 otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION, newGroupId);
264 } catch (Exception e) {
265 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e,
266 PolicyDBDao.POLICYDBDAO_VAR,
267 "Caught Exception on notifyOthers(" + groupId + ","
268 + GROUP_NOTIFICATION + "," + newGroupId + ")");
272 otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION);
273 } catch (Exception e) {
274 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e,
275 PolicyDBDao.POLICYDBDAO_VAR, "Caught Exception on notifyOthers("
276 + groupId + "," + GROUP_NOTIFICATION + ")");
281 // we don't want commit to fail just because this does
283 otherPaps.notifyOthers(pdpId, PDP_NOTIFICATION);
284 } catch (Exception e) {
285 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
286 "Caught Exception on notifyOthers(" + pdpId + "," + PDP_NOTIFICATION
291 if (transactionTimer != null) {
292 transactionTimer.interrupt();
297 public void rollbackTransaction() {
298 logger.debug("rollbackTransaction() as rollbackTransaction() called");
299 synchronized (emLock) {
300 if (isTransactionOpen()) {
302 session.getTransaction().rollback();
303 } catch (Exception e) {
304 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
305 "Could not rollback transaction");
309 } catch (Exception e) {
310 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
311 "Could not close Hibernate Session.");
317 } catch (Exception e) {
318 logger.warn("Could not close already closed transaction", e);
322 if (transactionTimer != null) {
323 transactionTimer.interrupt();
327 private void createPolicy(PolicyRestAdapter policy, String username, String policyScope,
328 String inputPolicyName, String policyDataString) {
329 String policyName = inputPolicyName;
330 logger.debug("createPolicy(PolicyRestAdapter policy, String username, String policyScope,"
331 + " String policyName, String policyDataString) as createPolicy(" + policy + ", "
332 + username + ", " + policyScope + ", " + policyName + ", " + policyDataString
334 synchronized (emLock) {
335 PolicyDBDao policyDbDao = new PolicyDBDao();
336 checkBeforeOperationRun();
337 String configName = policyName;
338 if (policyName.contains("Config_")) {
339 policyName = policyName.replace(".Config_", ":Config_");
340 } else if (policyName.contains("Action_")) {
341 policyName = policyName.replace(".Action_", ":Action_");
342 } else if (policyName.contains("Decision_MS_")) {
343 policyName = policyName.replace(".Decision_MS_", ":Decision_MS_");
344 } else if (policyName.contains("Decision_")) {
345 policyName = policyName.replace(".Decision_", ":Decision_");
347 policyName = policyName.split(":")[1];
348 Query createPolicyQuery = session.createQuery(
349 "SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
350 createPolicyQuery.setParameter(PolicyDBDao.SCOPE, policyScope);
351 createPolicyQuery.setParameter("policyName", policyName);
352 List<?> createPolicyQueryList = createPolicyQuery.list();
353 PolicyEntity newPolicyEntity;
355 if (createPolicyQueryList.isEmpty()) {
356 newPolicyEntity = new PolicyEntity();
358 } else if (createPolicyQueryList.size() > 1) {
359 PolicyLogger.error("Somehow, more than one policy with the same "
360 + "scope, name, and deleted status were found in the database");
361 throw new PersistenceException("Somehow, more than one policy with the same"
362 + " scope, name, and deleted status were found in the database");
364 newPolicyEntity = (PolicyEntity) createPolicyQueryList.get(0);
368 ActionBodyEntity newActionBodyEntity = null;
369 if (policy.getPolicyType().equals(PolicyDBDao.ACTION)) {
370 boolean abupdate = false;
371 if (newPolicyEntity.getActionBodyEntity() == null) {
372 newActionBodyEntity = new ActionBodyEntity();
374 newActionBodyEntity = (ActionBodyEntity) session.get(ActionBodyEntity.class,
375 newPolicyEntity.getActionBodyEntity().getActionBodyId());
379 if (newActionBodyEntity != null) {
380 // build the file path
381 // trim the .xml off the end
382 String policyNameClean = FilenameUtils.removeExtension(configName);
383 String actionBodyName = policyNameClean + ".json";
385 // get the action body
386 String actionBodyString = policy.getActionBody();
387 if (actionBodyString == null) {
388 actionBodyString = "{}";
390 newActionBodyEntity.setActionBody(actionBodyString);
391 newActionBodyEntity.setActionBodyName(actionBodyName);
392 newActionBodyEntity.setModifiedBy("PolicyDBDao.createPolicy()");
393 newActionBodyEntity.setDeleted(false);
395 newActionBodyEntity.setCreatedBy("PolicyDBDao.createPolicy()");
397 if (logger.isDebugEnabled()) {
398 logger.debug("\nPolicyDBDao.createPolicy"
399 + "\n newActionBodyEntity.getActionBody() = "
400 + newActionBodyEntity.getActionBody()
401 + "\n newActionBodyEntity.getActionBodyName() = "
402 + newActionBodyEntity.getActionBodyName()
403 + "\n newActionBodyEntity.getModifiedBy() = "
404 + newActionBodyEntity.getModifiedBy()
405 + "\n newActionBodyEntity.getCreatedBy() = "
406 + newActionBodyEntity.getCreatedBy()
407 + "\n newActionBodyEntity.isDeleted() = "
408 + newActionBodyEntity.isDeleted() + "\n FLUSHING to DB");
410 // push the actionBodyEntity to the DB
412 newActionBodyEntity.prePersist();
415 session.persist(newActionBodyEntity);
418 // newActionBodyEntity == null
419 // We have a actionBody in the policy but we found no
420 // actionBody in the DB
421 String msg = "\n\nPolicyDBDao.createPolicy - Incoming Action policy had an "
422 + "actionBody, but it could not be found in the DB for update."
423 + "\n policyScope = " + policyScope + "\n policyName = " + policyName
426 "PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, "
427 + "but it could not be found in the DB for update: policyName = "
429 throw new IllegalArgumentException(msg);
433 ConfigurationDataEntity newConfigurationDataEntity;
434 if (PolicyDBDao.CONFIG.equals(policy.getPolicyType())
435 || DECISIONMS_MODEL.equals(policy.getRuleProvider())) {
436 boolean configUpdate;
437 if (newPolicyEntity.getConfigurationData() == null) {
438 newConfigurationDataEntity = new ConfigurationDataEntity();
439 configUpdate = false;
441 newConfigurationDataEntity = (ConfigurationDataEntity) session.get(
442 ConfigurationDataEntity.class,
443 newPolicyEntity.getConfigurationData().getConfigurationDataId());
447 if (newConfigurationDataEntity != null) {
448 if (!PolicyDBDao.stringEquals(newConfigurationDataEntity.getConfigurationName(),
449 policyDbDao.getConfigFile(configName, policy))) {
450 newConfigurationDataEntity.setConfigurationName(
451 policyDbDao.getConfigFile(configName, policy));
453 if (newConfigurationDataEntity.getConfigType() == null
454 || !newConfigurationDataEntity.getConfigType()
455 .equals(policy.getConfigType())) {
456 newConfigurationDataEntity.setConfigType(policy.getConfigType());
459 newConfigurationDataEntity.setCreatedBy(username);
461 if (newConfigurationDataEntity.getModifiedBy() == null
462 || !newConfigurationDataEntity.getModifiedBy().equals(username)) {
463 newConfigurationDataEntity.setModifiedBy(username);
465 if (newConfigurationDataEntity.getDescription() == null
466 || !newConfigurationDataEntity.getDescription().equals("")) {
467 newConfigurationDataEntity.setDescription("");
469 if (newConfigurationDataEntity.getConfigBody() == null
470 || newConfigurationDataEntity.getConfigBody().isEmpty()
471 || (!newConfigurationDataEntity.getConfigBody()
472 .equals(policy.getConfigBodyData()))) {
473 // hopefully one of these won't be null
474 if (policy.getConfigBodyData() == null
475 || policy.getConfigBodyData().isEmpty()) {
476 newConfigurationDataEntity.setConfigBody(policy.getJsonBody());
478 newConfigurationDataEntity.setConfigBody(policy.getConfigBodyData());
481 if (newConfigurationDataEntity.isDeleted()) {
482 newConfigurationDataEntity.setDeleted(false);
485 newConfigurationDataEntity.prePersist();
488 session.persist(newConfigurationDataEntity);
491 // We have a configurationData body in the policy but we
492 // found no configurationData body in the DB
493 String msg = "\n\nPolicyDBDao.createPolicy - Incoming Config policy had a "
494 + "configurationData body, but it could not be found in the DB for update."
495 + "\n policyScope = " + policyScope + "\n policyName = " + policyName
498 "PolicyDBDao.createPolicy - Incoming Config policy had a configurationData body, "
499 + "but it could not be found in the DB for update: policyName = "
501 throw new IllegalArgumentException(msg);
505 newConfigurationDataEntity = null;
507 policyId = newPolicyEntity.getPolicyId();
509 if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) {
510 newPolicyEntity.setPolicyName(policyName);
512 if (!PolicyDBDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) {
513 newPolicyEntity.setCreatedBy(username);
515 if (!PolicyDBDao.stringEquals(newPolicyEntity.getDescription(),
516 policy.getPolicyDescription())) {
517 newPolicyEntity.setDescription(policy.getPolicyDescription());
519 if (!PolicyDBDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) {
520 newPolicyEntity.setModifiedBy(username);
522 if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) {
523 newPolicyEntity.setPolicyData(policyDataString);
525 if (!PolicyDBDao.stringEquals(newPolicyEntity.getScope(), policyScope)) {
526 newPolicyEntity.setScope(policyScope);
528 if (newPolicyEntity.isDeleted()) {
529 newPolicyEntity.setDeleted(false);
531 newPolicyEntity.setConfigurationData(newConfigurationDataEntity);
532 newPolicyEntity.setActionBodyEntity(newActionBodyEntity);
534 newPolicyEntity.prePersist();
537 session.persist(newPolicyEntity);
540 this.policyId = newPolicyEntity.getPolicyId();
546 public void createPolicy(Policy policy, String username) {
547 InputStream policyXmlStream = null;
549 logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy("
550 + policy + "," + username + ") called");
551 String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, ".");
552 // Does not need to be XACMLPolicyWriterWithPapNotify since it is
553 // already in the PAP
554 // and this transaction is intercepted up stream.
555 String policyDataString;
558 if (policy.policyAdapter.getData() instanceof PolicySetType) {
559 policyXmlStream = XACMLPolicyWriter.getPolicySetXmlAsInputStream(
560 (PolicySetType) policy.getCorrectPolicyDataObject());
562 policyXmlStream = XACMLPolicyWriter
563 .getXmlAsInputStream(policy.getCorrectPolicyDataObject());
565 policyDataString = IOUtils.toString(policyXmlStream);
566 } catch (IOException e) {
567 policyDataString = "could not read";
568 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
569 "Caught IOException on IOUtils.toString(" + policyXmlStream + ")");
570 throw new IllegalArgumentException(
571 "Cannot parse the policy xml from the PolicyRestAdapter.");
574 IOUtils.closeQuietly(policyXmlStream);
575 if (PolicyDBDao.isJunit()) {
576 // Using parentPath object to set policy data.
577 policyDataString = policy.policyAdapter.getParentPath();
579 String configPath = "";
580 if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
581 configPath = evaluateXPath(
582 "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
584 } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
585 configPath = evaluateXPath(
586 "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, "
587 + policy.policyAdapter.getActionAttribute()
588 + ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()",
590 } else if (DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
591 configPath = evaluateXPath(
592 "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
596 String prefix = null;
597 if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())
598 || DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
599 prefix = configPath.substring(
600 configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(),
601 configPath.lastIndexOf(policy.policyAdapter.getPolicyName()));
602 if (PolicyDBDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) {
603 String configData = "";
605 String newConfigPath = configPath;
607 newConfigPath = processConfigPath(newConfigPath);
608 } catch (Exception e2) {
609 logger.error("Could not process config path: " + newConfigPath, e2);
611 configData = readConfigFile(newConfigPath);
612 } catch (Exception e) {
613 logger.error("Could not read config body data for " + configPath, e);
615 policy.policyAdapter.setConfigBodyData(configData);
617 } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
619 } else if ("Decision".equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
620 prefix = "Decision_";
623 if (!(policy.policyAdapter.getData() instanceof PolicyType)
624 && !(policy.policyAdapter.getData() instanceof PolicySetType)) {
625 PolicyLogger.error("The data field is not an instance of PolicyType");
626 throw new IllegalArgumentException(
627 "The data field is not an instance of PolicyType");
629 String finalName = policyScope + "." + prefix + policy.policyAdapter.getPolicyName()
630 + "." + policy.policyAdapter.getHighestVersion() + ".xml";
631 if (policy.policyAdapter.getConfigType() == null
632 || "".equals(policy.policyAdapter.getConfigType())) {
633 // get the config file extension
635 if (configPath != null && !"".equalsIgnoreCase(configPath)) {
636 ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());;
639 if (ext.contains("txt")) {
640 policy.policyAdapter.setConfigType(PolicyDBDao.OTHER_CONFIG);
641 } else if (ext.contains("json")) {
642 policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG);
643 } else if (ext.contains("xml")) {
644 policy.policyAdapter.setConfigType(PolicyDBDao.XML_CONFIG);
645 } else if (ext.contains("properties")) {
646 policy.policyAdapter.setConfigType(PolicyDBDao.PROPERTIES_CONFIG);
648 if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDBDao.ACTION)) {
649 policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG);
654 createPolicy(policy.policyAdapter, username, policyScope, finalName, policyDataString);
656 if (policyXmlStream != null) {
658 policyXmlStream.close();
659 } catch (IOException e) {
660 logger.error("Exception Occured while closing input stream" + e);
667 public PolicyEntity getPolicy(int policyId) {
668 return getPolicy(policyId, null, null);
671 public PolicyEntity getPolicy(String policyName, String scope) {
672 return getPolicy(-1, policyName, scope);
675 private PolicyEntity getPolicy(int policyIdVar, String policyName, String scope) {
676 logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar
677 + "," + policyName + ") called");
678 if (policyIdVar < 0 && PolicyDBDao.isNullOrEmpty(policyName, scope)) {
679 throw new IllegalArgumentException(
680 "policyID must be at least 0 or policyName must be not null or blank");
683 synchronized (emLock) {
684 checkBeforeOperationRun(true);
685 // check if group exists
688 if (!PolicyDBDao.isNullOrEmpty(policyName, scope)) {
689 policyId = policyName;
690 policyQuery = session.createQuery(
691 "SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope");
692 policyQuery.setParameter("name", policyId);
693 policyQuery.setParameter("scope", scope);
695 policyId = String.valueOf(policyIdVar);
696 policyQuery = session.getNamedQuery("PolicyEntity.FindById");
697 policyQuery.setParameter("id", policyId);
699 List<?> policyQueryList;
701 policyQueryList = policyQuery.list();
702 } catch (Exception e) {
703 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
704 "Caught Exception trying to get policy with policyQuery.getResultList()");
705 throw new PersistenceException("Query failed trying to get policy " + policyId);
708 if (policyQueryList.isEmpty()) {
709 PolicyLogger.error("Policy does not exist with id " + policyId);
710 throw new PersistenceException(
711 "Group policy is being added to does not exist with id " + policyId);
712 } else if (policyQueryList.size() > 1) {
713 PolicyLogger.error(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB);
714 throw new PersistenceException(
715 PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB);
717 return (PolicyEntity) policyQueryList.get(0);
722 public GroupEntity getGroup(long groupKey) {
723 logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + ") called");
725 throw new IllegalArgumentException("groupKey must be at least 0");
727 synchronized (emLock) {
728 checkBeforeOperationRun(true);
729 // check if group exists
731 session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey");
732 groupQuery.setParameter("groupKey", groupKey);
733 List<?> groupQueryList;
735 groupQueryList = groupQuery.list();
736 } catch (Exception e) {
737 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
738 "Caught Exception trying to get group with groupQuery.getResultList()");
739 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupKey);
741 if (groupQueryList.isEmpty()) {
742 PolicyLogger.error("Group does not exist with groupKey " + groupKey);
743 throw new PersistenceException("Group does not exist with groupKey " + groupKey);
744 } else if (groupQueryList.size() > 1) {
745 PolicyLogger.error("Somehow, more than one group with the groupKey " + groupKey
746 + PolicyDBDao.FOUND_IN_DB);
747 throw new PersistenceException("Somehow, more than one group with the groupKey "
748 + groupKey + PolicyDBDao.FOUND_IN_DB);
750 return (GroupEntity) groupQueryList.get(0);
755 public GroupEntity getGroup(String groupId) {
756 logger.debug("getGroup(String groupId) as getGroup(" + groupId + ") called");
757 if (PolicyDBDao.isNullOrEmpty(groupId)) {
758 throw new IllegalArgumentException("groupId must not be null or empty");
760 synchronized (emLock) {
761 checkBeforeOperationRun(true);
762 // check if group exists
764 session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId");
765 groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId);
766 List<?> groupQueryList;
768 groupQueryList = groupQuery.list();
769 } catch (Exception e) {
770 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
771 "Caught Exception trying to get group with groupQuery.getResultList()");
772 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupId);
774 if (groupQueryList.isEmpty()) {
775 PolicyLogger.error("Group does not exist with id " + groupId);
776 throw new PersistenceException("Group does not exist with id " + groupId);
777 } else if (groupQueryList.size() > 1) {
779 .error(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB);
780 throw new PersistenceException(
781 PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB);
783 return (GroupEntity) groupQueryList.get(0);
788 public List<?> getPdpsInGroup(long groupKey) {
789 logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + ") called");
791 throw new IllegalArgumentException("groupId must not be < 0");
793 synchronized (emLock) {
794 checkBeforeOperationRun(true);
796 session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group");
797 pdpsQuery.setParameter("group", getGroup(groupKey));
798 return pdpsQuery.list();
803 public PdpEntity getPdp(long pdpKey) {
804 logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + ") called");
806 throw new IllegalArgumentException("pdpKey must be at least 0");
808 synchronized (emLock) {
809 checkBeforeOperationRun(true);
810 // check if group exists
812 session.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey");
813 pdpQuery.setParameter("pdpKey", pdpKey);
814 List<?> pdpQueryList;
816 pdpQueryList = pdpQuery.list();
817 } catch (Exception e) {
818 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
819 "Caught Exception trying to get pdp with pdpQuery.getResultList()");
820 throw new PersistenceException("Query failed trying to get pdp " + pdpKey);
822 if (pdpQueryList.isEmpty()) {
823 PolicyLogger.error("Pdp does not exist with pdpKey " + pdpKey);
824 throw new PersistenceException("Pdp does not exist with pdpKey " + pdpKey);
825 } else if (pdpQueryList.size() > 1) {
826 PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey
827 + PolicyDBDao.FOUND_IN_DB);
828 throw new PersistenceException("Somehow, more than one pdp with the pdpKey "
829 + pdpKey + PolicyDBDao.FOUND_IN_DB);
831 return (PdpEntity) pdpQueryList.get(0);
836 public boolean isTransactionOpen() {
837 logger.debug("isTransactionOpen() as isTransactionOpen() called");
838 synchronized (emLock) {
839 return session.isOpen() && session.getTransaction().isActive();
843 private String processConfigPath(String inputConfigPath) {
844 String configPath = inputConfigPath;
845 String webappsPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS);
846 if (webappsPath == null) {
847 logger.error("Webapps property does not exist");
848 throw new IllegalArgumentException("Webapps property does not exist");
850 configPath = configPath.replace("$URL", webappsPath);
851 // make sure the correct slashes are in
853 configPath = Paths.get(configPath).toString();
854 } catch (InvalidPathException e) {
855 logger.error("Invalid config path: " + configPath, e);
856 throw new IllegalArgumentException("Invalid config path: " + configPath);
861 private String readConfigFile(String configPath) {
862 String configDataString = null;
863 InputStream configContentStream = null;
865 configContentStream = new FileInputStream(configPath);
866 configDataString = IOUtils.toString(configContentStream);
867 } catch (FileNotFoundException e) {
868 logger.error("Caught FileNotFoundException on new FileInputStream(" + configPath + ")",
870 throw new IllegalArgumentException("The config file path does not exist");
871 } catch (IOException e2) {
872 logger.error("Caught IOException on newIOUtils.toString(" + configContentStream + ")",
874 throw new IllegalArgumentException("The config file path cannot be read");
876 IOUtils.closeQuietly(configContentStream);
878 if (configDataString == null) {
879 throw new IllegalArgumentException("The config file path cannot be read");
881 return configDataString;
886 public void close() {
887 synchronized (emLock) {
888 if (session.isOpen()) {
889 if (session.getTransaction().isActive()) {
890 session.getTransaction().rollback();
894 if (transactionTimer != null) {
895 transactionTimer.interrupt();
901 public void createGroup(String groupId, String groupName, String inputGroupDescription,
903 String groupDescription = inputGroupDescription;
904 logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", "
905 + groupName + ", " + groupDescription + ") called");
906 if (PolicyDBDao.isNullOrEmpty(groupId, groupName, username)) {
907 throw new IllegalArgumentException(
908 "groupId, groupName, and username must not be null or empty");
910 if (groupDescription == null) {
911 groupDescription = "";
914 synchronized (emLock) {
915 checkBeforeOperationRun();
916 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
917 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId);
918 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
919 List<?> checkGroupQueryList;
921 checkGroupQueryList = checkGroupQuery.list();
922 } catch (Exception e) {
923 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
924 "Caught Exception on checkGroupQuery.getResultList()");
925 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
927 if (!checkGroupQueryList.isEmpty()) {
928 PolicyLogger.error("The group being added already exists with id " + groupId);
929 throw new PersistenceException(
930 "The group being added already exists with id " + groupId);
932 GroupEntity newGroup = new GroupEntity();
933 newGroup.setCreatedBy(username);
934 newGroup.setModifiedBy(username);
935 newGroup.setGroupName(groupName);
936 newGroup.setGroupId(groupId);
937 newGroup.setDescription(groupDescription);
939 newGroup.prePersist();
941 session.persist(newGroup);
943 this.groupId = newGroup.getGroupKey();
948 public void updateGroup(OnapPDPGroup group, String requestType, String username) {
949 logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + ","
950 + requestType + "," + username + ") called");
952 throw new IllegalArgumentException("PDPGroup group must not be null");
954 if (PolicyDBDao.isNullOrEmpty(group.getId(), requestType)) {
955 throw new IllegalArgumentException(
956 "group.getId() and username must not be null or empty");
959 synchronized (emLock) {
960 PolicyDBDao policyDbDaoVar = new PolicyDBDao();
961 checkBeforeOperationRun();
962 Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
963 getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
964 getGroupQuery.setParameter(PolicyDBDao.DELETED, false);
965 List<?> getGroupQueryList;
967 getGroupQueryList = getGroupQuery.list();
968 } catch (Exception e) {
969 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
970 "Caught Exception on getGroupQuery.getResultList()");
971 throw new PersistenceException(
972 PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing");
974 if (getGroupQueryList.isEmpty()) {
975 PolicyLogger.error("The group cannot be found to update with id " + group.getId());
976 throw new PersistenceException(
977 "The group cannot be found to update with id " + group.getId());
978 } else if (getGroupQueryList.size() > 1) {
979 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId()
980 + PolicyDBDao.DELETED_STATUS_FOUND);
981 throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + group.getId()
982 + PolicyDBDao.DELETED_STATUS_FOUND);
984 GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0);
985 if (!PolicyDBDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) {
986 groupToUpdateInDb.setModifiedBy(requestType);
988 if (group.getDescription() != null && !PolicyDBDao.stringEquals(group.getDescription(),
989 groupToUpdateInDb.getDescription())) {
990 groupToUpdateInDb.setDescription(group.getDescription());
992 // let's find out what policies have been deleted
993 StdPDPGroup oldGroup = null;
995 oldGroup = (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine()
996 .getGroup(group.getId());
997 } catch (PAPException e1) {
998 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR,
999 "We cannot get the group from the papEngine to delete policies");
1001 if (oldGroup == null) {
1002 PolicyLogger.error("We cannot get the group from the papEngine to delete policies");
1004 Set<String> newPolicySet = new HashSet<>(group.getPolicies().size());
1005 // a multiple of n runtime is faster than n^2, so I am using a
1006 // hashset to do the comparison
1007 for (PDPPolicy pol : group.getPolicies()) {
1008 newPolicySet.add(pol.getId());
1010 for (PDPPolicy pol : oldGroup.getPolicies()) {
1011 // should be fast since getPolicies uses a HashSet in
1013 if (!newPolicySet.contains(pol.getId())) {
1014 String[] scopeAndName =
1015 policyDbDaoVar.getNameScopeAndVersionFromPdpPolicy(pol.getId());
1016 PolicyEntity policyToDelete = null;
1018 if (scopeAndName != null) {
1019 policyToDelete = getPolicy(scopeAndName[0], scopeAndName[1]);
1020 if ("XACMLPapServlet.doDelete".equals(requestType)) {
1021 Iterator<PolicyEntity> dbPolicyIt =
1022 groupToUpdateInDb.getPolicies().iterator();
1023 String policyName = policyDbDaoVar
1024 .getPolicyNameAndVersionFromPolicyFileName(
1025 policyToDelete.getPolicyName())[0];
1027 logger.info("PolicyDBDao: delete policy from GroupEntity");
1029 while (dbPolicyIt.hasNext()) {
1030 PolicyEntity dbpolicy = dbPolicyIt.next();
1031 if (policyToDelete.getScope()
1032 .equals(dbpolicy.getScope())
1034 .getPolicyNameAndVersionFromPolicyFileName(
1035 dbpolicy.getPolicyName())[0]
1036 .equals(policyName)) {
1037 dbPolicyIt.remove();
1039 "PolicyDBDao: deleting policy from the existing group:\n "
1041 + policyToDelete.getScope() + "."
1042 + policyToDelete.getPolicyName()
1043 + "\n" + "group is "
1044 + groupToUpdateInDb.getGroupId());
1047 } catch (Exception e) {
1049 PolicyLogger.error("Could not delete policy with name: "
1050 + policyToDelete.getScope() + "."
1051 + policyToDelete.getPolicyName() + "\n ID: "
1052 + policyToDelete.getPolicyId());
1056 } catch (Exception e) {
1057 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e,
1058 PolicyDBDao.POLICYDBDAO_VAR,
1059 "Could not get policy to remove: " + pol.getId());
1060 throw new PersistenceException(
1061 "Could not get policy to remove: " + pol.getId());
1067 if (group.getName() != null && !PolicyDBDao.stringEquals(group.getName(),
1068 groupToUpdateInDb.getgroupName())) {
1069 // we need to check if the new id exists in the database
1070 String newGrpId = PolicyDBDao.createNewPDPGroupId(group.getName());
1071 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1072 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, newGrpId);
1073 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1074 List<?> checkGroupQueryList;
1076 checkGroupQueryList = checkGroupQuery.list();
1077 } catch (Exception e) {
1078 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1079 "Caught Exception on checkGroupQuery.getResultList()");
1080 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
1082 if (!checkGroupQueryList.isEmpty()) {
1083 PolicyLogger.error("The new group name already exists, group id " + newGrpId);
1084 throw new PersistenceException(
1085 "The new group name already exists, group id " + newGrpId);
1087 groupToUpdateInDb.setGroupId(newGrpId);
1088 groupToUpdateInDb.setGroupName(group.getName());
1089 this.newGroupId = group.getId();
1092 this.groupId = groupToUpdateInDb.getGroupKey();
1097 public void addPdpToGroup(String pdpId, String groupIdVar, String pdpName,
1098 String pdpDescription, int pdpJmxPort, String username) {
1099 logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, "
1100 + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup("
1101 + pdpId + ", " + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", "
1102 + pdpJmxPort + ", " + username + ") called");
1103 if (PolicyDBDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) {
1104 throw new IllegalArgumentException(
1105 "pdpID, groupID, pdpName, and username must not be null or empty");
1107 synchronized (emLock) {
1108 checkBeforeOperationRun();
1109 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1110 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar);
1111 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1112 List<?> checkGroupQueryList;
1114 checkGroupQueryList = checkGroupQuery.list();
1115 } catch (Exception e) {
1116 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1117 "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()");
1118 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
1120 if (checkGroupQueryList.size() != 1) {
1121 PolicyLogger.error("The group does not exist");
1122 throw new PersistenceException("The group does not exist");
1124 Query checkDuplicateQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1125 checkDuplicateQuery.setParameter(PolicyDBDao.PDP_ID, pdpId);
1126 checkDuplicateQuery.setParameter(PolicyDBDao.DELETED, false);
1127 List<?> checkDuplicateList;
1129 checkDuplicateList = checkDuplicateQuery.list();
1130 } catch (Exception e) {
1131 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1132 "Caught Exception trying to check for duplicate PDP " + pdpId
1133 + " on checkDuplicateQuery.getResultList()");
1134 throw new PersistenceException(
1135 "Query failed trying to check for duplicate PDP " + pdpId);
1138 if (!checkDuplicateList.isEmpty()) {
1139 logger.warn("PDP already exists with id " + pdpId);
1140 newPdp = (PdpEntity) checkDuplicateList.get(0);
1142 newPdp = new PdpEntity();
1145 newPdp.setCreatedBy(username);
1146 newPdp.setDeleted(false);
1147 newPdp.setDescription(pdpDescription);
1148 newPdp.setGroup((GroupEntity) checkGroupQueryList.get(0));
1149 newPdp.setJmxPort(pdpJmxPort);
1150 newPdp.setModifiedBy(username);
1151 newPdp.setPdpId(pdpId);
1152 newPdp.setPdpName(pdpName);
1154 newPdp.prePersist();
1156 session.persist(newPdp);
1158 this.pdpId = newPdp.getPdpKey();
1163 public void updatePdp(OnapPDP pdp, String username) {
1164 logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username
1167 throw new IllegalArgumentException("PDP pdp must not be null");
1169 if (PolicyDBDao.isNullOrEmpty(pdp.getId(), username)) {
1170 throw new IllegalArgumentException(
1171 "pdp.getId() and username must not be null or empty");
1174 synchronized (emLock) {
1175 checkBeforeOperationRun();
1176 Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1177 getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId());
1178 getPdpQuery.setParameter(PolicyDBDao.DELETED, false);
1179 List<?> getPdpQueryList;
1181 getPdpQueryList = getPdpQuery.list();
1182 } catch (Exception e) {
1183 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1184 "Caught Exception on getPdpQuery.getResultList()");
1185 throw new PersistenceException("Query failed trying to get PDP " + pdp.getId());
1187 if (getPdpQueryList.isEmpty()) {
1188 PolicyLogger.error("The pdp cannot be found to update with id " + pdp.getId());
1189 throw new PersistenceException(
1190 "The pdp cannot be found to update with id " + pdp.getId());
1191 } else if (getPdpQueryList.size() > 1) {
1192 PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId()
1193 + PolicyDBDao.DELETED_STATUS_FOUND);
1194 throw new PersistenceException(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId()
1195 + PolicyDBDao.DELETED_STATUS_FOUND);
1197 PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1198 if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1199 pdpToUpdate.setModifiedBy(username);
1201 if (pdp.getDescription() != null && !PolicyDBDao.stringEquals(pdp.getDescription(),
1202 pdpToUpdate.getDescription())) {
1203 pdpToUpdate.setDescription(pdp.getDescription());
1205 if (pdp.getName() != null
1206 && !PolicyDBDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) {
1207 pdpToUpdate.setPdpName(pdp.getName());
1209 if (pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())) {
1210 pdpToUpdate.setJmxPort(pdp.getJmxPort());
1214 this.pdpId = pdpToUpdate.getPdpKey();
1219 public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) {
1220 logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + ","
1221 + group + "," + username + ") called");
1222 if (pdp == null || group == null) {
1223 throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null");
1225 if (PolicyDBDao.isNullOrEmpty(username, pdp.getId(), group.getId())) {
1226 throw new IllegalArgumentException(
1227 "pdp.getId(), group.getId(), and username must not be null or empty");
1230 synchronized (emLock) {
1231 checkBeforeOperationRun();
1232 // check if pdp exists
1233 Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1234 getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId());
1235 getPdpQuery.setParameter(PolicyDBDao.DELETED, false);
1236 List<?> getPdpQueryList;
1238 getPdpQueryList = getPdpQuery.list();
1239 } catch (Exception e) {
1240 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1241 "Caught Exception on getPdpQuery.getResultList()");
1242 throw new PersistenceException(
1243 "Query failed trying to get pdp to move with id " + pdp.getId());
1245 if (getPdpQueryList.isEmpty()) {
1246 PolicyLogger.error("The pdp cannot be found to move with id " + pdp.getId());
1247 throw new PersistenceException(
1248 "The pdp cannot be found to move with id " + pdp.getId());
1249 } else if (getPdpQueryList.size() > 1) {
1250 PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId()
1251 + PolicyDBDao.DELETED_STATUS_FOUND);
1252 throw new PersistenceException(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId()
1253 + PolicyDBDao.DELETED_STATUS_FOUND);
1256 // check if new group exists
1257 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1258 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1259 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1260 List<?> checkGroupQueryList;
1262 checkGroupQueryList = checkGroupQuery.list();
1263 } catch (Exception e) {
1264 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1265 "Caught Exception trying to get group on checkGroupQuery.getResultList()");
1266 throw new PersistenceException(
1267 "Query failed trying to get new group " + group.getId());
1269 if (checkGroupQueryList.size() != 1) {
1270 PolicyLogger.error("The group " + group.getId() + " does not exist");
1271 throw new PersistenceException("The group " + group.getId() + " does not exist");
1273 GroupEntity groupToMoveInto = (GroupEntity) checkGroupQueryList.get(0);
1274 PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1275 pdpToUpdate.setGroup(groupToMoveInto);
1276 if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1277 pdpToUpdate.setModifiedBy(username);
1281 this.pdpId = pdpToUpdate.getPdpKey();
1286 public void changeDefaultGroup(OnapPDPGroup group, String username) {
1287 logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup("
1288 + group + "," + username + ") called");
1289 if (group == null) {
1290 throw new IllegalArgumentException("PDPGroup group must not be null");
1292 if (PolicyDBDao.isNullOrEmpty(group.getId(), username)) {
1293 throw new IllegalArgumentException(
1294 "group.getId() and username must not be null or empty");
1297 synchronized (emLock) {
1298 checkBeforeOperationRun();
1299 Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1300 getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1301 getGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1302 List<?> getGroupQueryList;
1304 getGroupQueryList = getGroupQuery.list();
1305 } catch (Exception e) {
1306 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1307 "Caught Exception on getGroupQuery.getResultList()");
1308 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId());
1310 if (getGroupQueryList.isEmpty()) {
1312 .error("The group cannot be found to set default with id " + group.getId());
1313 throw new PersistenceException(
1314 "The group cannot be found to set default with id " + group.getId());
1315 } else if (getGroupQueryList.size() > 1) {
1316 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId()
1317 + PolicyDBDao.DELETED_STATUS_FOUND);
1318 throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + group.getId()
1319 + PolicyDBDao.DELETED_STATUS_FOUND);
1321 GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0);
1322 newDefaultGroup.setDefaultGroup(true);
1323 if (!PolicyDBDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) {
1324 newDefaultGroup.setModifiedBy(username);
1328 this.groupId = newDefaultGroup.getGroupKey();
1329 Query setAllGroupsNotDefault =
1330 session.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup "
1331 + "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey");
1332 // not going to set modified by for all groups
1333 setAllGroupsNotDefault.setParameter("defaultGroup", false);
1334 setAllGroupsNotDefault.setParameter(PolicyDBDao.DELETED, false);
1335 setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey());
1338 "set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default");
1339 } catch (Exception e) {
1340 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1341 "Caught Exception on setAllGroupsNotDefault.executeUpdate()");
1342 throw new PersistenceException("Could not set all other groups default to false");
1349 public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username)
1350 throws PolicyDBException {
1352 "deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup("
1353 + group + ", " + moveToGroup + "," + username + ") called");
1354 if (group == null) {
1355 throw new IllegalArgumentException("PDPGroup group cannot be null");
1357 if (PolicyDBDao.isNullOrEmpty(username, group.getId())) {
1358 throw new IllegalArgumentException(
1359 "group.getId() and and username must not be null or empty");
1362 if (group.isDefaultGroup()) {
1363 PolicyLogger.error("The default group " + group.getId()
1364 + " was attempted to be deleted. It cannot be.");
1365 throw new PolicyDBException("You cannot delete the default group.");
1367 synchronized (emLock) {
1368 checkBeforeOperationRun();
1369 Query deleteGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1370 deleteGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1371 deleteGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1372 List<?> deleteGroupQueryList;
1374 deleteGroupQueryList = deleteGroupQuery.list();
1375 } catch (Exception e) {
1376 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1377 "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()");
1378 throw new PersistenceException("Query failed trying to check if group exists");
1380 if (deleteGroupQueryList.isEmpty()) {
1381 logger.warn(PolicyDBDao.GROUP_NOT_FOUND + group.getId());
1383 } else if (deleteGroupQueryList.size() > 1) {
1384 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId()
1385 + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1386 throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + group.getId()
1387 + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1390 Query pdpsInGroupQuery = session.createQuery(
1391 "SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted");
1392 pdpsInGroupQuery.setParameter("group", (deleteGroupQueryList.get(0)));
1393 pdpsInGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1394 List<?> pdpsInGroupList;
1396 pdpsInGroupList = pdpsInGroupQuery.list();
1397 } catch (Exception e) {
1398 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1399 "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()");
1400 throw new PersistenceException("Query failed trying to get PDPs in group");
1402 if (!pdpsInGroupList.isEmpty()) {
1403 if (moveToGroup != null) {
1404 Query checkMoveToGroupQuery = session.createQuery(
1405 "SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted");
1406 checkMoveToGroupQuery.setParameter(PolicyDBDao.GROUP_ID, moveToGroup.getId());
1407 checkMoveToGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1408 List<?> checkMoveToGroupList;
1410 checkMoveToGroupList = checkMoveToGroupQuery.list();
1411 } catch (Exception e) {
1412 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e,
1413 PolicyDBDao.POLICYDBDAO_VAR,
1414 "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList");
1415 throw new PersistenceException(
1416 "Query failed trying to check if group exists");
1418 if (checkMoveToGroupList.isEmpty()) {
1419 PolicyLogger.error(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId());
1420 throw new PersistenceException(
1421 PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId());
1422 } else if (checkMoveToGroupList.size() > 1) {
1423 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId()
1424 + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1425 throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID
1426 + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1428 GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0);
1429 for (Object pdpObject : pdpsInGroupList) {
1430 PdpEntity pdp = (PdpEntity) pdpObject;
1431 pdp.setGroup(newGroup);
1432 if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) {
1433 pdp.setModifiedBy(username);
1437 this.newGroupId = newGroup.getGroupId();
1438 } catch (PersistenceException e) {
1439 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e,
1440 PolicyDBDao.POLICYDBDAO_VAR,
1441 "Caught PersistenceException trying to set pdp group to null on em.flush()");
1442 throw new PersistenceException(
1443 "Query failed trying to set pdp group to ");
1448 PolicyLogger.error("Group " + group.getId()
1449 + " is trying to be delted with PDPs. No group was provided to move them to");
1450 throw new PolicyDBException(
1451 "Group has PDPs. Must provide a group for them to move to");
1455 // delete group here
1456 GroupEntity groupToDelete = (GroupEntity) deleteGroupQueryList.get(0);
1457 groupToDelete.setDeleted(true);
1458 if (!PolicyDBDao.stringEquals(groupToDelete.getModifiedBy(), username)) {
1459 groupToDelete.setModifiedBy(username);
1462 this.groupId = groupToDelete.getGroupKey();
1467 public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType,
1468 String username) throws PolicyDBException {
1470 "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup("
1471 + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username
1473 if (PolicyDBDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) {
1474 throw new IllegalArgumentException(
1475 "groupID, policyID, and username must not be null or empty");
1477 synchronized (emLock) {
1478 checkBeforeOperationRun();
1479 // check if group exists
1480 Query groupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1481 groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar);
1482 groupQuery.setParameter(PolicyDBDao.DELETED, false);
1483 List<?> groupQueryList;
1485 groupQueryList = groupQuery.list();
1486 } catch (Exception e) {
1487 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1488 "Caught Exception trying to check if group exists groupQuery.getResultList()");
1489 throw new PersistenceException(
1490 "Query failed trying to check if group " + groupIdVar + " exists");
1492 if (groupQueryList.isEmpty()) {
1494 "Group policy is being added to does not exist with id " + groupIdVar);
1495 throw new PersistenceException(
1496 "Group policy is being added to does not exist with id " + groupIdVar);
1497 } else if (groupQueryList.size() > 1) {
1498 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupIdVar
1499 + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1500 throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + groupIdVar
1501 + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1504 // we need to convert the form of the policy id that is used groups
1505 // into the form that is used
1506 // for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml)
1507 PolicyDBDao policyDbDao = new PolicyDBDao();
1508 String[] policyNameScopeAndVersion =
1509 policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar);
1510 if (policyNameScopeAndVersion == null) {
1511 throw new IllegalArgumentException(
1512 "Invalid input - policyID must contain name, scope and version");
1514 Query policyQuery = session
1515 .createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName "
1516 + "AND p.scope=:scope AND p.deleted=:deleted");
1517 policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]);
1518 policyQuery.setParameter(PolicyDBDao.SCOPE, policyNameScopeAndVersion[1]);
1519 policyQuery.setParameter(PolicyDBDao.DELETED, false);
1520 List<?> policyQueryList;
1522 policyQueryList = policyQuery.list();
1523 } catch (Exception e) {
1525 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1526 "Caught Exception trying to check if policy exists policyQuery.getResultList()");
1527 throw new PersistenceException("Query failed trying to check if policy "
1528 + policyNameScopeAndVersion[0] + " exists");
1530 if (policyQueryList.isEmpty()) {
1531 PolicyLogger.error("Policy being added to the group does not exist with policy id "
1532 + policyNameScopeAndVersion[0]);
1533 throw new PersistenceException(
1534 "Policy being added to the group does not exist with policy id "
1535 + policyNameScopeAndVersion[0]);
1536 } else if (policyQueryList.size() > 1) {
1537 PolicyLogger.error(PolicyDBDao.DUP_POLICYID + policyNameScopeAndVersion[0]
1538 + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1539 throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID
1540 + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1542 logger.info("PolicyDBDao: Getting group and policy from database");
1543 GroupEntity group = (GroupEntity) groupQueryList.get(0);
1544 PolicyEntity policy = (PolicyEntity) policyQueryList.get(0);
1545 Iterator<PolicyEntity> policyIt = group.getPolicies().iterator();
1546 String policyName = policyDbDao
1547 .getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0];
1549 logger.info("PolicyDBDao: policyName retrieved is " + policyName);
1551 while (policyIt.hasNext()) {
1552 PolicyEntity pol = policyIt.next();
1553 if (policy.getScope().equals(pol.getScope()) && policyDbDao
1554 .getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0]
1555 .equals(policyName)) {
1559 } catch (Exception e) {
1561 PolicyLogger.error("Could not delete old versions for policy "
1562 + policy.getPolicyName() + ", ID: " + policy.getPolicyId());
1564 group.addPolicyToGroup(policy);
1567 // After adding policy to the db group we need to make sure the
1568 // filesytem group is in sync with the db group
1570 StdPDPGroup pdpGroup = (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance()
1571 .getPapEngine().getGroup(group.getGroupId());
1572 return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group);
1573 } catch (PAPException e) {
1576 "PolicyDBDao: Could not synchronize the filesystem group with the database group. "
1583 // this means delete pdp not just remove from group
1585 public void removePdpFromGroup(String pdpId, String username) {
1586 logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup("
1587 + pdpId + "," + username + ") called");
1588 if (PolicyDBDao.isNullOrEmpty(pdpId, username)) {
1589 throw new IllegalArgumentException("pdpID and username must not be null or empty");
1591 synchronized (emLock) {
1592 checkBeforeOperationRun();
1593 Query pdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1594 pdpQuery.setParameter(PolicyDBDao.PDP_ID, pdpId);
1595 pdpQuery.setParameter(PolicyDBDao.DELETED, false);
1598 pdpList = pdpQuery.list();
1599 } catch (Exception e) {
1600 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1601 "Caught Exception trying to check if pdp exists pdpQuery.getResultList()");
1602 throw new PersistenceException(
1603 "Query failed trying to check if pdp " + pdpId + " exists");
1605 if (pdpList.size() > 1) {
1606 PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId
1607 + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1608 throw new PersistenceException("Somehow, more than one pdp with the id " + pdpId
1609 + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1610 } else if (pdpList.isEmpty()) {
1611 PolicyLogger.error("Pdp being removed does not exist with id " + pdpId);
1614 PdpEntity pdp = (PdpEntity) pdpList.get(0);
1619 if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) {
1620 pdp.setModifiedBy(username);
1622 pdp.setDeleted(true);
1625 this.pdpId = pdp.getPdpKey();
1629 private static String evaluateXPath(String expression, String xml) {
1630 InputSource source = new InputSource(new StringReader(xml));
1632 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1633 String description = "";
1635 DocumentBuilder db = dbf.newDocumentBuilder();
1636 Document document = db.parse(source);
1638 XPathFactory xpathFactory = XPathFactory.newInstance();
1639 XPath xpath = xpathFactory.newXPath();
1641 description = xpath.evaluate(expression, document);
1642 } catch (Exception e) {
1643 logger.error("Exception Occured while evaluating path" + e);
1648 public static boolean isJunit() {
1652 public static void setJunit(boolean isJunit) {
1653 PolicyDbDaoTransactionInstance.isJunit = isJunit;