2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 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 // Using parentPath object to set policy data.
553 policyDataString = policy.policyAdapter.getParentPath();
555 String configPath = "";
556 if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
557 configPath = evaluateXPath(
558 "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/"
559 + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
561 } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
562 configPath = evaluateXPath(
563 "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, "
564 + policy.policyAdapter.getActionAttribute()
565 + ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()",
567 } else if (DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
568 configPath = evaluateXPath(
569 "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/"
570 + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
574 String prefix = null;
575 if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())
576 || DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
577 prefix = configPath.substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(),
578 configPath.lastIndexOf(policy.policyAdapter.getPolicyName()));
579 if (PolicyDbDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) {
580 String configData = "";
582 String newConfigPath = configPath;
584 newConfigPath = processConfigPath(newConfigPath);
585 } catch (Exception e2) {
586 logger.error("Could not process config path: " + newConfigPath, e2);
588 configData = readConfigFile(newConfigPath);
589 } catch (Exception e) {
590 logger.error("Could not read config body data for " + configPath, e);
592 policy.policyAdapter.setConfigBodyData(configData);
594 } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
596 } else if ("Decision".equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
597 prefix = "Decision_";
600 if (!(policy.policyAdapter.getData() instanceof PolicyType)
601 && !(policy.policyAdapter.getData() instanceof PolicySetType)) {
602 PolicyLogger.error("The data field is not an instance of PolicyType");
603 throw new IllegalArgumentException("The data field is not an instance of PolicyType");
605 String finalName = policyScope + "." + prefix + policy.policyAdapter.getPolicyName() + "."
606 + policy.policyAdapter.getHighestVersion() + ".xml";
607 if (policy.policyAdapter.getConfigType() == null || "".equals(policy.policyAdapter.getConfigType())) {
608 // get the config file extension
610 if (configPath != null && !"".equalsIgnoreCase(configPath)) {
611 ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());
614 if (ext.contains("txt")) {
615 policy.policyAdapter.setConfigType(PolicyDbDao.OTHER_CONFIG);
616 } else if (ext.contains("json")) {
617 policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG);
618 } else if (ext.contains("xml")) {
619 policy.policyAdapter.setConfigType(PolicyDbDao.XML_CONFIG);
620 } else if (ext.contains("properties")) {
621 policy.policyAdapter.setConfigType(PolicyDbDao.PROPERTIES_CONFIG);
623 if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDbDao.ACTION)) {
624 policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG);
629 createPolicy(policy.policyAdapter, username, policyScope, finalName, policyDataString);
631 if (policyXmlStream != null) {
633 policyXmlStream.close();
634 } catch (IOException e) {
635 logger.error("Exception Occured while closing input stream" + e);
641 public PolicyEntity getPolicy(int policyId) {
642 return getPolicy(policyId, null, null);
645 public PolicyEntity getPolicy(String policyName, String scope) {
646 return getPolicy(-1, policyName, scope);
649 private PolicyEntity getPolicy(int policyIdVar, String policyName, String scope) {
650 logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar + "," + policyName
652 if (policyIdVar < 0 && PolicyDbDao.isNullOrEmpty(policyName, scope)) {
653 throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank");
656 synchronized (emLock) {
657 checkBeforeOperationRun(true);
658 // check if group exists
661 if (!PolicyDbDao.isNullOrEmpty(policyName, scope)) {
662 locPolicyId = policyName;
664 session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope");
665 policyQuery.setParameter("name", locPolicyId);
666 policyQuery.setParameter("scope", scope);
668 locPolicyId = String.valueOf(policyIdVar);
669 policyQuery = session.getNamedQuery("PolicyEntity.FindById");
670 policyQuery.setParameter("id", locPolicyId);
672 List<?> policyQueryList;
674 policyQueryList = policyQuery.list();
675 } catch (Exception e) {
676 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
677 "Caught Exception trying to get policy with policyQuery.getResultList()");
678 throw new PersistenceException("Query failed trying to get policy " + locPolicyId);
681 if (policyQueryList.isEmpty()) {
682 PolicyLogger.error("Policy does not exist with id " + locPolicyId);
683 throw new PersistenceException("Group policy is being added to does not exist with id " + locPolicyId);
684 } else if (policyQueryList.size() > 1) {
685 PolicyLogger.error(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB);
686 throw new PersistenceException(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB);
688 return (PolicyEntity) policyQueryList.get(0);
693 public GroupEntity getGroup(long groupKey) {
694 logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + BRACKET_CALLED);
696 throw new IllegalArgumentException("groupKey must be at least 0");
698 synchronized (emLock) {
699 checkBeforeOperationRun(true);
700 // check if group exists
701 Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey");
702 groupQuery.setParameter("groupKey", groupKey);
703 List<?> groupQueryList;
705 groupQueryList = groupQuery.list();
706 } catch (Exception e) {
707 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
708 "Caught Exception trying to get group with groupQuery.getResultList()");
709 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupKey);
711 if (groupQueryList.isEmpty()) {
712 PolicyLogger.error("Group does not exist with groupKey " + groupKey);
713 throw new PersistenceException("Group does not exist with groupKey " + groupKey);
714 } else if (groupQueryList.size() > 1) {
716 .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB);
717 throw new PersistenceException(
718 "Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB);
720 return (GroupEntity) groupQueryList.get(0);
725 public GroupEntity getGroup(String groupId) {
726 logger.debug("getGroup(String groupId) as getGroup(" + groupId + BRACKET_CALLED);
727 if (PolicyDbDao.isNullOrEmpty(groupId)) {
728 throw new IllegalArgumentException("groupId must not be null or empty");
730 synchronized (emLock) {
731 checkBeforeOperationRun(true);
732 // check if group exists
733 Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId");
734 groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId);
735 List<?> groupQueryList;
737 groupQueryList = groupQuery.list();
738 } catch (Exception e) {
739 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
740 "Caught Exception trying to get group with groupQuery.getResultList()");
741 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupId);
743 if (groupQueryList.isEmpty()) {
744 PolicyLogger.error("Group does not exist with id " + groupId);
745 throw new PersistenceException("Group does not exist with id " + groupId);
746 } else if (groupQueryList.size() > 1) {
747 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB);
748 throw new PersistenceException(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB);
750 return (GroupEntity) groupQueryList.get(0);
755 public List<?> getPdpsInGroup(long groupKey) {
756 logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + BRACKET_CALLED);
758 throw new IllegalArgumentException("groupId must not be < 0");
760 synchronized (emLock) {
761 checkBeforeOperationRun(true);
762 Query pdpsQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group");
763 pdpsQuery.setParameter(GROUP, getGroup(groupKey));
764 return pdpsQuery.list();
769 public PdpEntity getPdp(long pdpKey) {
770 logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + BRACKET_CALLED);
772 throw new IllegalArgumentException("pdpKey must be at least 0");
774 synchronized (emLock) {
775 checkBeforeOperationRun(true);
776 // check if group exists
777 Query pdpQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey");
778 pdpQuery.setParameter("pdpKey", pdpKey);
779 List<?> pdpQueryList;
781 pdpQueryList = pdpQuery.list();
782 } catch (Exception e) {
783 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
784 "Caught Exception trying to get pdp with pdpQuery.getResultList()");
785 throw new PersistenceException("Query failed trying to get pdp " + pdpKey);
787 if (pdpQueryList.isEmpty()) {
788 PolicyLogger.error("Pdp does not exist with pdpKey " + pdpKey);
789 throw new PersistenceException("Pdp does not exist with pdpKey " + pdpKey);
790 } else if (pdpQueryList.size() > 1) {
791 PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB);
792 throw new PersistenceException(
793 "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB);
795 return (PdpEntity) pdpQueryList.get(0);
800 public boolean isTransactionOpen() {
801 logger.debug("isTransactionOpen() as isTransactionOpen() called");
802 synchronized (emLock) {
803 return session.isOpen() && session.getTransaction().isActive();
807 private String processConfigPath(String inputConfigPath) {
808 String configPath = inputConfigPath;
809 String webappsPath = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS);
810 if (webappsPath == null) {
811 logger.error("Webapps property does not exist");
812 throw new IllegalArgumentException("Webapps property does not exist");
814 configPath = configPath.replace("$URL", webappsPath);
815 // make sure the correct slashes are in
817 configPath = Paths.get(configPath).toString();
818 } catch (InvalidPathException e) {
819 logger.error("Invalid config path: " + configPath, e);
820 throw new IllegalArgumentException("Invalid config path: " + configPath);
825 private String readConfigFile(String configPath) {
826 String configDataString = null;
827 InputStream configContentStream = null;
829 configContentStream = new FileInputStream(configPath);
830 configDataString = IOUtils.toString(configContentStream);
831 } catch (FileNotFoundException e) {
832 logger.error("Caught FileNotFoundException on new FileInputStream(" + configPath + ")", e);
833 throw new IllegalArgumentException("The config file path does not exist");
834 } catch (IOException e2) {
835 logger.error("Caught IOException on newIOUtils.toString(" + configContentStream + ")", e2);
836 throw new IllegalArgumentException("The config file path cannot be read");
838 IOUtils.closeQuietly(configContentStream);
840 if (configDataString == null) {
841 throw new IllegalArgumentException("The config file path cannot be read");
843 return configDataString;
847 public void close() {
848 synchronized (emLock) {
849 if (session.isOpen()) {
850 if (session.getTransaction().isActive()) {
851 session.getTransaction().rollback();
855 if (transactionTimer != null) {
856 transactionTimer.interrupt();
862 public void createGroup(String groupId, String groupName, String inputGroupDescription, String username) {
863 String groupDescription = inputGroupDescription;
864 logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + groupName + ", "
865 + groupDescription + BRACKET_CALLED);
866 if (PolicyDbDao.isNullOrEmpty(groupId, groupName, username)) {
867 throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty");
869 if (groupDescription == null) {
870 groupDescription = "";
873 synchronized (emLock) {
874 checkBeforeOperationRun();
875 Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
876 checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId);
877 checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
878 List<?> checkGroupQueryList;
880 checkGroupQueryList = checkGroupQuery.list();
881 } catch (Exception e) {
882 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
883 "Caught Exception on checkGroupQuery.getResultList()");
884 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
886 if (!checkGroupQueryList.isEmpty()) {
887 PolicyLogger.error("The group being added already exists with id " + groupId);
888 throw new PersistenceException("The group being added already exists with id " + groupId);
890 GroupEntity newGroup = new GroupEntity();
891 newGroup.setCreatedBy(username);
892 newGroup.setModifiedBy(username);
893 newGroup.setGroupName(groupName);
894 newGroup.setGroupId(groupId);
895 newGroup.setDescription(groupDescription);
897 newGroup.prePersist();
899 session.persist(newGroup);
901 this.groupId = newGroup.getGroupKey();
906 public void updateGroup(OnapPDPGroup group, String requestType, String username) {
907 logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + "," + requestType + ","
908 + username + BRACKET_CALLED);
910 throw new IllegalArgumentException("PDPGroup group must not be null");
912 if (PolicyDbDao.isNullOrEmpty(group.getId(), requestType)) {
913 throw new IllegalArgumentException("group.getId() and username must not be null or empty");
916 synchronized (emLock) {
917 PolicyDbDao policyDbDaoVar = new PolicyDbDao();
918 checkBeforeOperationRun();
919 Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
920 getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
921 getGroupQuery.setParameter(PolicyDbDao.DELETED, false);
922 List<?> getGroupQueryList;
924 getGroupQueryList = getGroupQuery.list();
925 } catch (Exception e) {
926 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
927 "Caught Exception on getGroupQuery.getResultList()");
928 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing");
930 if (getGroupQueryList.isEmpty()) {
931 PolicyLogger.error("The group cannot be found to update with id " + group.getId());
932 throw new PersistenceException("The group cannot be found to update with id " + group.getId());
933 } else if (getGroupQueryList.size() > 1) {
934 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
935 throw new PersistenceException(
936 PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
938 GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0);
939 if (!PolicyDbDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) {
940 groupToUpdateInDb.setModifiedBy(requestType);
942 if (group.getDescription() != null
943 && !PolicyDbDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) {
944 groupToUpdateInDb.setDescription(group.getDescription());
946 // let's find out what policies have been deleted
947 StdPDPGroup oldGroup = null;
949 oldGroup = (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getId());
950 } catch (PAPException e1) {
951 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR,
952 "We cannot get the group from the papEngine to delete policies");
954 if (oldGroup == null) {
955 PolicyLogger.error("We cannot get the group from the papEngine to delete policies");
957 Set<String> newPolicySet = new HashSet<>(group.getPolicies().size());
958 // a multiple of n runtime is faster than n^2, so I am using a
959 // hashset to do the comparison
960 for (PDPPolicy pol : group.getPolicies()) {
961 newPolicySet.add(pol.getId());
963 for (PDPPolicy pol : oldGroup.getPolicies()) {
964 // should be fast since getPolicies uses a HashSet in
966 if (!newPolicySet.contains(pol.getId())) {
967 String[] scopeAndName = policyDbDaoVar.getNameScopeAndVersionFromPdpPolicy(pol.getId());
968 PolicyEntity policyToDelete = null;
970 if (scopeAndName != null) {
971 policyToDelete = getPolicy(scopeAndName[0], scopeAndName[1]);
972 if ("XACMLPapServlet.doDelete".equals(requestType)) {
973 Iterator<PolicyEntity> dbPolicyIt = groupToUpdateInDb.getPolicies().iterator();
974 String policyName = policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
975 policyToDelete.getPolicyName())[0];
977 logger.info("PolicyDBDao: delete policy from GroupEntity");
979 while (dbPolicyIt.hasNext()) {
980 PolicyEntity dbpolicy = dbPolicyIt.next();
981 if (policyToDelete.getScope().equals(dbpolicy.getScope())
982 && policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
983 dbpolicy.getPolicyName())[0].equals(policyName)) {
985 auditPdpOperations(username,
986 dbpolicy.getScope() + "." + dbpolicy.getPolicyName(), "Delete");
987 logger.info("PolicyDBDao: deleting policy from the existing group:\n "
988 + "policyName is " + policyToDelete.getScope() + "."
989 + policyToDelete.getPolicyName() + "\n" + "group is "
990 + groupToUpdateInDb.getGroupId());
993 } catch (Exception e) {
995 PolicyLogger.error("Could not delete policy with name: "
996 + policyToDelete.getScope() + "." + policyToDelete.getPolicyName()
997 + "\n ID: " + policyToDelete.getPolicyId());
1001 } catch (Exception e) {
1002 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1003 "Could not get policy to remove: " + pol.getId());
1004 throw new PersistenceException("Could not get policy to remove: " + pol.getId());
1010 if (group.getName() != null
1011 && !PolicyDbDao.stringEquals(group.getName(), groupToUpdateInDb.getGroupName())) {
1012 // we need to check if the new id exists in the database
1013 String newGrpId = PolicyDbDao.createNewPdpGroupId(group.getName());
1014 Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1015 checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, newGrpId);
1016 checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1017 List<?> checkGroupQueryList;
1019 checkGroupQueryList = checkGroupQuery.list();
1020 } catch (Exception e) {
1021 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1022 "Caught Exception on checkGroupQuery.getResultList()");
1023 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
1025 if (!checkGroupQueryList.isEmpty()) {
1026 PolicyLogger.error("The new group name already exists, group id " + newGrpId);
1027 throw new PersistenceException("The new group name already exists, group id " + newGrpId);
1029 groupToUpdateInDb.setGroupId(newGrpId);
1030 groupToUpdateInDb.setGroupName(group.getName());
1031 this.newGroupId = group.getId();
1034 this.groupId = groupToUpdateInDb.getGroupKey();
1039 public void addPdpToGroup(String pdpId, String groupIdVar, String pdpName, String pdpDescription, int pdpJmxPort,
1041 logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, "
1042 + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + pdpId + ", "
1043 + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + username
1045 if (PolicyDbDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) {
1046 throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty");
1048 synchronized (emLock) {
1049 checkBeforeOperationRun();
1050 Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1051 checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar);
1052 checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1053 List<?> checkGroupQueryList;
1055 checkGroupQueryList = checkGroupQuery.list();
1056 } catch (Exception e) {
1057 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1058 "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()");
1059 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
1061 if (checkGroupQueryList.size() != 1) {
1062 PolicyLogger.error("The group does not exist");
1063 throw new PersistenceException("The group does not exist");
1065 Query checkDuplicateQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1066 checkDuplicateQuery.setParameter(PolicyDbDao.PDP_ID, pdpId);
1067 checkDuplicateQuery.setParameter(PolicyDbDao.DELETED, false);
1068 List<?> checkDuplicateList;
1070 checkDuplicateList = checkDuplicateQuery.list();
1071 } catch (Exception e) {
1072 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1073 "Caught Exception trying to check for duplicate PDP " + pdpId
1074 + " on checkDuplicateQuery.getResultList()");
1075 throw new PersistenceException("Query failed trying to check for duplicate PDP " + pdpId);
1078 if (!checkDuplicateList.isEmpty()) {
1079 logger.warn("PDP already exists with id " + pdpId);
1080 newPdp = (PdpEntity) checkDuplicateList.get(0);
1082 newPdp = new PdpEntity();
1085 newPdp.setCreatedBy(username);
1086 newPdp.setDeleted(false);
1087 newPdp.setDescription(pdpDescription);
1088 newPdp.setGroup((GroupEntity) checkGroupQueryList.get(0));
1089 newPdp.setJmxPort(pdpJmxPort);
1090 newPdp.setModifiedBy(username);
1091 newPdp.setPdpId(pdpId);
1092 newPdp.setPdpName(pdpName);
1094 newPdp.prePersist();
1096 session.persist(newPdp);
1098 this.pdpId = newPdp.getPdpKey();
1103 public void updatePdp(OnapPDP pdp, String username) {
1104 logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + BRACKET_CALLED);
1106 throw new IllegalArgumentException("PDP pdp must not be null");
1108 if (PolicyDbDao.isNullOrEmpty(pdp.getId(), username)) {
1109 throw new IllegalArgumentException("pdp.getId() and username must not be null or empty");
1112 synchronized (emLock) {
1113 checkBeforeOperationRun();
1114 Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1115 getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId());
1116 getPdpQuery.setParameter(PolicyDbDao.DELETED, false);
1117 List<?> getPdpQueryList;
1119 getPdpQueryList = getPdpQuery.list();
1120 } catch (Exception e) {
1121 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1122 "Caught Exception on getPdpQuery.getResultList()");
1123 throw new PersistenceException("Query failed trying to get PDP " + pdp.getId());
1125 if (getPdpQueryList.isEmpty()) {
1126 PolicyLogger.error("The pdp cannot be found to update with id " + pdp.getId());
1127 throw new PersistenceException("The pdp cannot be found to update with id " + pdp.getId());
1128 } else if (getPdpQueryList.size() > 1) {
1129 PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1130 throw new PersistenceException(
1131 PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1133 PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1134 if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1135 pdpToUpdate.setModifiedBy(username);
1137 if (pdp.getDescription() != null
1138 && !PolicyDbDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) {
1139 pdpToUpdate.setDescription(pdp.getDescription());
1141 if (pdp.getName() != null && !PolicyDbDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) {
1142 pdpToUpdate.setPdpName(pdp.getName());
1144 if (pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())) {
1145 pdpToUpdate.setJmxPort(pdp.getJmxPort());
1149 this.pdpId = pdpToUpdate.getPdpKey();
1154 public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) {
1155 logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + "," + group + ","
1156 + username + BRACKET_CALLED);
1157 if (pdp == null || group == null) {
1158 throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null");
1160 if (PolicyDbDao.isNullOrEmpty(username, pdp.getId(), group.getId())) {
1161 throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty");
1164 synchronized (emLock) {
1165 checkBeforeOperationRun();
1166 // check if pdp exists
1167 Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1168 getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId());
1169 getPdpQuery.setParameter(PolicyDbDao.DELETED, false);
1170 List<?> getPdpQueryList;
1172 getPdpQueryList = getPdpQuery.list();
1173 } catch (Exception e) {
1174 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1175 "Caught Exception on getPdpQuery.getResultList()");
1176 throw new PersistenceException("Query failed trying to get pdp to move with id " + pdp.getId());
1178 if (getPdpQueryList.isEmpty()) {
1179 PolicyLogger.error("The pdp cannot be found to move with id " + pdp.getId());
1180 throw new PersistenceException("The pdp cannot be found to move with id " + pdp.getId());
1181 } else if (getPdpQueryList.size() > 1) {
1182 PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1183 throw new PersistenceException(
1184 PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1187 // check if new group exists
1188 Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1189 checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
1190 checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1191 List<?> checkGroupQueryList;
1193 checkGroupQueryList = checkGroupQuery.list();
1194 } catch (Exception e) {
1195 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1196 "Caught Exception trying to get group on checkGroupQuery.getResultList()");
1197 throw new PersistenceException("Query failed trying to get new group " + group.getId());
1199 if (checkGroupQueryList.size() != 1) {
1200 PolicyLogger.error("The group " + group.getId() + " does not exist");
1201 throw new PersistenceException("The group " + group.getId() + " does not exist");
1203 GroupEntity groupToMoveInto = (GroupEntity) checkGroupQueryList.get(0);
1204 PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1205 pdpToUpdate.setGroup(groupToMoveInto);
1206 if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1207 pdpToUpdate.setModifiedBy(username);
1211 this.pdpId = pdpToUpdate.getPdpKey();
1216 public void changeDefaultGroup(OnapPDPGroup group, String username) {
1217 logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + ","
1218 + username + BRACKET_CALLED);
1219 if (group == null) {
1220 throw new IllegalArgumentException("PDPGroup group must not be null");
1222 if (PolicyDbDao.isNullOrEmpty(group.getId(), username)) {
1223 throw new IllegalArgumentException("group.getId() and username must not be null or empty");
1226 synchronized (emLock) {
1227 checkBeforeOperationRun();
1228 Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1229 getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
1230 getGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1231 List<?> getGroupQueryList;
1233 getGroupQueryList = getGroupQuery.list();
1234 } catch (Exception e) {
1235 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1236 "Caught Exception on getGroupQuery.getResultList()");
1237 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId());
1239 if (getGroupQueryList.isEmpty()) {
1240 PolicyLogger.error("The group cannot be found to set default with id " + group.getId());
1241 throw new PersistenceException("The group cannot be found to set default with id " + group.getId());
1242 } else if (getGroupQueryList.size() > 1) {
1243 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1244 throw new PersistenceException(
1245 PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1247 GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0);
1248 newDefaultGroup.setDefaultGroup(true);
1249 if (!PolicyDbDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) {
1250 newDefaultGroup.setModifiedBy(username);
1254 this.groupId = newDefaultGroup.getGroupKey();
1255 Query setAllGroupsNotDefault = session.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup "
1256 + "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey");
1257 // not going to set modified by for all groups
1258 setAllGroupsNotDefault.setParameter("defaultGroup", false);
1259 setAllGroupsNotDefault.setParameter(PolicyDbDao.DELETED, false);
1260 setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey());
1262 logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default");
1263 } catch (Exception e) {
1264 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1265 "Caught Exception on setAllGroupsNotDefault.executeUpdate()");
1266 throw new PersistenceException("Could not set all other groups default to false");
1273 public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDbException {
1274 logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup(" + group + ", "
1275 + moveToGroup + "," + username + BRACKET_CALLED);
1276 if (group == null) {
1277 throw new IllegalArgumentException("PDPGroup group cannot be null");
1279 if (PolicyDbDao.isNullOrEmpty(username, group.getId())) {
1280 throw new IllegalArgumentException("group.getId() and and username must not be null or empty");
1283 if (group.isDefaultGroup()) {
1284 PolicyLogger.error("The default group " + group.getId() + " was attempted to be deleted. It cannot be.");
1285 throw new PolicyDbException("You cannot delete the default group.");
1287 synchronized (emLock) {
1288 checkBeforeOperationRun();
1289 Query deleteGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1290 deleteGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
1291 deleteGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1292 List<?> deleteGroupQueryList;
1294 deleteGroupQueryList = deleteGroupQuery.list();
1295 } catch (Exception e) {
1296 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1297 "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()");
1298 throw new PersistenceException("Query failed trying to check if group exists");
1300 if (deleteGroupQueryList.isEmpty()) {
1301 logger.warn(PolicyDbDao.GROUP_NOT_FOUND + group.getId());
1303 } else if (deleteGroupQueryList.size() > 1) {
1304 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1305 throw new PersistenceException(
1306 PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1309 Query pdpsInGroupQuery =
1310 session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted");
1311 pdpsInGroupQuery.setParameter(GROUP, (deleteGroupQueryList.get(0)));
1312 pdpsInGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1313 List<?> pdpsInGroupList;
1315 pdpsInGroupList = pdpsInGroupQuery.list();
1316 } catch (Exception e) {
1317 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1318 "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()");
1319 throw new PersistenceException("Query failed trying to get PDPs in group");
1321 if (!pdpsInGroupList.isEmpty()) {
1322 if (moveToGroup != null) {
1323 Query checkMoveToGroupQuery = session
1324 .createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted");
1325 checkMoveToGroupQuery.setParameter(PolicyDbDao.GROUP_ID, moveToGroup.getId());
1326 checkMoveToGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1327 List<?> checkMoveToGroupList;
1329 checkMoveToGroupList = checkMoveToGroupQuery.list();
1330 } catch (Exception e) {
1331 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1332 "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList");
1333 throw new PersistenceException("Query failed trying to check if group exists");
1335 if (checkMoveToGroupList.isEmpty()) {
1336 PolicyLogger.error(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId());
1337 throw new PersistenceException(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId());
1338 } else if (checkMoveToGroupList.size() > 1) {
1340 PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1341 throw new PersistenceException(
1342 PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1344 GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0);
1345 for (Object pdpObject : pdpsInGroupList) {
1346 PdpEntity pdp = (PdpEntity) pdpObject;
1347 pdp.setGroup(newGroup);
1348 if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) {
1349 pdp.setModifiedBy(username);
1353 this.newGroupId = newGroup.getGroupId();
1354 } catch (PersistenceException e) {
1355 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1356 "Caught PersistenceException trying to set pdp group to null on em.flush()");
1357 throw new PersistenceException("Query failed trying to set pdp group to ");
1362 PolicyLogger.error("Group " + group.getId()
1363 + " is trying to be delted with PDPs. No group was provided to move them to");
1364 throw new PolicyDbException("Group has PDPs. Must provide a group for them to move to");
1368 // delete group here
1369 GroupEntity groupToDelete = (GroupEntity) deleteGroupQueryList.get(0);
1370 groupToDelete.setDeleted(true);
1371 if (!PolicyDbDao.stringEquals(groupToDelete.getModifiedBy(), username)) {
1372 groupToDelete.setModifiedBy(username);
1375 this.groupId = groupToDelete.getGroupKey();
1380 public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, String username)
1381 throws PolicyDbException {
1383 "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup("
1384 + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + BRACKET_CALLED);
1385 if (PolicyDbDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) {
1386 throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty");
1388 synchronized (emLock) {
1389 checkBeforeOperationRun();
1390 // check if group exists
1391 Query groupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1392 groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar);
1393 groupQuery.setParameter(PolicyDbDao.DELETED, false);
1394 List<?> groupQueryList;
1396 groupQueryList = groupQuery.list();
1397 } catch (Exception e) {
1398 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1399 "Caught Exception trying to check if group exists groupQuery.getResultList()");
1400 throw new PersistenceException("Query failed trying to check if group " + groupIdVar + EXISTS);
1402 if (groupQueryList.isEmpty()) {
1403 PolicyLogger.error("Group policy is being added to does not exist with id " + groupIdVar);
1404 throw new PersistenceException("Group policy is being added to does not exist with id " + groupIdVar);
1405 } else if (groupQueryList.size() > 1) {
1406 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1407 throw new PersistenceException(
1408 PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1411 // we need to convert the form of the policy id that is used groups
1412 // into the form that is used
1413 // for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml)
1414 PolicyDbDao policyDbDao = new PolicyDbDao();
1415 String[] policyNameScopeAndVersion = policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar);
1416 if (policyNameScopeAndVersion == null) {
1417 throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version");
1419 Query policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName "
1420 + "AND p.scope=:scope AND p.deleted=:deleted");
1421 policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]);
1422 policyQuery.setParameter(PolicyDbDao.SCOPE, policyNameScopeAndVersion[1]);
1423 policyQuery.setParameter(PolicyDbDao.DELETED, false);
1424 List<?> policyQueryList;
1426 policyQueryList = policyQuery.list();
1427 } catch (Exception e) {
1429 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1430 "Caught Exception trying to check if policy exists policyQuery.getResultList()");
1431 throw new PersistenceException(
1432 "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + EXISTS);
1434 if (policyQueryList.isEmpty()) {
1435 PolicyLogger.error("Policy being added to the group does not exist with policy id "
1436 + policyNameScopeAndVersion[0]);
1437 throw new PersistenceException("Policy being added to the group does not exist with policy id "
1438 + policyNameScopeAndVersion[0]);
1439 } else if (policyQueryList.size() > 1) {
1441 PolicyDbDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1442 throw new PersistenceException(
1443 PolicyDbDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1445 logger.info("PolicyDBDao: Getting group and policy from database");
1446 GroupEntity group = (GroupEntity) groupQueryList.get(0);
1447 PolicyEntity policy = (PolicyEntity) policyQueryList.get(0);
1448 Iterator<PolicyEntity> policyIt = group.getPolicies().iterator();
1449 String policyName = policyDbDao.getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0];
1451 logger.info("PolicyDBDao: policyName retrieved is " + policyName);
1453 while (policyIt.hasNext()) {
1454 PolicyEntity pol = policyIt.next();
1455 if (policy.getScope().equals(pol.getScope())
1456 && policyDbDao.getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0]
1457 .equals(policyName)) {
1461 } catch (Exception e) {
1463 PolicyLogger.error("Could not delete old versions for policy " + policy.getPolicyName() + ", ID: "
1464 + policy.getPolicyId());
1466 group.addPolicyToGroup(policy);
1467 auditPdpOperations(username, policy.getScope() + "." + policy.getPolicyName(), "Push");
1470 // After adding policy to the db group we need to make sure the
1471 // filesytem group is in sync with the db group
1473 StdPDPGroup pdpGroup =
1474 (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getGroupId());
1475 return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group);
1476 } catch (PAPException e) {
1478 PolicyLogger.error("PolicyDBDao: Could not synchronize the filesystem group with the database group. "
1485 // this means delete pdp not just remove from group
1487 public void removePdpFromGroup(String pdpId, String username) {
1488 logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpId + "," + username
1490 if (PolicyDbDao.isNullOrEmpty(pdpId, username)) {
1491 throw new IllegalArgumentException("pdpID and username must not be null or empty");
1493 synchronized (emLock) {
1494 checkBeforeOperationRun();
1495 Query pdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1496 pdpQuery.setParameter(PolicyDbDao.PDP_ID, pdpId);
1497 pdpQuery.setParameter(PolicyDbDao.DELETED, false);
1500 pdpList = pdpQuery.list();
1501 } catch (Exception e) {
1502 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1503 "Caught Exception trying to check if pdp exists pdpQuery.getResultList()");
1504 throw new PersistenceException("Query failed trying to check if pdp " + pdpId + EXISTS);
1506 if (pdpList.size() > 1) {
1507 PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1508 throw new PersistenceException(
1509 "Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1510 } else if (pdpList.isEmpty()) {
1511 PolicyLogger.error("Pdp being removed does not exist with id " + pdpId);
1514 PdpEntity pdp = (PdpEntity) pdpList.get(0);
1519 if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) {
1520 pdp.setModifiedBy(username);
1522 pdp.setDeleted(true);
1525 this.pdpId = pdp.getPdpKey();
1529 private static String evaluateXPath(String expression, String xml) {
1530 InputSource source = new InputSource(new StringReader(xml));
1532 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1533 String description = "";
1535 DocumentBuilder db = dbf.newDocumentBuilder();
1536 Document document = db.parse(source);
1538 XPathFactory xpathFactory = XPathFactory.newInstance();
1539 XPath xpath = xpathFactory.newXPath();
1541 description = xpath.evaluate(expression, document);
1542 } catch (Exception e) {
1543 logger.error("Exception Occured while evaluating path" + e);
1548 public static boolean isJunit() {
1552 public static void setJunit(boolean isJunit) {
1553 PolicyDbDaoTransactionInstance.isJunit = isJunit;
1557 * Audit pdp operations.
1559 * @param username the username
1560 * @param policyID the policy ID
1561 * @param action the action
1563 public void auditPdpOperations(String username, String policyID, String action) {
1564 PolicyAuditlog log = new PolicyAuditlog();
1565 log.setUserName(username);
1566 log.setActions(action);
1567 log.setPolicyName(policyID);
1568 log.setDateAndTime(new Date());