2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2019 Nordix Foundation.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pap.xacml.rest.components;
24 import com.att.research.xacml.api.pap.PAPException;
25 import com.att.research.xacml.api.pap.PDPPolicy;
26 import com.att.research.xacml.util.XACMLProperties;
29 import java.io.FileInputStream;
30 import java.io.FileNotFoundException;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.StringReader;
34 import java.nio.file.InvalidPathException;
35 import java.nio.file.Paths;
36 import java.util.Date;
37 import java.util.HashSet;
38 import java.util.Iterator;
39 import java.util.List;
42 import javax.persistence.PersistenceException;
43 import javax.persistence.RollbackException;
44 import javax.xml.parsers.DocumentBuilder;
45 import javax.xml.parsers.DocumentBuilderFactory;
46 import javax.xml.xpath.XPath;
47 import javax.xml.xpath.XPathFactory;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
52 import org.apache.commons.io.FilenameUtils;
53 import org.apache.commons.io.IOUtils;
54 import org.hibernate.Query;
55 import org.hibernate.Session;
56 import org.hibernate.SessionFactory;
57 import org.onap.policy.common.logging.eelf.MessageCodes;
58 import org.onap.policy.common.logging.eelf.PolicyLogger;
59 import org.onap.policy.common.logging.flexlogger.FlexLogger;
60 import org.onap.policy.common.logging.flexlogger.Logger;
61 import org.onap.policy.rest.XacmlRestProperties;
62 import org.onap.policy.rest.adapter.PolicyRestAdapter;
63 import org.onap.policy.rest.dao.PolicyDbException;
64 import org.onap.policy.rest.jpa.ActionBodyEntity;
65 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
66 import org.onap.policy.rest.jpa.GroupEntity;
67 import org.onap.policy.rest.jpa.PdpEntity;
68 import org.onap.policy.rest.jpa.PolicyAuditlog;
69 import org.onap.policy.rest.jpa.PolicyEntity;
70 import org.onap.policy.xacml.api.pap.OnapPDP;
71 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
72 import org.onap.policy.xacml.std.pap.StdPDPGroup;
73 import org.onap.policy.xacml.util.XACMLPolicyWriter;
74 import org.springframework.beans.factory.annotation.Autowired;
75 import org.springframework.stereotype.Component;
76 import org.w3c.dom.Document;
77 import org.xml.sax.InputSource;
80 public class PolicyDbDaoTransactionInstance implements PolicyDbDaoTransaction {
81 private static final Logger logger = FlexLogger.getLogger(PolicyDbDaoTransactionInstance.class);
83 // Recurring constants
84 private static final String BRACKET_CALLED = ") called";
85 private static final String EXISTS = " exists";
86 private static final String GROUP = "group";
87 private static final String CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS = "Caught Exception on notifyOthers(";
89 private final Object emLock = new Object();
94 private boolean operationRun = false;
95 private Thread transactionTimer;
96 private static final String POLICY_NOTIFICATION = "policy";
97 private static final String PDP_NOTIFICATION = "pdp";
98 private static final String GROUP_NOTIFICATION = GROUP;
100 private static final String DECISIONMS_MODEL = "MicroService_Model";
101 private static boolean isJunit = false;
105 * Instantiates a new policy DB dao transaction instance.
107 * @param test the test
109 public PolicyDbDaoTransactionInstance(String test) {
110 // call the constructor with arguments
111 this(Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_TIMEOUT)),
112 Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT)));
115 public PolicyDbDaoTransactionInstance() {
116 // Default Constructor
120 public PolicyDbDaoTransactionInstance(SessionFactory sessionfactory) {
121 PolicyDbDaoTransactionInstance.sessionfactory = sessionfactory;
124 private static SessionFactory sessionfactory;
127 * Instantiates a new policy DB dao transaction instance.
129 * @param transactionTimeout the transaction timeout is how long the transaction can sit before rolling back
130 * @param transactionWaitTime the transaction wait time is how long to wait for the transaction to start before
132 public PolicyDbDaoTransactionInstance(int transactionTimeout, int transactionWaitTime) {
133 logger.info("\n\nPolicyDBDaoTransactionInstance() as PolicyDBDaoTransactionInstance() called:"
134 + "\n transactionTimeout = " + transactionTimeout + "\n transactionWaitTime = "
135 + transactionWaitTime + "\n\n");
141 synchronized (emLock) {
142 session = sessionfactory.openSession();
144 PolicyDbDao.getPolicyDbDaoInstance().startTransactionSynced(session, transactionWaitTime);
145 } catch (Exception e) {
146 logger.error("Could not lock transaction within " + transactionWaitTime + " milliseconds" + e);
147 throw new PersistenceException(
148 "Could not lock transaction within " + transactionWaitTime + " milliseconds");
151 class TransactionTimer implements Runnable {
153 private int sleepTime;
155 public TransactionTimer(int timeout) {
156 this.sleepTime = timeout;
161 if (logger.isDebugEnabled()) {
162 Date date = new java.util.Date();
163 logger.debug("\n\nTransactionTimer.run() - SLEEPING: " + "\n sleepTime (ms) = " + sleepTime
164 + "\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: " + "\n TimeStamp = "
174 + 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 = " + date.getTime()
184 logger.warn("PolicyDBDaoTransactionInstance - TransactionTimer - Rolling back transaction.");
185 rollbackTransaction();
190 transactionTimer = new Thread(new TransactionTimer(transactionTimeout), "transactionTimerThread");
191 transactionTimer.start();
195 private void checkBeforeOperationRun() {
196 checkBeforeOperationRun(false);
199 private void checkBeforeOperationRun(boolean justCheckOpen) {
200 if (!isTransactionOpen()) {
201 PolicyLogger.warn("checkBeforeOperationRun - There is no transaction currently open");
202 throw new IllegalStateException("There is no transaction currently open");
204 if (operationRun && !justCheckOpen) {
205 PolicyLogger.warn("checkBeforeOperationRun - "
206 + "An operation has already been performed and the current transaction should be committed");
207 throw new IllegalStateException(
208 "An operation has already been performed and the current transaction should be committed");
214 public void commitTransaction() {
215 synchronized (emLock) {
216 NotifyOtherPaps otherPaps = new NotifyOtherPaps();
217 logger.debug("commitTransaction() as commitTransaction() called");
218 if (!isTransactionOpen()) {
220 "There is no open transaction to commit - PolicyId - " + policyId + ", GroupId - " + groupId);
223 } catch (Exception e) {
224 logger.error("Exception Occured" + e);
229 session.getTransaction().commit();
230 } catch (RollbackException e) {
231 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
232 "Caught RollbackException on em.getTransaction().commit()");
233 throw new PersistenceException("The commit failed. Message:\n" + e.getMessage());
238 if (newGroupId != null) {
240 otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION, newGroupId);
241 } catch (Exception e) {
242 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
243 CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + policyId + "," + POLICY_NOTIFICATION + ","
248 otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION);
249 } catch (Exception e) {
250 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
251 CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + policyId + "," + POLICY_NOTIFICATION + ")");
256 // we don't want commit to fail just because this does
257 if (newGroupId != null) {
259 otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION, newGroupId);
260 } catch (Exception e) {
261 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
262 CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + groupId + "," + GROUP_NOTIFICATION + ","
267 otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION);
268 } catch (Exception e) {
269 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
270 CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + groupId + "," + GROUP_NOTIFICATION + ")");
275 // we don't want commit to fail just because this does
277 otherPaps.notifyOthers(pdpId, PDP_NOTIFICATION);
278 } catch (Exception e) {
279 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
280 CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + pdpId + "," + PDP_NOTIFICATION + ")");
284 if (transactionTimer != null) {
285 transactionTimer.interrupt();
290 public void rollbackTransaction() {
291 logger.debug("rollbackTransaction() as rollbackTransaction() called");
292 synchronized (emLock) {
293 if (isTransactionOpen()) {
295 session.getTransaction().rollback();
296 } catch (Exception e) {
297 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
298 "Could not rollback transaction");
302 } catch (Exception e) {
303 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
304 "Could not close Hibernate Session.");
310 } catch (Exception e) {
311 logger.warn("Could not close already closed transaction", e);
315 if (transactionTimer != null) {
316 transactionTimer.interrupt();
320 private void createPolicy(PolicyRestAdapter policy, String username, String policyScope, String inputPolicyName,
321 String policyDataString) {
322 String policyName = inputPolicyName;
323 logger.debug("createPolicy(PolicyRestAdapter policy, String username, String policyScope,"
324 + " String policyName, String policyDataString) as createPolicy(" + policy + ", " + username + ", "
325 + policyScope + ", " + policyName + ", " + policyDataString + ") called");
326 synchronized (emLock) {
327 PolicyDbDao policyDbDao = new PolicyDbDao();
328 checkBeforeOperationRun();
329 String configName = policyName;
330 if (policyName.contains("Config_")) {
331 policyName = policyName.replace(".Config_", ":Config_");
332 } else if (policyName.contains("Action_")) {
333 policyName = policyName.replace(".Action_", ":Action_");
334 } else if (policyName.contains("Decision_MS_")) {
335 policyName = policyName.replace(".Decision_MS_", ":Decision_MS_");
336 } else if (policyName.contains("Decision_")) {
337 policyName = policyName.replace(".Decision_", ":Decision_");
339 policyName = policyName.split(":")[1];
340 Query createPolicyQuery = session
341 .createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
342 createPolicyQuery.setParameter(PolicyDbDao.SCOPE, policyScope);
343 createPolicyQuery.setParameter("policyName", policyName);
344 List<?> createPolicyQueryList = createPolicyQuery.list();
345 PolicyEntity newPolicyEntity;
347 if (createPolicyQueryList.isEmpty()) {
348 newPolicyEntity = new PolicyEntity();
350 } else if (createPolicyQueryList.size() > 1) {
351 PolicyLogger.error("Somehow, more than one policy with the same "
352 + "scope, name, and deleted status were found in the database");
353 throw new PersistenceException("Somehow, more than one policy with the same"
354 + " scope, name, and deleted status were found in the database");
356 newPolicyEntity = (PolicyEntity) createPolicyQueryList.get(0);
360 ActionBodyEntity newActionBodyEntity = null;
361 if (policy.getPolicyType().equals(PolicyDbDao.ACTION)) {
362 boolean abupdate = false;
363 if (newPolicyEntity.getActionBodyEntity() == null) {
364 newActionBodyEntity = new ActionBodyEntity();
366 newActionBodyEntity = (ActionBodyEntity) session.get(ActionBodyEntity.class,
367 newPolicyEntity.getActionBodyEntity().getActionBodyId());
371 if (newActionBodyEntity != null) {
372 // build the file path
373 // trim the .xml off the end
374 String policyNameClean = FilenameUtils.removeExtension(configName);
375 String actionBodyName = policyNameClean + ".json";
377 // get the action body
378 String actionBodyString = policy.getActionBody();
379 if (actionBodyString == null) {
380 actionBodyString = "{}";
382 newActionBodyEntity.setActionBody(actionBodyString);
383 newActionBodyEntity.setActionBodyName(actionBodyName);
384 newActionBodyEntity.setModifiedBy("PolicyDBDao.createPolicy()");
385 newActionBodyEntity.setDeleted(false);
387 newActionBodyEntity.setCreatedBy("PolicyDBDao.createPolicy()");
389 if (logger.isDebugEnabled()) {
390 logger.debug("\nPolicyDBDao.createPolicy" + "\n newActionBodyEntity.getActionBody() = "
391 + newActionBodyEntity.getActionBody()
392 + "\n newActionBodyEntity.getActionBodyName() = "
393 + newActionBodyEntity.getActionBodyName()
394 + "\n newActionBodyEntity.getModifiedBy() = " + newActionBodyEntity.getModifiedBy()
395 + "\n newActionBodyEntity.getCreatedBy() = " + newActionBodyEntity.getCreatedBy()
396 + "\n newActionBodyEntity.isDeleted() = " + newActionBodyEntity.isDeleted()
397 + "\n FLUSHING to DB");
399 // push the actionBodyEntity to the DB
401 newActionBodyEntity.prePersist();
404 session.persist(newActionBodyEntity);
407 // newActionBodyEntity == null
408 // We have a actionBody in the policy but we found no
409 // actionBody in the DB
410 String msg = "\n\nPolicyDBDao.createPolicy - Incoming Action policy had an "
411 + "actionBody, but it could not be found in the DB for update." + "\n policyScope = "
412 + policyScope + "\n policyName = " + policyName + "\n\n";
413 PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, "
414 + "but it could not be found in the DB for update: policyName = " + policyName);
415 throw new IllegalArgumentException(msg);
419 ConfigurationDataEntity newConfigurationDataEntity;
420 if (PolicyDbDao.CONFIG.equals(policy.getPolicyType())
421 || DECISIONMS_MODEL.equals(policy.getRuleProvider())) {
422 boolean configUpdate;
423 if (newPolicyEntity.getConfigurationData() == null) {
424 newConfigurationDataEntity = new ConfigurationDataEntity();
425 configUpdate = false;
427 newConfigurationDataEntity = (ConfigurationDataEntity) session.get(ConfigurationDataEntity.class,
428 newPolicyEntity.getConfigurationData().getConfigurationDataId());
432 if (newConfigurationDataEntity != null) {
433 if (!PolicyDbDao.stringEquals(newConfigurationDataEntity.getConfigurationName(),
434 policyDbDao.getConfigFile(configName, policy))) {
435 newConfigurationDataEntity.setConfigurationName(policyDbDao.getConfigFile(configName, policy));
437 if (newConfigurationDataEntity.getConfigType() == null
438 || !newConfigurationDataEntity.getConfigType().equals(policy.getConfigType())) {
439 newConfigurationDataEntity.setConfigType(policy.getConfigType());
442 newConfigurationDataEntity.setCreatedBy(username);
444 if (newConfigurationDataEntity.getModifiedBy() == null
445 || !newConfigurationDataEntity.getModifiedBy().equals(username)) {
446 newConfigurationDataEntity.setModifiedBy(username);
448 if (newConfigurationDataEntity.getDescription() == null
449 || !newConfigurationDataEntity.getDescription().equals("")) {
450 newConfigurationDataEntity.setDescription("");
452 if (newConfigurationDataEntity.getConfigBody() == null
453 || newConfigurationDataEntity.getConfigBody().isEmpty()
454 || (!newConfigurationDataEntity.getConfigBody().equals(policy.getConfigBodyData()))) {
455 // hopefully one of these won't be null
456 if (policy.getConfigBodyData() == null || policy.getConfigBodyData().isEmpty()) {
457 newConfigurationDataEntity.setConfigBody(policy.getJsonBody());
459 newConfigurationDataEntity.setConfigBody(policy.getConfigBodyData());
462 if (newConfigurationDataEntity.isDeleted()) {
463 newConfigurationDataEntity.setDeleted(false);
466 newConfigurationDataEntity.prePersist();
469 session.persist(newConfigurationDataEntity);
472 // We have a configurationData body in the policy but we
473 // found no configurationData body in the DB
474 String msg = "\n\nPolicyDBDao.createPolicy - Incoming Config policy had a "
475 + "configurationData body, but it could not be found in the DB for update."
476 + "\n policyScope = " + policyScope + "\n policyName = " + policyName + "\n\n";
478 .error("PolicyDBDao.createPolicy - Incoming Config policy had a configurationData body, "
479 + "but it could not be found in the DB for update: policyName = " + policyName);
480 throw new IllegalArgumentException(msg);
484 newConfigurationDataEntity = null;
486 policyId = newPolicyEntity.getPolicyId();
488 if (!PolicyDbDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) {
489 newPolicyEntity.setPolicyName(policyName);
491 if (!PolicyDbDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) {
492 newPolicyEntity.setCreatedBy(username);
494 if (!PolicyDbDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) {
495 newPolicyEntity.setDescription(policy.getPolicyDescription());
497 if (!PolicyDbDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) {
498 newPolicyEntity.setModifiedBy(username);
500 if (!PolicyDbDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) {
501 newPolicyEntity.setPolicyData(policyDataString);
503 if (!PolicyDbDao.stringEquals(newPolicyEntity.getScope(), policyScope)) {
504 newPolicyEntity.setScope(policyScope);
506 if (newPolicyEntity.isDeleted()) {
507 newPolicyEntity.setDeleted(false);
509 newPolicyEntity.setConfigurationData(newConfigurationDataEntity);
510 newPolicyEntity.setActionBodyEntity(newActionBodyEntity);
512 newPolicyEntity.prePersist();
515 session.persist(newPolicyEntity);
518 this.policyId = newPolicyEntity.getPolicyId();
524 public void createPolicy(Policy policy, String username) {
525 InputStream policyXmlStream = null;
527 logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + policy + ","
528 + username + BRACKET_CALLED);
529 String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, ".");
530 // Does not need to be XACMLPolicyWriterWithPapNotify since it is
531 // already in the PAP
532 // and this transaction is intercepted up stream.
533 String policyDataString;
536 if (policy.policyAdapter.getData() instanceof PolicySetType) {
537 policyXmlStream = XACMLPolicyWriter
538 .getPolicySetXmlAsInputStream((PolicySetType) policy.getCorrectPolicyDataObject());
540 policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policy.getCorrectPolicyDataObject());
542 policyDataString = IOUtils.toString(policyXmlStream);
543 } catch (IOException e) {
544 policyDataString = "could not read";
545 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
546 "Caught IOException on IOUtils.toString(" + policyXmlStream + ")");
547 throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter.");
550 IOUtils.closeQuietly(policyXmlStream);
551 if (PolicyDbDao.isJunit()) {
552 if (policyDataString != null) {
553 logger.warn("isJUnit will overwrite policyDataString");
555 // Using parentPath object to set policy data.
556 policyDataString = policy.policyAdapter.getParentPath();
558 String configPath = "";
559 if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
560 configPath = evaluateXPath(
561 "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/"
562 + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
564 } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
565 configPath = evaluateXPath(
566 "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, "
567 + policy.policyAdapter.getActionAttribute()
568 + ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()",
570 } else if (DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
571 configPath = evaluateXPath(
572 "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/"
573 + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
577 String prefix = null;
578 if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())
579 || DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
580 prefix = configPath.substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(),
581 configPath.lastIndexOf(policy.policyAdapter.getPolicyName()));
582 if (PolicyDbDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) {
583 String configData = "";
585 String newConfigPath = configPath;
587 newConfigPath = processConfigPath(newConfigPath);
588 } catch (Exception e2) {
589 logger.error("Could not process config path: " + newConfigPath, e2);
591 configData = readConfigFile(newConfigPath);
592 } catch (Exception e) {
593 logger.error("Could not read config body data for " + configPath, e);
595 policy.policyAdapter.setConfigBodyData(configData);
597 } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
599 } else if ("Decision".equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
600 prefix = "Decision_";
603 if (!(policy.policyAdapter.getData() instanceof PolicyType)
604 && !(policy.policyAdapter.getData() instanceof PolicySetType)) {
605 PolicyLogger.error("The data field is not an instance of PolicyType");
606 throw new IllegalArgumentException("The data field is not an instance of PolicyType");
608 String finalName = policyScope + "." + prefix + policy.policyAdapter.getPolicyName() + "."
609 + policy.policyAdapter.getHighestVersion() + ".xml";
610 if (policy.policyAdapter.getConfigType() == null || "".equals(policy.policyAdapter.getConfigType())) {
611 // get the config file extension
613 if (configPath != null && !"".equalsIgnoreCase(configPath)) {
614 ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());
617 if (ext.contains("txt")) {
618 policy.policyAdapter.setConfigType(PolicyDbDao.OTHER_CONFIG);
619 } else if (ext.contains("json")) {
620 policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG);
621 } else if (ext.contains("xml")) {
622 policy.policyAdapter.setConfigType(PolicyDbDao.XML_CONFIG);
623 } else if (ext.contains("properties")) {
624 policy.policyAdapter.setConfigType(PolicyDbDao.PROPERTIES_CONFIG);
626 if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDbDao.ACTION)) {
627 policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG);
632 createPolicy(policy.policyAdapter, username, policyScope, finalName, policyDataString);
634 if (policyXmlStream != null) {
636 policyXmlStream.close();
637 } catch (IOException e) {
638 logger.error("Exception Occured while closing input stream" + e);
644 public PolicyEntity getPolicy(int policyId) {
645 return getPolicy(policyId, null, null);
648 public PolicyEntity getPolicy(String policyName, String scope) {
649 return getPolicy(-1, policyName, scope);
652 private PolicyEntity getPolicy(int policyIdVar, String policyName, String scope) {
653 logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar + "," + policyName
655 if (policyIdVar < 0 && PolicyDbDao.isNullOrEmpty(policyName, scope)) {
656 throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank");
659 synchronized (emLock) {
660 checkBeforeOperationRun(true);
661 // check if group exists
664 if (!PolicyDbDao.isNullOrEmpty(policyName, scope)) {
665 locPolicyId = policyName;
667 session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope");
668 policyQuery.setParameter("name", locPolicyId);
669 policyQuery.setParameter("scope", scope);
671 locPolicyId = String.valueOf(policyIdVar);
672 policyQuery = session.getNamedQuery("PolicyEntity.FindById");
673 policyQuery.setParameter("id", locPolicyId);
675 List<?> policyQueryList;
677 policyQueryList = policyQuery.list();
678 } catch (Exception e) {
679 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
680 "Caught Exception trying to get policy with policyQuery.getResultList()");
681 throw new PersistenceException("Query failed trying to get policy " + locPolicyId);
684 if (policyQueryList.isEmpty()) {
685 PolicyLogger.error("Policy does not exist with id " + locPolicyId);
686 throw new PersistenceException("Group policy is being added to does not exist with id " + locPolicyId);
687 } else if (policyQueryList.size() > 1) {
688 PolicyLogger.error(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB);
689 throw new PersistenceException(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB);
691 return (PolicyEntity) policyQueryList.get(0);
696 public GroupEntity getGroup(long groupKey) {
697 logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + BRACKET_CALLED);
699 throw new IllegalArgumentException("groupKey must be at least 0");
701 synchronized (emLock) {
702 checkBeforeOperationRun(true);
703 // check if group exists
704 Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey");
705 groupQuery.setParameter("groupKey", groupKey);
706 List<?> groupQueryList;
708 groupQueryList = groupQuery.list();
709 } catch (Exception e) {
710 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
711 "Caught Exception trying to get group with groupQuery.getResultList()");
712 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupKey);
714 if (groupQueryList.isEmpty()) {
715 PolicyLogger.error("Group does not exist with groupKey " + groupKey);
716 throw new PersistenceException("Group does not exist with groupKey " + groupKey);
717 } else if (groupQueryList.size() > 1) {
719 .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB);
720 throw new PersistenceException(
721 "Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB);
723 return (GroupEntity) groupQueryList.get(0);
728 public GroupEntity getGroup(String groupId) {
729 logger.debug("getGroup(String groupId) as getGroup(" + groupId + BRACKET_CALLED);
730 if (PolicyDbDao.isNullOrEmpty(groupId)) {
731 throw new IllegalArgumentException("groupId must not be null or empty");
733 synchronized (emLock) {
734 checkBeforeOperationRun(true);
735 // check if group exists
736 Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId");
737 groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId);
738 List<?> groupQueryList;
740 groupQueryList = groupQuery.list();
741 } catch (Exception e) {
742 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
743 "Caught Exception trying to get group with groupQuery.getResultList()");
744 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupId);
746 if (groupQueryList.isEmpty()) {
747 PolicyLogger.error("Group does not exist with id " + groupId);
748 throw new PersistenceException("Group does not exist with id " + groupId);
749 } else if (groupQueryList.size() > 1) {
750 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB);
751 throw new PersistenceException(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB);
753 return (GroupEntity) groupQueryList.get(0);
758 public List<?> getPdpsInGroup(long groupKey) {
759 logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + BRACKET_CALLED);
761 throw new IllegalArgumentException("groupId must not be < 0");
763 synchronized (emLock) {
764 checkBeforeOperationRun(true);
765 Query pdpsQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group");
766 pdpsQuery.setParameter(GROUP, getGroup(groupKey));
767 return pdpsQuery.list();
772 public PdpEntity getPdp(long pdpKey) {
773 logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + BRACKET_CALLED);
775 throw new IllegalArgumentException("pdpKey must be at least 0");
777 synchronized (emLock) {
778 checkBeforeOperationRun(true);
779 // check if group exists
780 Query pdpQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey");
781 pdpQuery.setParameter("pdpKey", pdpKey);
782 List<?> pdpQueryList;
784 pdpQueryList = pdpQuery.list();
785 } catch (Exception e) {
786 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
787 "Caught Exception trying to get pdp with pdpQuery.getResultList()");
788 throw new PersistenceException("Query failed trying to get pdp " + pdpKey);
790 if (pdpQueryList.isEmpty()) {
791 PolicyLogger.error("Pdp does not exist with pdpKey " + pdpKey);
792 throw new PersistenceException("Pdp does not exist with pdpKey " + pdpKey);
793 } else if (pdpQueryList.size() > 1) {
794 PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB);
795 throw new PersistenceException(
796 "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB);
798 return (PdpEntity) pdpQueryList.get(0);
803 public boolean isTransactionOpen() {
804 logger.debug("isTransactionOpen() as isTransactionOpen() called");
805 synchronized (emLock) {
806 return session.isOpen() && session.getTransaction().isActive();
810 private String processConfigPath(String inputConfigPath) {
811 String configPath = inputConfigPath;
812 String webappsPath = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS);
813 if (webappsPath == null) {
814 logger.error("Webapps property does not exist");
815 throw new IllegalArgumentException("Webapps property does not exist");
817 configPath = configPath.replace("$URL", webappsPath);
818 // make sure the correct slashes are in
820 configPath = Paths.get(configPath).toString();
821 } catch (InvalidPathException e) {
822 logger.error("Invalid config path: " + configPath, e);
823 throw new IllegalArgumentException("Invalid config path: " + configPath);
828 private String readConfigFile(String configPath) {
829 String configDataString = null;
830 InputStream configContentStream = null;
832 configContentStream = new FileInputStream(configPath);
833 configDataString = IOUtils.toString(configContentStream);
834 } catch (FileNotFoundException e) {
835 logger.error("Caught FileNotFoundException on new FileInputStream(" + configPath + ")", e);
836 throw new IllegalArgumentException("The config file path does not exist");
837 } catch (IOException e2) {
838 logger.error("Caught IOException on newIOUtils.toString(" + configContentStream + ")", e2);
839 throw new IllegalArgumentException("The config file path cannot be read");
841 IOUtils.closeQuietly(configContentStream);
843 if (configDataString == null) {
844 throw new IllegalArgumentException("The config file path cannot be read");
846 return configDataString;
850 public void close() {
851 synchronized (emLock) {
852 if (session.isOpen()) {
853 if (session.getTransaction().isActive()) {
854 session.getTransaction().rollback();
858 if (transactionTimer != null) {
859 transactionTimer.interrupt();
865 public void createGroup(String groupId, String groupName, String inputGroupDescription, String username) {
866 String groupDescription = inputGroupDescription;
867 logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + groupName + ", "
868 + groupDescription + BRACKET_CALLED);
869 if (PolicyDbDao.isNullOrEmpty(groupId, groupName, username)) {
870 throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty");
872 if (groupDescription == null) {
873 groupDescription = "";
876 synchronized (emLock) {
877 checkBeforeOperationRun();
878 Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
879 checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId);
880 checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
881 List<?> checkGroupQueryList;
883 checkGroupQueryList = checkGroupQuery.list();
884 } catch (Exception e) {
885 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
886 "Caught Exception on checkGroupQuery.getResultList()");
887 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
889 if (!checkGroupQueryList.isEmpty()) {
890 PolicyLogger.error("The group being added already exists with id " + groupId);
891 throw new PersistenceException("The group being added already exists with id " + groupId);
893 GroupEntity newGroup = new GroupEntity();
894 newGroup.setCreatedBy(username);
895 newGroup.setModifiedBy(username);
896 newGroup.setGroupName(groupName);
897 newGroup.setGroupId(groupId);
898 newGroup.setDescription(groupDescription);
900 newGroup.prePersist();
902 session.persist(newGroup);
904 this.groupId = newGroup.getGroupKey();
909 public void updateGroup(OnapPDPGroup group, String requestType, String username) {
910 logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + "," + requestType + ","
911 + username + BRACKET_CALLED);
913 throw new IllegalArgumentException("PDPGroup group must not be null");
915 if (PolicyDbDao.isNullOrEmpty(group.getId(), requestType)) {
916 throw new IllegalArgumentException("group.getId() and username must not be null or empty");
919 synchronized (emLock) {
920 PolicyDbDao policyDbDaoVar = new PolicyDbDao();
921 checkBeforeOperationRun();
922 Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
923 getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
924 getGroupQuery.setParameter(PolicyDbDao.DELETED, false);
925 List<?> getGroupQueryList;
927 getGroupQueryList = getGroupQuery.list();
928 } catch (Exception e) {
929 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
930 "Caught Exception on getGroupQuery.getResultList()");
931 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing");
933 if (getGroupQueryList.isEmpty()) {
934 PolicyLogger.error("The group cannot be found to update with id " + group.getId());
935 throw new PersistenceException("The group cannot be found to update with id " + group.getId());
936 } else if (getGroupQueryList.size() > 1) {
937 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
938 throw new PersistenceException(
939 PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
941 GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0);
942 if (!PolicyDbDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) {
943 groupToUpdateInDb.setModifiedBy(requestType);
945 if (group.getDescription() != null
946 && !PolicyDbDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) {
947 groupToUpdateInDb.setDescription(group.getDescription());
949 // let's find out what policies have been deleted
950 StdPDPGroup oldGroup = null;
952 oldGroup = (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getId());
953 } catch (PAPException e1) {
954 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR,
955 "We cannot get the group from the papEngine to delete policies");
957 if (oldGroup == null) {
958 PolicyLogger.error("We cannot get the group from the papEngine to delete policies");
960 Set<String> newPolicySet = new HashSet<>(group.getPolicies().size());
961 // a multiple of n runtime is faster than n^2, so I am using a
962 // hashset to do the comparison
963 for (PDPPolicy pol : group.getPolicies()) {
964 newPolicySet.add(pol.getId());
966 for (PDPPolicy pol : oldGroup.getPolicies()) {
967 // should be fast since getPolicies uses a HashSet in
969 if (!newPolicySet.contains(pol.getId())) {
970 String[] scopeAndName = policyDbDaoVar.getNameScopeAndVersionFromPdpPolicy(pol.getId());
971 PolicyEntity policyToDelete = null;
973 if (scopeAndName != null) {
974 policyToDelete = getPolicy(scopeAndName[0], scopeAndName[1]);
975 if ("XACMLPapServlet.doDelete".equals(requestType)) {
976 Iterator<PolicyEntity> dbPolicyIt = groupToUpdateInDb.getPolicies().iterator();
977 String policyName = policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
978 policyToDelete.getPolicyName())[0];
980 logger.info("PolicyDBDao: delete policy from GroupEntity");
982 while (dbPolicyIt.hasNext()) {
983 PolicyEntity dbpolicy = dbPolicyIt.next();
984 if (policyToDelete.getScope().equals(dbpolicy.getScope())
985 && policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
986 dbpolicy.getPolicyName())[0].equals(policyName)) {
988 auditPdpOperations(username,
989 dbpolicy.getScope() + "." + dbpolicy.getPolicyName(), "Delete");
990 logger.info("PolicyDBDao: deleting policy from the existing group:\n "
991 + "policyName is " + policyToDelete.getScope() + "."
992 + policyToDelete.getPolicyName() + "\n" + "group is "
993 + groupToUpdateInDb.getGroupId());
996 } catch (Exception e) {
998 PolicyLogger.error("Could not delete policy with name: "
999 + policyToDelete.getScope() + "." + policyToDelete.getPolicyName()
1000 + "\n ID: " + policyToDelete.getPolicyId());
1004 } catch (Exception e) {
1005 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1006 "Could not get policy to remove: " + pol.getId());
1007 throw new PersistenceException("Could not get policy to remove: " + pol.getId());
1013 if (group.getName() != null
1014 && !PolicyDbDao.stringEquals(group.getName(), groupToUpdateInDb.getGroupName())) {
1015 // we need to check if the new id exists in the database
1016 String newGrpId = PolicyDbDao.createNewPdpGroupId(group.getName());
1017 Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1018 checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, newGrpId);
1019 checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1020 List<?> checkGroupQueryList;
1022 checkGroupQueryList = checkGroupQuery.list();
1023 } catch (Exception e) {
1024 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1025 "Caught Exception on checkGroupQuery.getResultList()");
1026 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
1028 if (!checkGroupQueryList.isEmpty()) {
1029 PolicyLogger.error("The new group name already exists, group id " + newGrpId);
1030 throw new PersistenceException("The new group name already exists, group id " + newGrpId);
1032 groupToUpdateInDb.setGroupId(newGrpId);
1033 groupToUpdateInDb.setGroupName(group.getName());
1034 this.newGroupId = group.getId();
1037 this.groupId = groupToUpdateInDb.getGroupKey();
1042 public void addPdpToGroup(String pdpId, String groupIdVar, String pdpName, String pdpDescription, int pdpJmxPort,
1044 logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, "
1045 + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + pdpId + ", "
1046 + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + username
1048 if (PolicyDbDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) {
1049 throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty");
1051 synchronized (emLock) {
1052 checkBeforeOperationRun();
1053 Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1054 checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar);
1055 checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1056 List<?> checkGroupQueryList;
1058 checkGroupQueryList = checkGroupQuery.list();
1059 } catch (Exception e) {
1060 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1061 "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()");
1062 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
1064 if (checkGroupQueryList.size() != 1) {
1065 PolicyLogger.error("The group does not exist");
1066 throw new PersistenceException("The group does not exist");
1068 Query checkDuplicateQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1069 checkDuplicateQuery.setParameter(PolicyDbDao.PDP_ID, pdpId);
1070 checkDuplicateQuery.setParameter(PolicyDbDao.DELETED, false);
1071 List<?> checkDuplicateList;
1073 checkDuplicateList = checkDuplicateQuery.list();
1074 } catch (Exception e) {
1075 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1076 "Caught Exception trying to check for duplicate PDP " + pdpId
1077 + " on checkDuplicateQuery.getResultList()");
1078 throw new PersistenceException("Query failed trying to check for duplicate PDP " + pdpId);
1081 if (!checkDuplicateList.isEmpty()) {
1082 logger.warn("PDP already exists with id " + pdpId);
1083 newPdp = (PdpEntity) checkDuplicateList.get(0);
1085 newPdp = new PdpEntity();
1088 newPdp.setCreatedBy(username);
1089 newPdp.setDeleted(false);
1090 newPdp.setDescription(pdpDescription);
1091 newPdp.setGroup((GroupEntity) checkGroupQueryList.get(0));
1092 newPdp.setJmxPort(pdpJmxPort);
1093 newPdp.setModifiedBy(username);
1094 newPdp.setPdpId(pdpId);
1095 newPdp.setPdpName(pdpName);
1097 newPdp.prePersist();
1099 session.persist(newPdp);
1101 this.pdpId = newPdp.getPdpKey();
1106 public void updatePdp(OnapPDP pdp, String username) {
1107 logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + BRACKET_CALLED);
1109 throw new IllegalArgumentException("PDP pdp must not be null");
1111 if (PolicyDbDao.isNullOrEmpty(pdp.getId(), username)) {
1112 throw new IllegalArgumentException("pdp.getId() and username must not be null or empty");
1115 synchronized (emLock) {
1116 checkBeforeOperationRun();
1117 Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1118 getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId());
1119 getPdpQuery.setParameter(PolicyDbDao.DELETED, false);
1120 List<?> getPdpQueryList;
1122 getPdpQueryList = getPdpQuery.list();
1123 } catch (Exception e) {
1124 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1125 "Caught Exception on getPdpQuery.getResultList()");
1126 throw new PersistenceException("Query failed trying to get PDP " + pdp.getId());
1128 if (getPdpQueryList.isEmpty()) {
1129 PolicyLogger.error("The pdp cannot be found to update with id " + pdp.getId());
1130 throw new PersistenceException("The pdp cannot be found to update with id " + pdp.getId());
1131 } else if (getPdpQueryList.size() > 1) {
1132 PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1133 throw new PersistenceException(
1134 PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1136 PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1137 if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1138 pdpToUpdate.setModifiedBy(username);
1140 if (pdp.getDescription() != null
1141 && !PolicyDbDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) {
1142 pdpToUpdate.setDescription(pdp.getDescription());
1144 if (pdp.getName() != null && !PolicyDbDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) {
1145 pdpToUpdate.setPdpName(pdp.getName());
1147 if (pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())) {
1148 pdpToUpdate.setJmxPort(pdp.getJmxPort());
1152 this.pdpId = pdpToUpdate.getPdpKey();
1157 public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) {
1158 logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + "," + group + ","
1159 + username + BRACKET_CALLED);
1160 if (pdp == null || group == null) {
1161 throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null");
1163 if (PolicyDbDao.isNullOrEmpty(username, pdp.getId(), group.getId())) {
1164 throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty");
1167 synchronized (emLock) {
1168 checkBeforeOperationRun();
1169 // check if pdp exists
1170 Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1171 getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId());
1172 getPdpQuery.setParameter(PolicyDbDao.DELETED, false);
1173 List<?> getPdpQueryList;
1175 getPdpQueryList = getPdpQuery.list();
1176 } catch (Exception e) {
1177 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1178 "Caught Exception on getPdpQuery.getResultList()");
1179 throw new PersistenceException("Query failed trying to get pdp to move with id " + pdp.getId());
1181 if (getPdpQueryList.isEmpty()) {
1182 PolicyLogger.error("The pdp cannot be found to move with id " + pdp.getId());
1183 throw new PersistenceException("The pdp cannot be found to move with id " + pdp.getId());
1184 } else if (getPdpQueryList.size() > 1) {
1185 PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1186 throw new PersistenceException(
1187 PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1190 // check if new group exists
1191 Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1192 checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
1193 checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1194 List<?> checkGroupQueryList;
1196 checkGroupQueryList = checkGroupQuery.list();
1197 } catch (Exception e) {
1198 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1199 "Caught Exception trying to get group on checkGroupQuery.getResultList()");
1200 throw new PersistenceException("Query failed trying to get new group " + group.getId());
1202 if (checkGroupQueryList.size() != 1) {
1203 PolicyLogger.error("The group " + group.getId() + " does not exist");
1204 throw new PersistenceException("The group " + group.getId() + " does not exist");
1206 GroupEntity groupToMoveInto = (GroupEntity) checkGroupQueryList.get(0);
1207 PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1208 pdpToUpdate.setGroup(groupToMoveInto);
1209 if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1210 pdpToUpdate.setModifiedBy(username);
1214 this.pdpId = pdpToUpdate.getPdpKey();
1219 public void changeDefaultGroup(OnapPDPGroup group, String username) {
1220 logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + ","
1221 + username + BRACKET_CALLED);
1222 if (group == null) {
1223 throw new IllegalArgumentException("PDPGroup group must not be null");
1225 if (PolicyDbDao.isNullOrEmpty(group.getId(), username)) {
1226 throw new IllegalArgumentException("group.getId() and username must not be null or empty");
1229 synchronized (emLock) {
1230 checkBeforeOperationRun();
1231 Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1232 getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
1233 getGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1234 List<?> getGroupQueryList;
1236 getGroupQueryList = getGroupQuery.list();
1237 } catch (Exception e) {
1238 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1239 "Caught Exception on getGroupQuery.getResultList()");
1240 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId());
1242 if (getGroupQueryList.isEmpty()) {
1243 PolicyLogger.error("The group cannot be found to set default with id " + group.getId());
1244 throw new PersistenceException("The group cannot be found to set default with id " + group.getId());
1245 } else if (getGroupQueryList.size() > 1) {
1246 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1247 throw new PersistenceException(
1248 PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1250 GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0);
1251 newDefaultGroup.setDefaultGroup(true);
1252 if (!PolicyDbDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) {
1253 newDefaultGroup.setModifiedBy(username);
1257 this.groupId = newDefaultGroup.getGroupKey();
1258 Query setAllGroupsNotDefault = session.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup "
1259 + "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey");
1260 // not going to set modified by for all groups
1261 setAllGroupsNotDefault.setParameter("defaultGroup", false);
1262 setAllGroupsNotDefault.setParameter(PolicyDbDao.DELETED, false);
1263 setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey());
1265 logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default");
1266 } catch (Exception e) {
1267 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1268 "Caught Exception on setAllGroupsNotDefault.executeUpdate()");
1269 throw new PersistenceException("Could not set all other groups default to false");
1276 public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDbException {
1277 logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup(" + group + ", "
1278 + moveToGroup + "," + username + BRACKET_CALLED);
1279 if (group == null) {
1280 throw new IllegalArgumentException("PDPGroup group cannot be null");
1282 if (PolicyDbDao.isNullOrEmpty(username, group.getId())) {
1283 throw new IllegalArgumentException("group.getId() and and username must not be null or empty");
1286 if (group.isDefaultGroup()) {
1287 PolicyLogger.error("The default group " + group.getId() + " was attempted to be deleted. It cannot be.");
1288 throw new PolicyDbException("You cannot delete the default group.");
1290 synchronized (emLock) {
1291 checkBeforeOperationRun();
1292 Query deleteGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1293 deleteGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
1294 deleteGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1295 List<?> deleteGroupQueryList;
1297 deleteGroupQueryList = deleteGroupQuery.list();
1298 } catch (Exception e) {
1299 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1300 "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()");
1301 throw new PersistenceException("Query failed trying to check if group exists");
1303 if (deleteGroupQueryList.isEmpty()) {
1304 logger.warn(PolicyDbDao.GROUP_NOT_FOUND + group.getId());
1306 } else if (deleteGroupQueryList.size() > 1) {
1307 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1308 throw new PersistenceException(
1309 PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1312 Query pdpsInGroupQuery =
1313 session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted");
1314 pdpsInGroupQuery.setParameter(GROUP, (deleteGroupQueryList.get(0)));
1315 pdpsInGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1316 List<?> pdpsInGroupList;
1318 pdpsInGroupList = pdpsInGroupQuery.list();
1319 } catch (Exception e) {
1320 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1321 "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()");
1322 throw new PersistenceException("Query failed trying to get PDPs in group");
1324 if (!pdpsInGroupList.isEmpty()) {
1325 if (moveToGroup != null) {
1326 Query checkMoveToGroupQuery = session
1327 .createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted");
1328 checkMoveToGroupQuery.setParameter(PolicyDbDao.GROUP_ID, moveToGroup.getId());
1329 checkMoveToGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1330 List<?> checkMoveToGroupList;
1332 checkMoveToGroupList = checkMoveToGroupQuery.list();
1333 } catch (Exception e) {
1334 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1335 "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList");
1336 throw new PersistenceException("Query failed trying to check if group exists");
1338 if (checkMoveToGroupList.isEmpty()) {
1339 PolicyLogger.error(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId());
1340 throw new PersistenceException(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId());
1341 } else if (checkMoveToGroupList.size() > 1) {
1343 PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1344 throw new PersistenceException(
1345 PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1347 GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0);
1348 for (Object pdpObject : pdpsInGroupList) {
1349 PdpEntity pdp = (PdpEntity) pdpObject;
1350 pdp.setGroup(newGroup);
1351 if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) {
1352 pdp.setModifiedBy(username);
1356 this.newGroupId = newGroup.getGroupId();
1357 } catch (PersistenceException e) {
1358 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1359 "Caught PersistenceException trying to set pdp group to null on em.flush()");
1360 throw new PersistenceException("Query failed trying to set pdp group to ");
1365 PolicyLogger.error("Group " + group.getId()
1366 + " is trying to be delted with PDPs. No group was provided to move them to");
1367 throw new PolicyDbException("Group has PDPs. Must provide a group for them to move to");
1371 // delete group here
1372 GroupEntity groupToDelete = (GroupEntity) deleteGroupQueryList.get(0);
1373 groupToDelete.setDeleted(true);
1374 if (!PolicyDbDao.stringEquals(groupToDelete.getModifiedBy(), username)) {
1375 groupToDelete.setModifiedBy(username);
1378 this.groupId = groupToDelete.getGroupKey();
1383 public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, String username)
1384 throws PolicyDbException {
1386 "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup("
1387 + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + BRACKET_CALLED);
1388 if (PolicyDbDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) {
1389 throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty");
1391 synchronized (emLock) {
1392 checkBeforeOperationRun();
1393 // check if group exists
1394 Query groupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1395 groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar);
1396 groupQuery.setParameter(PolicyDbDao.DELETED, false);
1397 List<?> groupQueryList;
1399 groupQueryList = groupQuery.list();
1400 } catch (Exception e) {
1401 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1402 "Caught Exception trying to check if group exists groupQuery.getResultList()");
1403 throw new PersistenceException("Query failed trying to check if group " + groupIdVar + EXISTS);
1405 if (groupQueryList.isEmpty()) {
1406 PolicyLogger.error("Group policy is being added to does not exist with id " + groupIdVar);
1407 throw new PersistenceException("Group policy is being added to does not exist with id " + groupIdVar);
1408 } else if (groupQueryList.size() > 1) {
1409 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1410 throw new PersistenceException(
1411 PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1414 // we need to convert the form of the policy id that is used groups
1415 // into the form that is used
1416 // for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml)
1417 PolicyDbDao policyDbDao = new PolicyDbDao();
1418 String[] policyNameScopeAndVersion = policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar);
1419 if (policyNameScopeAndVersion == null) {
1420 throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version");
1422 Query policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName "
1423 + "AND p.scope=:scope AND p.deleted=:deleted");
1424 policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]);
1425 policyQuery.setParameter(PolicyDbDao.SCOPE, policyNameScopeAndVersion[1]);
1426 policyQuery.setParameter(PolicyDbDao.DELETED, false);
1427 List<?> policyQueryList;
1429 policyQueryList = policyQuery.list();
1430 } catch (Exception e) {
1432 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1433 "Caught Exception trying to check if policy exists policyQuery.getResultList()");
1434 throw new PersistenceException(
1435 "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + EXISTS);
1437 if (policyQueryList.isEmpty()) {
1438 PolicyLogger.error("Policy being added to the group does not exist with policy id "
1439 + policyNameScopeAndVersion[0]);
1440 throw new PersistenceException("Policy being added to the group does not exist with policy id "
1441 + policyNameScopeAndVersion[0]);
1442 } else if (policyQueryList.size() > 1) {
1444 PolicyDbDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1445 throw new PersistenceException(
1446 PolicyDbDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1448 logger.info("PolicyDBDao: Getting group and policy from database");
1449 GroupEntity group = (GroupEntity) groupQueryList.get(0);
1450 PolicyEntity policy = (PolicyEntity) policyQueryList.get(0);
1451 Iterator<PolicyEntity> policyIt = group.getPolicies().iterator();
1452 String policyName = policyDbDao.getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0];
1454 logger.info("PolicyDBDao: policyName retrieved is " + policyName);
1456 while (policyIt.hasNext()) {
1457 PolicyEntity pol = policyIt.next();
1458 if (policy.getScope().equals(pol.getScope())
1459 && policyDbDao.getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0]
1460 .equals(policyName)) {
1464 } catch (Exception e) {
1466 PolicyLogger.error("Could not delete old versions for policy " + policy.getPolicyName() + ", ID: "
1467 + policy.getPolicyId());
1469 group.addPolicyToGroup(policy);
1470 auditPdpOperations(username, policy.getScope() + "." + policy.getPolicyName(), "Push");
1473 // After adding policy to the db group we need to make sure the
1474 // filesytem group is in sync with the db group
1476 StdPDPGroup pdpGroup =
1477 (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getGroupId());
1478 return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group);
1479 } catch (PAPException e) {
1481 PolicyLogger.error("PolicyDBDao: Could not synchronize the filesystem group with the database group. "
1488 // this means delete pdp not just remove from group
1490 public void removePdpFromGroup(String pdpId, String username) {
1491 logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpId + "," + username
1493 if (PolicyDbDao.isNullOrEmpty(pdpId, username)) {
1494 throw new IllegalArgumentException("pdpID and username must not be null or empty");
1496 synchronized (emLock) {
1497 checkBeforeOperationRun();
1498 Query pdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1499 pdpQuery.setParameter(PolicyDbDao.PDP_ID, pdpId);
1500 pdpQuery.setParameter(PolicyDbDao.DELETED, false);
1503 pdpList = pdpQuery.list();
1504 } catch (Exception e) {
1505 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1506 "Caught Exception trying to check if pdp exists pdpQuery.getResultList()");
1507 throw new PersistenceException("Query failed trying to check if pdp " + pdpId + EXISTS);
1509 if (pdpList.size() > 1) {
1510 PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1511 throw new PersistenceException(
1512 "Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1513 } else if (pdpList.isEmpty()) {
1514 PolicyLogger.error("Pdp being removed does not exist with id " + pdpId);
1517 PdpEntity pdp = (PdpEntity) pdpList.get(0);
1522 if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) {
1523 pdp.setModifiedBy(username);
1525 pdp.setDeleted(true);
1528 this.pdpId = pdp.getPdpKey();
1532 private static String evaluateXPath(String expression, String xml) {
1533 InputSource source = new InputSource(new StringReader(xml));
1535 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1536 String description = "";
1538 DocumentBuilder db = dbf.newDocumentBuilder();
1539 Document document = db.parse(source);
1541 XPathFactory xpathFactory = XPathFactory.newInstance();
1542 XPath xpath = xpathFactory.newXPath();
1544 description = xpath.evaluate(expression, document);
1545 } catch (Exception e) {
1546 logger.error("Exception Occured while evaluating path" + e);
1551 public static boolean isJunit() {
1555 public static void setJunit(boolean isJunit) {
1556 PolicyDbDaoTransactionInstance.isJunit = isJunit;
1560 * Audit pdp operations.
1562 * @param username the username
1563 * @param policyID the policy ID
1564 * @param action the action
1566 public void auditPdpOperations(String username, String policyID, String action) {
1567 PolicyAuditlog log = new PolicyAuditlog();
1568 log.setUserName(username);
1569 log.setActions(action);
1570 log.setPolicyName(policyID);
1571 log.setDateAndTime(new Date());