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.PolicyAuditlog;
64 import org.onap.policy.rest.jpa.PolicyEntity;
65 import org.onap.policy.xacml.api.pap.OnapPDP;
66 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
67 import org.onap.policy.xacml.std.pap.StdPDPGroup;
68 import org.onap.policy.xacml.util.XACMLPolicyWriter;
69 import org.springframework.beans.factory.annotation.Autowired;
70 import org.springframework.stereotype.Component;
71 import org.w3c.dom.Document;
72 import org.xml.sax.InputSource;
76 public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
78 private static final Logger logger = FlexLogger.getLogger(PolicyDbDaoTransactionInstance.class);
80 private final Object emLock = new Object();
85 private boolean operationRun = false;
86 private Thread transactionTimer;
87 private static final String POLICY_NOTIFICATION = "policy";
88 private static final String PDP_NOTIFICATION = "pdp";
89 private static final String GROUP_NOTIFICATION = "group";
92 private static final String DECISIONMS_MODEL = "MicroService_Model";
93 private static boolean isJunit = false;
97 * Instantiates a new policy DB dao transaction instance.
99 * @param test the test
101 public PolicyDbDaoTransactionInstance(String test) {
102 // call the constructor with arguments
103 this(Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)),
104 Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)));
107 public PolicyDbDaoTransactionInstance() {
108 // Default Constructor
112 public PolicyDbDaoTransactionInstance(SessionFactory sessionfactory) {
113 PolicyDbDaoTransactionInstance.sessionfactory = sessionfactory;
116 private static SessionFactory sessionfactory;
120 * Instantiates a new policy DB dao transaction instance.
122 * @param transactionTimeout the transaction timeout is how long the transaction can sit before rolling back
123 * @param transactionWaitTime the transaction wait time is how long to wait for the transaction to start before
125 public PolicyDbDaoTransactionInstance(int transactionTimeout, int transactionWaitTime) {
126 logger.info("\n\nPolicyDBDaoTransactionInstance() as PolicyDBDaoTransactionInstance() called:"
127 + "\n transactionTimeout = " + transactionTimeout + "\n transactionWaitTime = "
128 + transactionWaitTime + "\n\n");
134 synchronized (emLock) {
135 session = sessionfactory.openSession();
137 PolicyDBDao.getPolicyDBDaoInstance().startTransactionSynced(session, transactionWaitTime);
138 } catch (Exception e) {
139 logger.error("Could not lock transaction within " + transactionWaitTime + " milliseconds" + e);
140 throw new PersistenceException(
141 "Could not lock transaction within " + transactionWaitTime + " milliseconds");
144 class TransactionTimer implements Runnable {
146 private int sleepTime;
148 public TransactionTimer(int timeout) {
149 this.sleepTime = timeout;
154 if (logger.isDebugEnabled()) {
155 Date date = new java.util.Date();
156 logger.debug("\n\nTransactionTimer.run() - SLEEPING: " + "\n sleepTime (ms) = " + sleepTime
157 + "\n TimeStamp = " + date.getTime() + "\n\n");
160 Thread.sleep(sleepTime);
161 } catch (InterruptedException e) {
162 // probably, the transaction was completed, the last thing
163 // we want to do is roll back
164 if (logger.isDebugEnabled()) {
165 Date date = new java.util.Date();
166 logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: " + "\n TimeStamp = "
167 + date.getTime() + "\n\n");
169 Thread.currentThread().interrupt();
172 if (logger.isDebugEnabled()) {
173 Date date = new java.util.Date();
174 logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " + "\n TimeStamp = " + date.getTime()
177 logger.warn("PolicyDBDaoTransactionInstance - TransactionTimer - Rolling back transaction.");
178 rollbackTransaction();
183 transactionTimer = new Thread(new TransactionTimer(transactionTimeout), "transactionTimerThread");
184 transactionTimer.start();
188 private void checkBeforeOperationRun() {
189 checkBeforeOperationRun(false);
192 private void checkBeforeOperationRun(boolean justCheckOpen) {
193 if (!isTransactionOpen()) {
194 PolicyLogger.warn("checkBeforeOperationRun - There is no transaction currently open");
195 throw new IllegalStateException("There is no transaction currently open");
197 if (operationRun && !justCheckOpen) {
198 PolicyLogger.warn("checkBeforeOperationRun - "
199 + "An operation has already been performed and the current transaction should be committed");
200 throw new IllegalStateException(
201 "An operation has already been performed and the current transaction should be committed");
207 public void commitTransaction() {
208 synchronized (emLock) {
209 NotifyOtherPaps otherPaps = new NotifyOtherPaps();
210 logger.debug("commitTransaction() as commitTransaction() called");
211 if (!isTransactionOpen()) {
213 "There is no open transaction to commit - PolicyId - " + policyId + ", GroupId - " + groupId);
216 } catch (Exception e) {
217 logger.error("Exception Occured" + e);
222 session.getTransaction().commit();
223 } catch (RollbackException e) {
224 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
225 "Caught RollbackException on em.getTransaction().commit()");
226 throw new PersistenceException("The commit failed. Message:\n" + e.getMessage());
231 if (newGroupId != null) {
233 otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION, newGroupId);
234 } catch (Exception e) {
235 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
236 "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ","
241 otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION);
242 } catch (Exception e) {
243 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
244 "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ")");
249 // we don't want commit to fail just because this does
250 if (newGroupId != null) {
252 otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION, newGroupId);
253 } catch (Exception e) {
254 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
255 "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ","
260 otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION);
261 } catch (Exception e) {
262 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
263 "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ")");
268 // we don't want commit to fail just because this does
270 otherPaps.notifyOthers(pdpId, PDP_NOTIFICATION);
271 } catch (Exception e) {
272 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
273 "Caught Exception on notifyOthers(" + pdpId + "," + PDP_NOTIFICATION + ")");
277 if (transactionTimer != null) {
278 transactionTimer.interrupt();
283 public void rollbackTransaction() {
284 logger.debug("rollbackTransaction() as rollbackTransaction() called");
285 synchronized (emLock) {
286 if (isTransactionOpen()) {
288 session.getTransaction().rollback();
289 } catch (Exception e) {
290 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
291 "Could not rollback transaction");
295 } catch (Exception e) {
296 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
297 "Could not close Hibernate Session.");
303 } catch (Exception e) {
304 logger.warn("Could not close already closed transaction", e);
308 if (transactionTimer != null) {
309 transactionTimer.interrupt();
313 private void createPolicy(PolicyRestAdapter policy, String username, String policyScope, String inputPolicyName,
314 String policyDataString) {
315 String policyName = inputPolicyName;
316 logger.debug("createPolicy(PolicyRestAdapter policy, String username, String policyScope,"
317 + " String policyName, String policyDataString) as createPolicy(" + policy + ", " + username + ", "
318 + policyScope + ", " + policyName + ", " + policyDataString + ") called");
319 synchronized (emLock) {
320 PolicyDBDao policyDbDao = new PolicyDBDao();
321 checkBeforeOperationRun();
322 String configName = policyName;
323 if (policyName.contains("Config_")) {
324 policyName = policyName.replace(".Config_", ":Config_");
325 } else if (policyName.contains("Action_")) {
326 policyName = policyName.replace(".Action_", ":Action_");
327 } else if (policyName.contains("Decision_MS_")) {
328 policyName = policyName.replace(".Decision_MS_", ":Decision_MS_");
329 } else if (policyName.contains("Decision_")) {
330 policyName = policyName.replace(".Decision_", ":Decision_");
332 policyName = policyName.split(":")[1];
333 Query createPolicyQuery = session
334 .createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
335 createPolicyQuery.setParameter(PolicyDBDao.SCOPE, policyScope);
336 createPolicyQuery.setParameter("policyName", policyName);
337 List<?> createPolicyQueryList = createPolicyQuery.list();
338 PolicyEntity newPolicyEntity;
340 if (createPolicyQueryList.isEmpty()) {
341 newPolicyEntity = new PolicyEntity();
343 } else if (createPolicyQueryList.size() > 1) {
344 PolicyLogger.error("Somehow, more than one policy with the same "
345 + "scope, name, and deleted status were found in the database");
346 throw new PersistenceException("Somehow, more than one policy with the same"
347 + " scope, name, and deleted status were found in the database");
349 newPolicyEntity = (PolicyEntity) createPolicyQueryList.get(0);
353 ActionBodyEntity newActionBodyEntity = null;
354 if (policy.getPolicyType().equals(PolicyDBDao.ACTION)) {
355 boolean abupdate = false;
356 if (newPolicyEntity.getActionBodyEntity() == null) {
357 newActionBodyEntity = new ActionBodyEntity();
359 newActionBodyEntity = (ActionBodyEntity) session.get(ActionBodyEntity.class,
360 newPolicyEntity.getActionBodyEntity().getActionBodyId());
364 if (newActionBodyEntity != null) {
365 // build the file path
366 // trim the .xml off the end
367 String policyNameClean = FilenameUtils.removeExtension(configName);
368 String actionBodyName = policyNameClean + ".json";
370 // get the action body
371 String actionBodyString = policy.getActionBody();
372 if (actionBodyString == null) {
373 actionBodyString = "{}";
375 newActionBodyEntity.setActionBody(actionBodyString);
376 newActionBodyEntity.setActionBodyName(actionBodyName);
377 newActionBodyEntity.setModifiedBy("PolicyDBDao.createPolicy()");
378 newActionBodyEntity.setDeleted(false);
380 newActionBodyEntity.setCreatedBy("PolicyDBDao.createPolicy()");
382 if (logger.isDebugEnabled()) {
383 logger.debug("\nPolicyDBDao.createPolicy" + "\n newActionBodyEntity.getActionBody() = "
384 + newActionBodyEntity.getActionBody()
385 + "\n newActionBodyEntity.getActionBodyName() = "
386 + newActionBodyEntity.getActionBodyName()
387 + "\n newActionBodyEntity.getModifiedBy() = " + newActionBodyEntity.getModifiedBy()
388 + "\n newActionBodyEntity.getCreatedBy() = " + newActionBodyEntity.getCreatedBy()
389 + "\n newActionBodyEntity.isDeleted() = " + newActionBodyEntity.isDeleted()
390 + "\n FLUSHING to DB");
392 // push the actionBodyEntity to the DB
394 newActionBodyEntity.prePersist();
397 session.persist(newActionBodyEntity);
400 // newActionBodyEntity == null
401 // We have a actionBody in the policy but we found no
402 // actionBody in the DB
403 String msg = "\n\nPolicyDBDao.createPolicy - Incoming Action policy had an "
404 + "actionBody, but it could not be found in the DB for update." + "\n policyScope = "
405 + policyScope + "\n policyName = " + policyName + "\n\n";
406 PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, "
407 + "but it could not be found in the DB for update: policyName = " + policyName);
408 throw new IllegalArgumentException(msg);
412 ConfigurationDataEntity newConfigurationDataEntity;
413 if (PolicyDBDao.CONFIG.equals(policy.getPolicyType())
414 || DECISIONMS_MODEL.equals(policy.getRuleProvider())) {
415 boolean configUpdate;
416 if (newPolicyEntity.getConfigurationData() == null) {
417 newConfigurationDataEntity = new ConfigurationDataEntity();
418 configUpdate = false;
420 newConfigurationDataEntity = (ConfigurationDataEntity) session.get(ConfigurationDataEntity.class,
421 newPolicyEntity.getConfigurationData().getConfigurationDataId());
425 if (newConfigurationDataEntity != null) {
426 if (!PolicyDBDao.stringEquals(newConfigurationDataEntity.getConfigurationName(),
427 policyDbDao.getConfigFile(configName, policy))) {
428 newConfigurationDataEntity.setConfigurationName(policyDbDao.getConfigFile(configName, policy));
430 if (newConfigurationDataEntity.getConfigType() == null
431 || !newConfigurationDataEntity.getConfigType().equals(policy.getConfigType())) {
432 newConfigurationDataEntity.setConfigType(policy.getConfigType());
435 newConfigurationDataEntity.setCreatedBy(username);
437 if (newConfigurationDataEntity.getModifiedBy() == null
438 || !newConfigurationDataEntity.getModifiedBy().equals(username)) {
439 newConfigurationDataEntity.setModifiedBy(username);
441 if (newConfigurationDataEntity.getDescription() == null
442 || !newConfigurationDataEntity.getDescription().equals("")) {
443 newConfigurationDataEntity.setDescription("");
445 if (newConfigurationDataEntity.getConfigBody() == null
446 || newConfigurationDataEntity.getConfigBody().isEmpty()
447 || (!newConfigurationDataEntity.getConfigBody().equals(policy.getConfigBodyData()))) {
448 // hopefully one of these won't be null
449 if (policy.getConfigBodyData() == null || policy.getConfigBodyData().isEmpty()) {
450 newConfigurationDataEntity.setConfigBody(policy.getJsonBody());
452 newConfigurationDataEntity.setConfigBody(policy.getConfigBodyData());
455 if (newConfigurationDataEntity.isDeleted()) {
456 newConfigurationDataEntity.setDeleted(false);
459 newConfigurationDataEntity.prePersist();
462 session.persist(newConfigurationDataEntity);
465 // We have a configurationData body in the policy but we
466 // found no configurationData body in the DB
467 String msg = "\n\nPolicyDBDao.createPolicy - Incoming Config policy had a "
468 + "configurationData body, but it could not be found in the DB for update."
469 + "\n policyScope = " + policyScope + "\n policyName = " + policyName + "\n\n";
471 .error("PolicyDBDao.createPolicy - Incoming Config policy had a configurationData body, "
472 + "but it could not be found in the DB for update: policyName = " + policyName);
473 throw new IllegalArgumentException(msg);
477 newConfigurationDataEntity = null;
479 policyId = newPolicyEntity.getPolicyId();
481 if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) {
482 newPolicyEntity.setPolicyName(policyName);
484 if (!PolicyDBDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) {
485 newPolicyEntity.setCreatedBy(username);
487 if (!PolicyDBDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) {
488 newPolicyEntity.setDescription(policy.getPolicyDescription());
490 if (!PolicyDBDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) {
491 newPolicyEntity.setModifiedBy(username);
493 if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) {
494 newPolicyEntity.setPolicyData(policyDataString);
496 if (!PolicyDBDao.stringEquals(newPolicyEntity.getScope(), policyScope)) {
497 newPolicyEntity.setScope(policyScope);
499 if (newPolicyEntity.isDeleted()) {
500 newPolicyEntity.setDeleted(false);
502 newPolicyEntity.setConfigurationData(newConfigurationDataEntity);
503 newPolicyEntity.setActionBodyEntity(newActionBodyEntity);
505 newPolicyEntity.prePersist();
508 session.persist(newPolicyEntity);
511 this.policyId = newPolicyEntity.getPolicyId();
517 public void createPolicy(Policy policy, String username) {
518 InputStream policyXmlStream = null;
520 logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + policy + ","
521 + username + ") called");
522 String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, ".");
523 // Does not need to be XACMLPolicyWriterWithPapNotify since it is
524 // already in the PAP
525 // and this transaction is intercepted up stream.
526 String policyDataString;
529 if (policy.policyAdapter.getData() instanceof PolicySetType) {
530 policyXmlStream = XACMLPolicyWriter
531 .getPolicySetXmlAsInputStream((PolicySetType) policy.getCorrectPolicyDataObject());
533 policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policy.getCorrectPolicyDataObject());
535 policyDataString = IOUtils.toString(policyXmlStream);
536 } catch (IOException e) {
537 policyDataString = "could not read";
538 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
539 "Caught IOException on IOUtils.toString(" + policyXmlStream + ")");
540 throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter.");
543 IOUtils.closeQuietly(policyXmlStream);
544 if (PolicyDBDao.isJunit()) {
545 // Using parentPath object to set policy data.
546 policyDataString = policy.policyAdapter.getParentPath();
548 String configPath = "";
549 if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
550 configPath = evaluateXPath(
551 "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
553 } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
554 configPath = evaluateXPath(
555 "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, "
556 + policy.policyAdapter.getActionAttribute()
557 + ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()",
559 } else if (DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
560 configPath = evaluateXPath(
561 "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
565 String prefix = null;
566 if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())
567 || DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
568 prefix = configPath.substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(),
569 configPath.lastIndexOf(policy.policyAdapter.getPolicyName()));
570 if (PolicyDBDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) {
571 String configData = "";
573 String newConfigPath = configPath;
575 newConfigPath = processConfigPath(newConfigPath);
576 } catch (Exception e2) {
577 logger.error("Could not process config path: " + newConfigPath, e2);
579 configData = readConfigFile(newConfigPath);
580 } catch (Exception e) {
581 logger.error("Could not read config body data for " + configPath, e);
583 policy.policyAdapter.setConfigBodyData(configData);
585 } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
587 } else if ("Decision".equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
588 prefix = "Decision_";
591 if (!(policy.policyAdapter.getData() instanceof PolicyType)
592 && !(policy.policyAdapter.getData() instanceof PolicySetType)) {
593 PolicyLogger.error("The data field is not an instance of PolicyType");
594 throw new IllegalArgumentException("The data field is not an instance of PolicyType");
596 String finalName = policyScope + "." + prefix + policy.policyAdapter.getPolicyName() + "."
597 + policy.policyAdapter.getHighestVersion() + ".xml";
598 if (policy.policyAdapter.getConfigType() == null || "".equals(policy.policyAdapter.getConfigType())) {
599 // get the config file extension
601 if (configPath != null && !"".equalsIgnoreCase(configPath)) {
602 ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());;
605 if (ext.contains("txt")) {
606 policy.policyAdapter.setConfigType(PolicyDBDao.OTHER_CONFIG);
607 } else if (ext.contains("json")) {
608 policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG);
609 } else if (ext.contains("xml")) {
610 policy.policyAdapter.setConfigType(PolicyDBDao.XML_CONFIG);
611 } else if (ext.contains("properties")) {
612 policy.policyAdapter.setConfigType(PolicyDBDao.PROPERTIES_CONFIG);
614 if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDBDao.ACTION)) {
615 policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG);
620 createPolicy(policy.policyAdapter, username, policyScope, finalName, policyDataString);
622 if (policyXmlStream != null) {
624 policyXmlStream.close();
625 } catch (IOException e) {
626 logger.error("Exception Occured while closing input stream" + e);
633 public PolicyEntity getPolicy(int policyId) {
634 return getPolicy(policyId, null, null);
637 public PolicyEntity getPolicy(String policyName, String scope) {
638 return getPolicy(-1, policyName, scope);
641 private PolicyEntity getPolicy(int policyIdVar, String policyName, String scope) {
642 logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar + "," + policyName
644 if (policyIdVar < 0 && PolicyDBDao.isNullOrEmpty(policyName, scope)) {
645 throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank");
648 synchronized (emLock) {
649 checkBeforeOperationRun(true);
650 // check if group exists
653 if (!PolicyDBDao.isNullOrEmpty(policyName, scope)) {
654 policyId = policyName;
656 session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope");
657 policyQuery.setParameter("name", policyId);
658 policyQuery.setParameter("scope", scope);
660 policyId = String.valueOf(policyIdVar);
661 policyQuery = session.getNamedQuery("PolicyEntity.FindById");
662 policyQuery.setParameter("id", policyId);
664 List<?> policyQueryList;
666 policyQueryList = policyQuery.list();
667 } catch (Exception e) {
668 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
669 "Caught Exception trying to get policy with policyQuery.getResultList()");
670 throw new PersistenceException("Query failed trying to get policy " + policyId);
673 if (policyQueryList.isEmpty()) {
674 PolicyLogger.error("Policy does not exist with id " + policyId);
675 throw new PersistenceException("Group policy is being added to does not exist with id " + policyId);
676 } else if (policyQueryList.size() > 1) {
677 PolicyLogger.error(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB);
678 throw new PersistenceException(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB);
680 return (PolicyEntity) policyQueryList.get(0);
685 public GroupEntity getGroup(long groupKey) {
686 logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + ") called");
688 throw new IllegalArgumentException("groupKey must be at least 0");
690 synchronized (emLock) {
691 checkBeforeOperationRun(true);
692 // check if group exists
693 Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey");
694 groupQuery.setParameter("groupKey", groupKey);
695 List<?> groupQueryList;
697 groupQueryList = groupQuery.list();
698 } catch (Exception e) {
699 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
700 "Caught Exception trying to get group with groupQuery.getResultList()");
701 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupKey);
703 if (groupQueryList.isEmpty()) {
704 PolicyLogger.error("Group does not exist with groupKey " + groupKey);
705 throw new PersistenceException("Group does not exist with groupKey " + groupKey);
706 } else if (groupQueryList.size() > 1) {
708 .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB);
709 throw new PersistenceException(
710 "Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB);
712 return (GroupEntity) groupQueryList.get(0);
717 public GroupEntity getGroup(String groupId) {
718 logger.debug("getGroup(String groupId) as getGroup(" + groupId + ") called");
719 if (PolicyDBDao.isNullOrEmpty(groupId)) {
720 throw new IllegalArgumentException("groupId must not be null or empty");
722 synchronized (emLock) {
723 checkBeforeOperationRun(true);
724 // check if group exists
725 Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId");
726 groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId);
727 List<?> groupQueryList;
729 groupQueryList = groupQuery.list();
730 } catch (Exception e) {
731 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
732 "Caught Exception trying to get group with groupQuery.getResultList()");
733 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupId);
735 if (groupQueryList.isEmpty()) {
736 PolicyLogger.error("Group does not exist with id " + groupId);
737 throw new PersistenceException("Group does not exist with id " + groupId);
738 } else if (groupQueryList.size() > 1) {
739 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB);
740 throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB);
742 return (GroupEntity) groupQueryList.get(0);
747 public List<?> getPdpsInGroup(long groupKey) {
748 logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + ") called");
750 throw new IllegalArgumentException("groupId must not be < 0");
752 synchronized (emLock) {
753 checkBeforeOperationRun(true);
754 Query pdpsQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group");
755 pdpsQuery.setParameter("group", getGroup(groupKey));
756 return pdpsQuery.list();
761 public PdpEntity getPdp(long pdpKey) {
762 logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + ") called");
764 throw new IllegalArgumentException("pdpKey must be at least 0");
766 synchronized (emLock) {
767 checkBeforeOperationRun(true);
768 // check if group exists
769 Query pdpQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey");
770 pdpQuery.setParameter("pdpKey", pdpKey);
771 List<?> pdpQueryList;
773 pdpQueryList = pdpQuery.list();
774 } catch (Exception e) {
775 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
776 "Caught Exception trying to get pdp with pdpQuery.getResultList()");
777 throw new PersistenceException("Query failed trying to get pdp " + pdpKey);
779 if (pdpQueryList.isEmpty()) {
780 PolicyLogger.error("Pdp does not exist with pdpKey " + pdpKey);
781 throw new PersistenceException("Pdp does not exist with pdpKey " + pdpKey);
782 } else if (pdpQueryList.size() > 1) {
783 PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB);
784 throw new PersistenceException(
785 "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB);
787 return (PdpEntity) pdpQueryList.get(0);
792 public boolean isTransactionOpen() {
793 logger.debug("isTransactionOpen() as isTransactionOpen() called");
794 synchronized (emLock) {
795 return session.isOpen() && session.getTransaction().isActive();
799 private String processConfigPath(String inputConfigPath) {
800 String configPath = inputConfigPath;
801 String webappsPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS);
802 if (webappsPath == null) {
803 logger.error("Webapps property does not exist");
804 throw new IllegalArgumentException("Webapps property does not exist");
806 configPath = configPath.replace("$URL", webappsPath);
807 // make sure the correct slashes are in
809 configPath = Paths.get(configPath).toString();
810 } catch (InvalidPathException e) {
811 logger.error("Invalid config path: " + configPath, e);
812 throw new IllegalArgumentException("Invalid config path: " + configPath);
817 private String readConfigFile(String configPath) {
818 String configDataString = null;
819 InputStream configContentStream = null;
821 configContentStream = new FileInputStream(configPath);
822 configDataString = IOUtils.toString(configContentStream);
823 } catch (FileNotFoundException e) {
824 logger.error("Caught FileNotFoundException on new FileInputStream(" + configPath + ")", e);
825 throw new IllegalArgumentException("The config file path does not exist");
826 } catch (IOException e2) {
827 logger.error("Caught IOException on newIOUtils.toString(" + configContentStream + ")", e2);
828 throw new IllegalArgumentException("The config file path cannot be read");
830 IOUtils.closeQuietly(configContentStream);
832 if (configDataString == null) {
833 throw new IllegalArgumentException("The config file path cannot be read");
835 return configDataString;
840 public void close() {
841 synchronized (emLock) {
842 if (session.isOpen()) {
843 if (session.getTransaction().isActive()) {
844 session.getTransaction().rollback();
848 if (transactionTimer != null) {
849 transactionTimer.interrupt();
855 public void createGroup(String groupId, String groupName, String inputGroupDescription, String username) {
856 String groupDescription = inputGroupDescription;
857 logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + groupName + ", "
858 + groupDescription + ") called");
859 if (PolicyDBDao.isNullOrEmpty(groupId, groupName, username)) {
860 throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty");
862 if (groupDescription == null) {
863 groupDescription = "";
866 synchronized (emLock) {
867 checkBeforeOperationRun();
868 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
869 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId);
870 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
871 List<?> checkGroupQueryList;
873 checkGroupQueryList = checkGroupQuery.list();
874 } catch (Exception e) {
875 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
876 "Caught Exception on checkGroupQuery.getResultList()");
877 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
879 if (!checkGroupQueryList.isEmpty()) {
880 PolicyLogger.error("The group being added already exists with id " + groupId);
881 throw new PersistenceException("The group being added already exists with id " + groupId);
883 GroupEntity newGroup = new GroupEntity();
884 newGroup.setCreatedBy(username);
885 newGroup.setModifiedBy(username);
886 newGroup.setGroupName(groupName);
887 newGroup.setGroupId(groupId);
888 newGroup.setDescription(groupDescription);
890 newGroup.prePersist();
892 session.persist(newGroup);
894 this.groupId = newGroup.getGroupKey();
899 public void updateGroup(OnapPDPGroup group, String requestType, String username) {
900 logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + "," + requestType + ","
901 + username + ") called");
903 throw new IllegalArgumentException("PDPGroup group must not be null");
905 if (PolicyDBDao.isNullOrEmpty(group.getId(), requestType)) {
906 throw new IllegalArgumentException("group.getId() and username must not be null or empty");
909 synchronized (emLock) {
910 PolicyDBDao policyDbDaoVar = new PolicyDBDao();
911 checkBeforeOperationRun();
912 Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
913 getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
914 getGroupQuery.setParameter(PolicyDBDao.DELETED, false);
915 List<?> getGroupQueryList;
917 getGroupQueryList = getGroupQuery.list();
918 } catch (Exception e) {
919 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
920 "Caught Exception on getGroupQuery.getResultList()");
921 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing");
923 if (getGroupQueryList.isEmpty()) {
924 PolicyLogger.error("The group cannot be found to update with id " + group.getId());
925 throw new PersistenceException("The group cannot be found to update with id " + group.getId());
926 } else if (getGroupQueryList.size() > 1) {
927 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
928 throw new PersistenceException(
929 PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
931 GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0);
932 if (!PolicyDBDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) {
933 groupToUpdateInDb.setModifiedBy(requestType);
935 if (group.getDescription() != null
936 && !PolicyDBDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) {
937 groupToUpdateInDb.setDescription(group.getDescription());
939 // let's find out what policies have been deleted
940 StdPDPGroup oldGroup = null;
942 oldGroup = (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getId());
943 } catch (PAPException e1) {
944 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR,
945 "We cannot get the group from the papEngine to delete policies");
947 if (oldGroup == null) {
948 PolicyLogger.error("We cannot get the group from the papEngine to delete policies");
950 Set<String> newPolicySet = new HashSet<>(group.getPolicies().size());
951 // a multiple of n runtime is faster than n^2, so I am using a
952 // hashset to do the comparison
953 for (PDPPolicy pol : group.getPolicies()) {
954 newPolicySet.add(pol.getId());
956 for (PDPPolicy pol : oldGroup.getPolicies()) {
957 // should be fast since getPolicies uses a HashSet in
959 if (!newPolicySet.contains(pol.getId())) {
960 String[] scopeAndName = policyDbDaoVar.getNameScopeAndVersionFromPdpPolicy(pol.getId());
961 PolicyEntity policyToDelete = null;
963 if (scopeAndName != null) {
964 policyToDelete = getPolicy(scopeAndName[0], scopeAndName[1]);
965 if ("XACMLPapServlet.doDelete".equals(requestType)) {
966 Iterator<PolicyEntity> dbPolicyIt = groupToUpdateInDb.getPolicies().iterator();
967 String policyName = policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
968 policyToDelete.getPolicyName())[0];
970 logger.info("PolicyDBDao: delete policy from GroupEntity");
972 while (dbPolicyIt.hasNext()) {
973 PolicyEntity dbpolicy = dbPolicyIt.next();
974 if (policyToDelete.getScope().equals(dbpolicy.getScope())
975 && policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
976 dbpolicy.getPolicyName())[0].equals(policyName)) {
978 auditPdpOperations(username,
979 dbpolicy.getScope() + "." + dbpolicy.getPolicyName(), "Delete");
980 logger.info("PolicyDBDao: deleting policy from the existing group:\n "
981 + "policyName is " + policyToDelete.getScope() + "."
982 + policyToDelete.getPolicyName() + "\n" + "group is "
983 + groupToUpdateInDb.getGroupId());
986 } catch (Exception e) {
988 PolicyLogger.error("Could not delete policy with name: "
989 + policyToDelete.getScope() + "." + policyToDelete.getPolicyName()
990 + "\n ID: " + policyToDelete.getPolicyId());
994 } catch (Exception e) {
995 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
996 "Could not get policy to remove: " + pol.getId());
997 throw new PersistenceException("Could not get policy to remove: " + pol.getId());
1003 if (group.getName() != null
1004 && !PolicyDBDao.stringEquals(group.getName(), groupToUpdateInDb.getgroupName())) {
1005 // we need to check if the new id exists in the database
1006 String newGrpId = PolicyDBDao.createNewPDPGroupId(group.getName());
1007 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1008 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, newGrpId);
1009 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1010 List<?> checkGroupQueryList;
1012 checkGroupQueryList = checkGroupQuery.list();
1013 } catch (Exception e) {
1014 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1015 "Caught Exception on checkGroupQuery.getResultList()");
1016 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
1018 if (!checkGroupQueryList.isEmpty()) {
1019 PolicyLogger.error("The new group name already exists, group id " + newGrpId);
1020 throw new PersistenceException("The new group name already exists, group id " + newGrpId);
1022 groupToUpdateInDb.setGroupId(newGrpId);
1023 groupToUpdateInDb.setGroupName(group.getName());
1024 this.newGroupId = group.getId();
1027 this.groupId = groupToUpdateInDb.getGroupKey();
1032 public void addPdpToGroup(String pdpId, String groupIdVar, String pdpName, String pdpDescription, int pdpJmxPort,
1034 logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, "
1035 + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + pdpId + ", "
1036 + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + username
1038 if (PolicyDBDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) {
1039 throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty");
1041 synchronized (emLock) {
1042 checkBeforeOperationRun();
1043 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1044 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar);
1045 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1046 List<?> checkGroupQueryList;
1048 checkGroupQueryList = checkGroupQuery.list();
1049 } catch (Exception e) {
1050 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1051 "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()");
1052 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
1054 if (checkGroupQueryList.size() != 1) {
1055 PolicyLogger.error("The group does not exist");
1056 throw new PersistenceException("The group does not exist");
1058 Query checkDuplicateQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1059 checkDuplicateQuery.setParameter(PolicyDBDao.PDP_ID, pdpId);
1060 checkDuplicateQuery.setParameter(PolicyDBDao.DELETED, false);
1061 List<?> checkDuplicateList;
1063 checkDuplicateList = checkDuplicateQuery.list();
1064 } catch (Exception e) {
1065 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1066 "Caught Exception trying to check for duplicate PDP " + pdpId
1067 + " on checkDuplicateQuery.getResultList()");
1068 throw new PersistenceException("Query failed trying to check for duplicate PDP " + pdpId);
1071 if (!checkDuplicateList.isEmpty()) {
1072 logger.warn("PDP already exists with id " + pdpId);
1073 newPdp = (PdpEntity) checkDuplicateList.get(0);
1075 newPdp = new PdpEntity();
1078 newPdp.setCreatedBy(username);
1079 newPdp.setDeleted(false);
1080 newPdp.setDescription(pdpDescription);
1081 newPdp.setGroup((GroupEntity) checkGroupQueryList.get(0));
1082 newPdp.setJmxPort(pdpJmxPort);
1083 newPdp.setModifiedBy(username);
1084 newPdp.setPdpId(pdpId);
1085 newPdp.setPdpName(pdpName);
1087 newPdp.prePersist();
1089 session.persist(newPdp);
1091 this.pdpId = newPdp.getPdpKey();
1096 public void updatePdp(OnapPDP pdp, String username) {
1097 logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + ") called");
1099 throw new IllegalArgumentException("PDP pdp must not be null");
1101 if (PolicyDBDao.isNullOrEmpty(pdp.getId(), username)) {
1102 throw new IllegalArgumentException("pdp.getId() and username must not be null or empty");
1105 synchronized (emLock) {
1106 checkBeforeOperationRun();
1107 Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1108 getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId());
1109 getPdpQuery.setParameter(PolicyDBDao.DELETED, false);
1110 List<?> getPdpQueryList;
1112 getPdpQueryList = getPdpQuery.list();
1113 } catch (Exception e) {
1114 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1115 "Caught Exception on getPdpQuery.getResultList()");
1116 throw new PersistenceException("Query failed trying to get PDP " + pdp.getId());
1118 if (getPdpQueryList.isEmpty()) {
1119 PolicyLogger.error("The pdp cannot be found to update with id " + pdp.getId());
1120 throw new PersistenceException("The pdp cannot be found to update with id " + pdp.getId());
1121 } else if (getPdpQueryList.size() > 1) {
1122 PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1123 throw new PersistenceException(
1124 PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1126 PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1127 if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1128 pdpToUpdate.setModifiedBy(username);
1130 if (pdp.getDescription() != null
1131 && !PolicyDBDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) {
1132 pdpToUpdate.setDescription(pdp.getDescription());
1134 if (pdp.getName() != null && !PolicyDBDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) {
1135 pdpToUpdate.setPdpName(pdp.getName());
1137 if (pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())) {
1138 pdpToUpdate.setJmxPort(pdp.getJmxPort());
1142 this.pdpId = pdpToUpdate.getPdpKey();
1147 public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) {
1148 logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + "," + group + ","
1149 + username + ") called");
1150 if (pdp == null || group == null) {
1151 throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null");
1153 if (PolicyDBDao.isNullOrEmpty(username, pdp.getId(), group.getId())) {
1154 throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty");
1157 synchronized (emLock) {
1158 checkBeforeOperationRun();
1159 // check if pdp exists
1160 Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1161 getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId());
1162 getPdpQuery.setParameter(PolicyDBDao.DELETED, false);
1163 List<?> getPdpQueryList;
1165 getPdpQueryList = getPdpQuery.list();
1166 } catch (Exception e) {
1167 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1168 "Caught Exception on getPdpQuery.getResultList()");
1169 throw new PersistenceException("Query failed trying to get pdp to move with id " + pdp.getId());
1171 if (getPdpQueryList.isEmpty()) {
1172 PolicyLogger.error("The pdp cannot be found to move with id " + pdp.getId());
1173 throw new PersistenceException("The pdp cannot be found to move with id " + pdp.getId());
1174 } else if (getPdpQueryList.size() > 1) {
1175 PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1176 throw new PersistenceException(
1177 PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1180 // check if new group exists
1181 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1182 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1183 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1184 List<?> checkGroupQueryList;
1186 checkGroupQueryList = checkGroupQuery.list();
1187 } catch (Exception e) {
1188 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1189 "Caught Exception trying to get group on checkGroupQuery.getResultList()");
1190 throw new PersistenceException("Query failed trying to get new group " + group.getId());
1192 if (checkGroupQueryList.size() != 1) {
1193 PolicyLogger.error("The group " + group.getId() + " does not exist");
1194 throw new PersistenceException("The group " + group.getId() + " does not exist");
1196 GroupEntity groupToMoveInto = (GroupEntity) checkGroupQueryList.get(0);
1197 PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1198 pdpToUpdate.setGroup(groupToMoveInto);
1199 if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1200 pdpToUpdate.setModifiedBy(username);
1204 this.pdpId = pdpToUpdate.getPdpKey();
1209 public void changeDefaultGroup(OnapPDPGroup group, String username) {
1210 logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + ","
1211 + username + ") called");
1212 if (group == null) {
1213 throw new IllegalArgumentException("PDPGroup group must not be null");
1215 if (PolicyDBDao.isNullOrEmpty(group.getId(), username)) {
1216 throw new IllegalArgumentException("group.getId() and username must not be null or empty");
1219 synchronized (emLock) {
1220 checkBeforeOperationRun();
1221 Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1222 getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1223 getGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1224 List<?> getGroupQueryList;
1226 getGroupQueryList = getGroupQuery.list();
1227 } catch (Exception e) {
1228 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1229 "Caught Exception on getGroupQuery.getResultList()");
1230 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId());
1232 if (getGroupQueryList.isEmpty()) {
1233 PolicyLogger.error("The group cannot be found to set default with id " + group.getId());
1234 throw new PersistenceException("The group cannot be found to set default with id " + group.getId());
1235 } else if (getGroupQueryList.size() > 1) {
1236 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1237 throw new PersistenceException(
1238 PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1240 GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0);
1241 newDefaultGroup.setDefaultGroup(true);
1242 if (!PolicyDBDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) {
1243 newDefaultGroup.setModifiedBy(username);
1247 this.groupId = newDefaultGroup.getGroupKey();
1248 Query setAllGroupsNotDefault = session.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup "
1249 + "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey");
1250 // not going to set modified by for all groups
1251 setAllGroupsNotDefault.setParameter("defaultGroup", false);
1252 setAllGroupsNotDefault.setParameter(PolicyDBDao.DELETED, false);
1253 setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey());
1255 logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default");
1256 } catch (Exception e) {
1257 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1258 "Caught Exception on setAllGroupsNotDefault.executeUpdate()");
1259 throw new PersistenceException("Could not set all other groups default to false");
1266 public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDBException {
1267 logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup(" + group + ", "
1268 + moveToGroup + "," + username + ") called");
1269 if (group == null) {
1270 throw new IllegalArgumentException("PDPGroup group cannot be null");
1272 if (PolicyDBDao.isNullOrEmpty(username, group.getId())) {
1273 throw new IllegalArgumentException("group.getId() and and username must not be null or empty");
1276 if (group.isDefaultGroup()) {
1277 PolicyLogger.error("The default group " + group.getId() + " was attempted to be deleted. It cannot be.");
1278 throw new PolicyDBException("You cannot delete the default group.");
1280 synchronized (emLock) {
1281 checkBeforeOperationRun();
1282 Query deleteGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1283 deleteGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1284 deleteGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1285 List<?> deleteGroupQueryList;
1287 deleteGroupQueryList = deleteGroupQuery.list();
1288 } catch (Exception e) {
1289 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1290 "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()");
1291 throw new PersistenceException("Query failed trying to check if group exists");
1293 if (deleteGroupQueryList.isEmpty()) {
1294 logger.warn(PolicyDBDao.GROUP_NOT_FOUND + group.getId());
1296 } else if (deleteGroupQueryList.size() > 1) {
1297 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1298 throw new PersistenceException(
1299 PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1302 Query pdpsInGroupQuery =
1303 session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted");
1304 pdpsInGroupQuery.setParameter("group", (deleteGroupQueryList.get(0)));
1305 pdpsInGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1306 List<?> pdpsInGroupList;
1308 pdpsInGroupList = pdpsInGroupQuery.list();
1309 } catch (Exception e) {
1310 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1311 "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()");
1312 throw new PersistenceException("Query failed trying to get PDPs in group");
1314 if (!pdpsInGroupList.isEmpty()) {
1315 if (moveToGroup != null) {
1316 Query checkMoveToGroupQuery = session
1317 .createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted");
1318 checkMoveToGroupQuery.setParameter(PolicyDBDao.GROUP_ID, moveToGroup.getId());
1319 checkMoveToGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1320 List<?> checkMoveToGroupList;
1322 checkMoveToGroupList = checkMoveToGroupQuery.list();
1323 } catch (Exception e) {
1324 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1325 "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList");
1326 throw new PersistenceException("Query failed trying to check if group exists");
1328 if (checkMoveToGroupList.isEmpty()) {
1329 PolicyLogger.error(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId());
1330 throw new PersistenceException(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId());
1331 } else if (checkMoveToGroupList.size() > 1) {
1333 PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1334 throw new PersistenceException(
1335 PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1337 GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0);
1338 for (Object pdpObject : pdpsInGroupList) {
1339 PdpEntity pdp = (PdpEntity) pdpObject;
1340 pdp.setGroup(newGroup);
1341 if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) {
1342 pdp.setModifiedBy(username);
1346 this.newGroupId = newGroup.getGroupId();
1347 } catch (PersistenceException e) {
1348 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1349 "Caught PersistenceException trying to set pdp group to null on em.flush()");
1350 throw new PersistenceException("Query failed trying to set pdp group to ");
1355 PolicyLogger.error("Group " + group.getId()
1356 + " is trying to be delted with PDPs. No group was provided to move them to");
1357 throw new PolicyDBException("Group has PDPs. Must provide a group for them to move to");
1361 // delete group here
1362 GroupEntity groupToDelete = (GroupEntity) deleteGroupQueryList.get(0);
1363 groupToDelete.setDeleted(true);
1364 if (!PolicyDBDao.stringEquals(groupToDelete.getModifiedBy(), username)) {
1365 groupToDelete.setModifiedBy(username);
1368 this.groupId = groupToDelete.getGroupKey();
1373 public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, String username)
1374 throws PolicyDBException {
1376 "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup("
1377 + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + ") called");
1378 if (PolicyDBDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) {
1379 throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty");
1381 synchronized (emLock) {
1382 checkBeforeOperationRun();
1383 // check if group exists
1384 Query groupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1385 groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar);
1386 groupQuery.setParameter(PolicyDBDao.DELETED, false);
1387 List<?> groupQueryList;
1389 groupQueryList = groupQuery.list();
1390 } catch (Exception e) {
1391 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1392 "Caught Exception trying to check if group exists groupQuery.getResultList()");
1393 throw new PersistenceException("Query failed trying to check if group " + groupIdVar + " exists");
1395 if (groupQueryList.isEmpty()) {
1396 PolicyLogger.error("Group policy is being added to does not exist with id " + groupIdVar);
1397 throw new PersistenceException("Group policy is being added to does not exist with id " + groupIdVar);
1398 } else if (groupQueryList.size() > 1) {
1399 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1400 throw new PersistenceException(
1401 PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1404 // we need to convert the form of the policy id that is used groups
1405 // into the form that is used
1406 // for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml)
1407 PolicyDBDao policyDbDao = new PolicyDBDao();
1408 String[] policyNameScopeAndVersion = policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar);
1409 if (policyNameScopeAndVersion == null) {
1410 throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version");
1412 Query policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName "
1413 + "AND p.scope=:scope AND p.deleted=:deleted");
1414 policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]);
1415 policyQuery.setParameter(PolicyDBDao.SCOPE, policyNameScopeAndVersion[1]);
1416 policyQuery.setParameter(PolicyDBDao.DELETED, false);
1417 List<?> policyQueryList;
1419 policyQueryList = policyQuery.list();
1420 } catch (Exception e) {
1422 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1423 "Caught Exception trying to check if policy exists policyQuery.getResultList()");
1424 throw new PersistenceException(
1425 "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + " exists");
1427 if (policyQueryList.isEmpty()) {
1428 PolicyLogger.error("Policy being added to the group does not exist with policy id "
1429 + policyNameScopeAndVersion[0]);
1430 throw new PersistenceException("Policy being added to the group does not exist with policy id "
1431 + policyNameScopeAndVersion[0]);
1432 } else if (policyQueryList.size() > 1) {
1434 PolicyDBDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1435 throw new PersistenceException(
1436 PolicyDBDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1438 logger.info("PolicyDBDao: Getting group and policy from database");
1439 GroupEntity group = (GroupEntity) groupQueryList.get(0);
1440 PolicyEntity policy = (PolicyEntity) policyQueryList.get(0);
1441 Iterator<PolicyEntity> policyIt = group.getPolicies().iterator();
1442 String policyName = policyDbDao.getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0];
1444 logger.info("PolicyDBDao: policyName retrieved is " + policyName);
1446 while (policyIt.hasNext()) {
1447 PolicyEntity pol = policyIt.next();
1448 if (policy.getScope().equals(pol.getScope())
1449 && policyDbDao.getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0]
1450 .equals(policyName)) {
1454 } catch (Exception e) {
1456 PolicyLogger.error("Could not delete old versions for policy " + policy.getPolicyName() + ", ID: "
1457 + policy.getPolicyId());
1459 group.addPolicyToGroup(policy);
1460 auditPdpOperations(username, policy.getScope() + "." + policy.getPolicyName(), "Push");
1463 // After adding policy to the db group we need to make sure the
1464 // filesytem group is in sync with the db group
1466 StdPDPGroup pdpGroup =
1467 (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getGroupId());
1468 return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group);
1469 } catch (PAPException e) {
1471 PolicyLogger.error("PolicyDBDao: Could not synchronize the filesystem group with the database group. "
1478 // this means delete pdp not just remove from group
1480 public void removePdpFromGroup(String pdpId, String username) {
1481 logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpId + "," + username
1483 if (PolicyDBDao.isNullOrEmpty(pdpId, username)) {
1484 throw new IllegalArgumentException("pdpID and username must not be null or empty");
1486 synchronized (emLock) {
1487 checkBeforeOperationRun();
1488 Query pdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1489 pdpQuery.setParameter(PolicyDBDao.PDP_ID, pdpId);
1490 pdpQuery.setParameter(PolicyDBDao.DELETED, false);
1493 pdpList = pdpQuery.list();
1494 } catch (Exception e) {
1495 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1496 "Caught Exception trying to check if pdp exists pdpQuery.getResultList()");
1497 throw new PersistenceException("Query failed trying to check if pdp " + pdpId + " exists");
1499 if (pdpList.size() > 1) {
1500 PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1501 throw new PersistenceException(
1502 "Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1503 } else if (pdpList.isEmpty()) {
1504 PolicyLogger.error("Pdp being removed does not exist with id " + pdpId);
1507 PdpEntity pdp = (PdpEntity) pdpList.get(0);
1512 if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) {
1513 pdp.setModifiedBy(username);
1515 pdp.setDeleted(true);
1518 this.pdpId = pdp.getPdpKey();
1522 private static String evaluateXPath(String expression, String xml) {
1523 InputSource source = new InputSource(new StringReader(xml));
1525 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1526 String description = "";
1528 DocumentBuilder db = dbf.newDocumentBuilder();
1529 Document document = db.parse(source);
1531 XPathFactory xpathFactory = XPathFactory.newInstance();
1532 XPath xpath = xpathFactory.newXPath();
1534 description = xpath.evaluate(expression, document);
1535 } catch (Exception e) {
1536 logger.error("Exception Occured while evaluating path" + e);
1541 public static boolean isJunit() {
1545 public static void setJunit(boolean isJunit) {
1546 PolicyDbDaoTransactionInstance.isJunit = isJunit;
1550 * Audit pdp operations.
1552 * @param username the username
1553 * @param policyID the policy ID
1554 * @param action the action
1556 public void auditPdpOperations(String username, String policyID, String action) {
1557 PolicyAuditlog log = new PolicyAuditlog();
1558 log.setUserName(username);
1559 log.setActions(action);
1560 log.setPolicyName(policyID);
1561 log.setDateAndTime(new Date());