Merge "Auditing User Operations Push or Delete Policies."
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / PolicyDbDaoTransactionInstance.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pap.xacml.rest.components;
22
23 import com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.api.pap.PDPPolicy;
25 import com.att.research.xacml.util.XACMLProperties;
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.StringReader;
32 import java.nio.file.InvalidPathException;
33 import java.nio.file.Paths;
34 import java.util.Date;
35 import java.util.HashSet;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Set;
39 import javax.persistence.PersistenceException;
40 import javax.persistence.RollbackException;
41 import javax.xml.parsers.DocumentBuilder;
42 import javax.xml.parsers.DocumentBuilderFactory;
43 import javax.xml.xpath.XPath;
44 import javax.xml.xpath.XPathFactory;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
47 import org.apache.commons.io.FilenameUtils;
48 import org.apache.commons.io.IOUtils;
49 import org.hibernate.Query;
50 import org.hibernate.Session;
51 import org.hibernate.SessionFactory;
52 import org.onap.policy.common.logging.eelf.MessageCodes;
53 import org.onap.policy.common.logging.eelf.PolicyLogger;
54 import org.onap.policy.common.logging.flexlogger.FlexLogger;
55 import org.onap.policy.common.logging.flexlogger.Logger;
56 import org.onap.policy.rest.XACMLRestProperties;
57 import org.onap.policy.rest.adapter.PolicyRestAdapter;
58 import org.onap.policy.rest.dao.PolicyDBException;
59 import org.onap.policy.rest.jpa.ActionBodyEntity;
60 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
61 import org.onap.policy.rest.jpa.GroupEntity;
62 import org.onap.policy.rest.jpa.PdpEntity;
63 import org.onap.policy.rest.jpa.PolicyAuditlog;
64 import org.onap.policy.rest.jpa.PolicyEntity;
65 import org.onap.policy.xacml.api.pap.OnapPDP;
66 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
67 import org.onap.policy.xacml.std.pap.StdPDPGroup;
68 import org.onap.policy.xacml.util.XACMLPolicyWriter;
69 import org.springframework.beans.factory.annotation.Autowired;
70 import org.springframework.stereotype.Component;
71 import org.w3c.dom.Document;
72 import org.xml.sax.InputSource;
73
74
75 @Component
76 public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
77
78     private static final Logger logger = FlexLogger.getLogger(PolicyDbDaoTransactionInstance.class);
79
80     private final Object emLock = new Object();
81     long policyId;
82     long groupId;
83     long pdpId;
84     String newGroupId;
85     private boolean operationRun = false;
86     private Thread transactionTimer;
87     private static final String POLICY_NOTIFICATION = "policy";
88     private static final String PDP_NOTIFICATION = "pdp";
89     private static final String GROUP_NOTIFICATION = "group";
90
91
92     private static final String DECISIONMS_MODEL = "MicroService_Model";
93     private static boolean isJunit = false;
94     Session session;
95
96     /**
97      * Instantiates a new policy DB dao transaction instance.
98      *
99      * @param test the test
100      */
101     public PolicyDbDaoTransactionInstance(String test) {
102         // call the constructor with arguments
103         this(Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)),
104                 Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)));
105     }
106
107     public PolicyDbDaoTransactionInstance() {
108         // Default Constructor
109     }
110
111     @Autowired
112     public PolicyDbDaoTransactionInstance(SessionFactory sessionfactory) {
113         PolicyDbDaoTransactionInstance.sessionfactory = sessionfactory;
114     }
115
116     private static SessionFactory sessionfactory;
117
118
119     /**
120      * Instantiates a new policy DB dao transaction instance.
121      *
122      * @param transactionTimeout the transaction timeout is how long the transaction can sit before rolling back
123      * @param transactionWaitTime the transaction wait time is how long to wait for the transaction to start before
124      */
125     public PolicyDbDaoTransactionInstance(int transactionTimeout, int transactionWaitTime) {
126         logger.info("\n\nPolicyDBDaoTransactionInstance() as PolicyDBDaoTransactionInstance() called:"
127                 + "\n   transactionTimeout = " + transactionTimeout + "\n   transactionWaitTime = "
128                 + transactionWaitTime + "\n\n");
129
130         policyId = -1;
131         groupId = -1;
132         pdpId = -1;
133         newGroupId = null;
134         synchronized (emLock) {
135             session = sessionfactory.openSession();
136             try {
137                 PolicyDBDao.getPolicyDBDaoInstance().startTransactionSynced(session, transactionWaitTime);
138             } catch (Exception e) {
139                 logger.error("Could not lock transaction within " + transactionWaitTime + " milliseconds" + e);
140                 throw new PersistenceException(
141                         "Could not lock transaction within " + transactionWaitTime + " milliseconds");
142             }
143         }
144         class TransactionTimer implements Runnable {
145
146             private int sleepTime;
147
148             public TransactionTimer(int timeout) {
149                 this.sleepTime = timeout;
150             }
151
152             @Override
153             public void run() {
154                 if (logger.isDebugEnabled()) {
155                     Date date = new java.util.Date();
156                     logger.debug("\n\nTransactionTimer.run() - SLEEPING: " + "\n   sleepTime (ms) = " + sleepTime
157                             + "\n   TimeStamp  = " + date.getTime() + "\n\n");
158                 }
159                 try {
160                     Thread.sleep(sleepTime);
161                 } catch (InterruptedException e) {
162                     // probably, the transaction was completed, the last thing
163                     // we want to do is roll back
164                     if (logger.isDebugEnabled()) {
165                         Date date = new java.util.Date();
166                         logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: " + "\n   TimeStamp = "
167                                 + date.getTime() + "\n\n");
168                     }
169                     Thread.currentThread().interrupt();
170                     return;
171                 }
172                 if (logger.isDebugEnabled()) {
173                     Date date = new java.util.Date();
174                     logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " + "\n   TimeStamp = " + date.getTime()
175                             + "\n\n");
176                 }
177                 logger.warn("PolicyDBDaoTransactionInstance - TransactionTimer - Rolling back transaction.");
178                 rollbackTransaction();
179             }
180
181         }
182
183         transactionTimer = new Thread(new TransactionTimer(transactionTimeout), "transactionTimerThread");
184         transactionTimer.start();
185
186     }
187
188     private void checkBeforeOperationRun() {
189         checkBeforeOperationRun(false);
190     }
191
192     private void checkBeforeOperationRun(boolean justCheckOpen) {
193         if (!isTransactionOpen()) {
194             PolicyLogger.warn("checkBeforeOperationRun - There is no transaction currently open");
195             throw new IllegalStateException("There is no transaction currently open");
196         }
197         if (operationRun && !justCheckOpen) {
198             PolicyLogger.warn("checkBeforeOperationRun - "
199                     + "An operation has already been performed and the current transaction should be committed");
200             throw new IllegalStateException(
201                     "An operation has already been performed and the current transaction should be committed");
202         }
203         operationRun = true;
204     }
205
206     @Override
207     public void commitTransaction() {
208         synchronized (emLock) {
209             NotifyOtherPaps otherPaps = new NotifyOtherPaps();
210             logger.debug("commitTransaction() as commitTransaction() called");
211             if (!isTransactionOpen()) {
212                 logger.warn(
213                         "There is no open transaction to commit - PolicyId - " + policyId + ", GroupId - " + groupId);
214                 try {
215                     session.close();
216                 } catch (Exception e) {
217                     logger.error("Exception Occured" + e);
218                 }
219                 return;
220             }
221             try {
222                 session.getTransaction().commit();
223             } catch (RollbackException e) {
224                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
225                         "Caught RollbackException on em.getTransaction().commit()");
226                 throw new PersistenceException("The commit failed. Message:\n" + e.getMessage());
227             }
228             session.close();
229             // need to revisit
230             if (policyId >= 0) {
231                 if (newGroupId != null) {
232                     try {
233                         otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION, newGroupId);
234                     } catch (Exception e) {
235                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
236                                 "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ","
237                                         + newGroupId + ")");
238                     }
239                 } else {
240                     try {
241                         otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION);
242                     } catch (Exception e) {
243                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
244                                 "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ")");
245                     }
246                 }
247             }
248             if (groupId >= 0) {
249                 // we don't want commit to fail just because this does
250                 if (newGroupId != null) {
251                     try {
252                         otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION, newGroupId);
253                     } catch (Exception e) {
254                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
255                                 "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ","
256                                         + newGroupId + ")");
257                     }
258                 } else {
259                     try {
260                         otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION);
261                     } catch (Exception e) {
262                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
263                                 "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ")");
264                     }
265                 }
266             }
267             if (pdpId >= 0) {
268                 // we don't want commit to fail just because this does
269                 try {
270                     otherPaps.notifyOthers(pdpId, PDP_NOTIFICATION);
271                 } catch (Exception e) {
272                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
273                             "Caught Exception on notifyOthers(" + pdpId + "," + PDP_NOTIFICATION + ")");
274                 }
275             }
276         }
277         if (transactionTimer != null) {
278             transactionTimer.interrupt();
279         }
280     }
281
282     @Override
283     public void rollbackTransaction() {
284         logger.debug("rollbackTransaction() as rollbackTransaction() called");
285         synchronized (emLock) {
286             if (isTransactionOpen()) {
287                 try {
288                     session.getTransaction().rollback();
289                 } catch (Exception e) {
290                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
291                             "Could not rollback transaction");
292                 }
293                 try {
294                     session.close();
295                 } catch (Exception e) {
296                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
297                             "Could not close Hibernate Session.");
298                 }
299
300             } else {
301                 try {
302                     session.close();
303                 } catch (Exception e) {
304                     logger.warn("Could not close already closed transaction", e);
305                 }
306             }
307         }
308         if (transactionTimer != null) {
309             transactionTimer.interrupt();
310         }
311     }
312
313     private void createPolicy(PolicyRestAdapter policy, String username, String policyScope, String inputPolicyName,
314             String policyDataString) {
315         String policyName = inputPolicyName;
316         logger.debug("createPolicy(PolicyRestAdapter policy, String username, String policyScope,"
317                 + " String policyName, String policyDataString) as createPolicy(" + policy + ", " + username + ", "
318                 + policyScope + ", " + policyName + ", " + policyDataString + ")  called");
319         synchronized (emLock) {
320             PolicyDBDao policyDbDao = new PolicyDBDao();
321             checkBeforeOperationRun();
322             String configName = policyName;
323             if (policyName.contains("Config_")) {
324                 policyName = policyName.replace(".Config_", ":Config_");
325             } else if (policyName.contains("Action_")) {
326                 policyName = policyName.replace(".Action_", ":Action_");
327             } else if (policyName.contains("Decision_MS_")) {
328                 policyName = policyName.replace(".Decision_MS_", ":Decision_MS_");
329             } else if (policyName.contains("Decision_")) {
330                 policyName = policyName.replace(".Decision_", ":Decision_");
331             }
332             policyName = policyName.split(":")[1];
333             Query createPolicyQuery = session
334                     .createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
335             createPolicyQuery.setParameter(PolicyDBDao.SCOPE, policyScope);
336             createPolicyQuery.setParameter("policyName", policyName);
337             List<?> createPolicyQueryList = createPolicyQuery.list();
338             PolicyEntity newPolicyEntity;
339             boolean update;
340             if (createPolicyQueryList.isEmpty()) {
341                 newPolicyEntity = new PolicyEntity();
342                 update = false;
343             } else if (createPolicyQueryList.size() > 1) {
344                 PolicyLogger.error("Somehow, more than one policy with the same "
345                         + "scope, name, and deleted status were found in the database");
346                 throw new PersistenceException("Somehow, more than one policy with the same"
347                         + " scope, name, and deleted status were found in the database");
348             } else {
349                 newPolicyEntity = (PolicyEntity) createPolicyQueryList.get(0);
350                 update = true;
351             }
352
353             ActionBodyEntity newActionBodyEntity = null;
354             if (policy.getPolicyType().equals(PolicyDBDao.ACTION)) {
355                 boolean abupdate = false;
356                 if (newPolicyEntity.getActionBodyEntity() == null) {
357                     newActionBodyEntity = new ActionBodyEntity();
358                 } else {
359                     newActionBodyEntity = (ActionBodyEntity) session.get(ActionBodyEntity.class,
360                             newPolicyEntity.getActionBodyEntity().getActionBodyId());
361                     abupdate = true;
362                 }
363
364                 if (newActionBodyEntity != null) {
365                     // build the file path
366                     // trim the .xml off the end
367                     String policyNameClean = FilenameUtils.removeExtension(configName);
368                     String actionBodyName = policyNameClean + ".json";
369
370                     // get the action body
371                     String actionBodyString = policy.getActionBody();
372                     if (actionBodyString == null) {
373                         actionBodyString = "{}";
374                     }
375                     newActionBodyEntity.setActionBody(actionBodyString);
376                     newActionBodyEntity.setActionBodyName(actionBodyName);
377                     newActionBodyEntity.setModifiedBy("PolicyDBDao.createPolicy()");
378                     newActionBodyEntity.setDeleted(false);
379                     if (!abupdate) {
380                         newActionBodyEntity.setCreatedBy("PolicyDBDao.createPolicy()");
381                     }
382                     if (logger.isDebugEnabled()) {
383                         logger.debug("\nPolicyDBDao.createPolicy" + "\n   newActionBodyEntity.getActionBody() = "
384                                 + newActionBodyEntity.getActionBody()
385                                 + "\n   newActionBodyEntity.getActionBodyName() = "
386                                 + newActionBodyEntity.getActionBodyName()
387                                 + "\n   newActionBodyEntity.getModifiedBy() = " + newActionBodyEntity.getModifiedBy()
388                                 + "\n   newActionBodyEntity.getCreatedBy() = " + newActionBodyEntity.getCreatedBy()
389                                 + "\n   newActionBodyEntity.isDeleted() = " + newActionBodyEntity.isDeleted()
390                                 + "\n   FLUSHING to DB");
391                     }
392                     // push the actionBodyEntity to the DB
393                     if (isJunit) {
394                         newActionBodyEntity.prePersist();
395                     }
396                     if (!abupdate) {
397                         session.persist(newActionBodyEntity);
398                     }
399                 } else {
400                     // newActionBodyEntity == null
401                     // We have a actionBody in the policy but we found no
402                     // actionBody in the DB
403                     String msg = "\n\nPolicyDBDao.createPolicy - Incoming Action policy had an "
404                             + "actionBody, but it could not be found in the DB for update." + "\n  policyScope = "
405                             + policyScope + "\n  policyName = " + policyName + "\n\n";
406                     PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, "
407                             + "but it could not be found in the DB for update: policyName = " + policyName);
408                     throw new IllegalArgumentException(msg);
409                 }
410             }
411
412             ConfigurationDataEntity newConfigurationDataEntity;
413             if (PolicyDBDao.CONFIG.equals(policy.getPolicyType())
414                     || DECISIONMS_MODEL.equals(policy.getRuleProvider())) {
415                 boolean configUpdate;
416                 if (newPolicyEntity.getConfigurationData() == null) {
417                     newConfigurationDataEntity = new ConfigurationDataEntity();
418                     configUpdate = false;
419                 } else {
420                     newConfigurationDataEntity = (ConfigurationDataEntity) session.get(ConfigurationDataEntity.class,
421                             newPolicyEntity.getConfigurationData().getConfigurationDataId());
422                     configUpdate = true;
423                 }
424
425                 if (newConfigurationDataEntity != null) {
426                     if (!PolicyDBDao.stringEquals(newConfigurationDataEntity.getConfigurationName(),
427                             policyDbDao.getConfigFile(configName, policy))) {
428                         newConfigurationDataEntity.setConfigurationName(policyDbDao.getConfigFile(configName, policy));
429                     }
430                     if (newConfigurationDataEntity.getConfigType() == null
431                             || !newConfigurationDataEntity.getConfigType().equals(policy.getConfigType())) {
432                         newConfigurationDataEntity.setConfigType(policy.getConfigType());
433                     }
434                     if (!configUpdate) {
435                         newConfigurationDataEntity.setCreatedBy(username);
436                     }
437                     if (newConfigurationDataEntity.getModifiedBy() == null
438                             || !newConfigurationDataEntity.getModifiedBy().equals(username)) {
439                         newConfigurationDataEntity.setModifiedBy(username);
440                     }
441                     if (newConfigurationDataEntity.getDescription() == null
442                             || !newConfigurationDataEntity.getDescription().equals("")) {
443                         newConfigurationDataEntity.setDescription("");
444                     }
445                     if (newConfigurationDataEntity.getConfigBody() == null
446                             || newConfigurationDataEntity.getConfigBody().isEmpty()
447                             || (!newConfigurationDataEntity.getConfigBody().equals(policy.getConfigBodyData()))) {
448                         // hopefully one of these won't be null
449                         if (policy.getConfigBodyData() == null || policy.getConfigBodyData().isEmpty()) {
450                             newConfigurationDataEntity.setConfigBody(policy.getJsonBody());
451                         } else {
452                             newConfigurationDataEntity.setConfigBody(policy.getConfigBodyData());
453                         }
454                     }
455                     if (newConfigurationDataEntity.isDeleted()) {
456                         newConfigurationDataEntity.setDeleted(false);
457                     }
458                     if (isJunit) {
459                         newConfigurationDataEntity.prePersist();
460                     }
461                     if (!configUpdate) {
462                         session.persist(newConfigurationDataEntity);
463                     }
464                 } else {
465                     // We have a configurationData body in the policy but we
466                     // found no configurationData body in the DB
467                     String msg = "\n\nPolicyDBDao.createPolicy - Incoming Config policy had a "
468                             + "configurationData body, but it could not be found in the DB for update."
469                             + "\n  policyScope = " + policyScope + "\n  policyName = " + policyName + "\n\n";
470                     PolicyLogger
471                             .error("PolicyDBDao.createPolicy - Incoming Config policy had a configurationData body, "
472                                     + "but it could not be found in the DB for update: policyName = " + policyName);
473                     throw new IllegalArgumentException(msg);
474                 }
475
476             } else {
477                 newConfigurationDataEntity = null;
478             }
479             policyId = newPolicyEntity.getPolicyId();
480
481             if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) {
482                 newPolicyEntity.setPolicyName(policyName);
483             }
484             if (!PolicyDBDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) {
485                 newPolicyEntity.setCreatedBy(username);
486             }
487             if (!PolicyDBDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) {
488                 newPolicyEntity.setDescription(policy.getPolicyDescription());
489             }
490             if (!PolicyDBDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) {
491                 newPolicyEntity.setModifiedBy(username);
492             }
493             if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) {
494                 newPolicyEntity.setPolicyData(policyDataString);
495             }
496             if (!PolicyDBDao.stringEquals(newPolicyEntity.getScope(), policyScope)) {
497                 newPolicyEntity.setScope(policyScope);
498             }
499             if (newPolicyEntity.isDeleted()) {
500                 newPolicyEntity.setDeleted(false);
501             }
502             newPolicyEntity.setConfigurationData(newConfigurationDataEntity);
503             newPolicyEntity.setActionBodyEntity(newActionBodyEntity);
504             if (isJunit) {
505                 newPolicyEntity.prePersist();
506             }
507             if (!update) {
508                 session.persist(newPolicyEntity);
509             }
510             session.flush();
511             this.policyId = newPolicyEntity.getPolicyId();
512         }
513         return;
514     }
515
516     @Override
517     public void createPolicy(Policy policy, String username) {
518         InputStream policyXmlStream = null;
519         try {
520             logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + policy + ","
521                     + username + ") called");
522             String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, ".");
523             // Does not need to be XACMLPolicyWriterWithPapNotify since it is
524             // already in the PAP
525             // and this transaction is intercepted up stream.
526             String policyDataString;
527
528             try {
529                 if (policy.policyAdapter.getData() instanceof PolicySetType) {
530                     policyXmlStream = XACMLPolicyWriter
531                             .getPolicySetXmlAsInputStream((PolicySetType) policy.getCorrectPolicyDataObject());
532                 } else {
533                     policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policy.getCorrectPolicyDataObject());
534                 }
535                 policyDataString = IOUtils.toString(policyXmlStream);
536             } catch (IOException e) {
537                 policyDataString = "could not read";
538                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
539                         "Caught IOException on IOUtils.toString(" + policyXmlStream + ")");
540                 throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter.");
541             }
542
543             IOUtils.closeQuietly(policyXmlStream);
544             if (PolicyDBDao.isJunit()) {
545                 // Using parentPath object to set policy data.
546                 policyDataString = policy.policyAdapter.getParentPath();
547             }
548             String configPath = "";
549             if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
550                 configPath = evaluateXPath(
551                         "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
552                         policyDataString);
553             } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
554                 configPath = evaluateXPath(
555                         "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, "
556                                 + policy.policyAdapter.getActionAttribute()
557                                 + ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()",
558                         policyDataString);
559             } else if (DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
560                 configPath = evaluateXPath(
561                         "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
562                         policyDataString);
563             }
564
565             String prefix = null;
566             if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())
567                     || DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
568                 prefix = configPath.substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(),
569                         configPath.lastIndexOf(policy.policyAdapter.getPolicyName()));
570                 if (PolicyDBDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) {
571                     String configData = "";
572                     try {
573                         String newConfigPath = configPath;
574                         try {
575                             newConfigPath = processConfigPath(newConfigPath);
576                         } catch (Exception e2) {
577                             logger.error("Could not process config path: " + newConfigPath, e2);
578                         }
579                         configData = readConfigFile(newConfigPath);
580                     } catch (Exception e) {
581                         logger.error("Could not read config body data for " + configPath, e);
582                     }
583                     policy.policyAdapter.setConfigBodyData(configData);
584                 }
585             } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
586                 prefix = "Action_";
587             } else if ("Decision".equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
588                 prefix = "Decision_";
589             }
590
591             if (!(policy.policyAdapter.getData() instanceof PolicyType)
592                     && !(policy.policyAdapter.getData() instanceof PolicySetType)) {
593                 PolicyLogger.error("The data field is not an instance of PolicyType");
594                 throw new IllegalArgumentException("The data field is not an instance of PolicyType");
595             }
596             String finalName = policyScope + "." + prefix + policy.policyAdapter.getPolicyName() + "."
597                     + policy.policyAdapter.getHighestVersion() + ".xml";
598             if (policy.policyAdapter.getConfigType() == null || "".equals(policy.policyAdapter.getConfigType())) {
599                 // get the config file extension
600                 String ext = "";
601                 if (configPath != null && !"".equalsIgnoreCase(configPath)) {
602                     ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());;
603                 }
604
605                 if (ext.contains("txt")) {
606                     policy.policyAdapter.setConfigType(PolicyDBDao.OTHER_CONFIG);
607                 } else if (ext.contains("json")) {
608                     policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG);
609                 } else if (ext.contains("xml")) {
610                     policy.policyAdapter.setConfigType(PolicyDBDao.XML_CONFIG);
611                 } else if (ext.contains("properties")) {
612                     policy.policyAdapter.setConfigType(PolicyDBDao.PROPERTIES_CONFIG);
613                 } else {
614                     if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDBDao.ACTION)) {
615                         policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG);
616                     }
617                 }
618             }
619
620             createPolicy(policy.policyAdapter, username, policyScope, finalName, policyDataString);
621         } finally {
622             if (policyXmlStream != null) {
623                 try {
624                     policyXmlStream.close();
625                 } catch (IOException e) {
626                     logger.error("Exception Occured while closing input stream" + e);
627                 }
628             }
629         }
630     }
631
632
633     public PolicyEntity getPolicy(int policyId) {
634         return getPolicy(policyId, null, null);
635     }
636
637     public PolicyEntity getPolicy(String policyName, String scope) {
638         return getPolicy(-1, policyName, scope);
639     }
640
641     private PolicyEntity getPolicy(int policyIdVar, String policyName, String scope) {
642         logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar + "," + policyName
643                 + ") called");
644         if (policyIdVar < 0 && PolicyDBDao.isNullOrEmpty(policyName, scope)) {
645             throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank");
646         }
647
648         synchronized (emLock) {
649             checkBeforeOperationRun(true);
650             // check if group exists
651             String policyId;
652             Query policyQuery;
653             if (!PolicyDBDao.isNullOrEmpty(policyName, scope)) {
654                 policyId = policyName;
655                 policyQuery =
656                         session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope");
657                 policyQuery.setParameter("name", policyId);
658                 policyQuery.setParameter("scope", scope);
659             } else {
660                 policyId = String.valueOf(policyIdVar);
661                 policyQuery = session.getNamedQuery("PolicyEntity.FindById");
662                 policyQuery.setParameter("id", policyId);
663             }
664             List<?> policyQueryList;
665             try {
666                 policyQueryList = policyQuery.list();
667             } catch (Exception e) {
668                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
669                         "Caught Exception trying to get policy with policyQuery.getResultList()");
670                 throw new PersistenceException("Query failed trying to get policy " + policyId);
671             }
672
673             if (policyQueryList.isEmpty()) {
674                 PolicyLogger.error("Policy does not exist with id " + policyId);
675                 throw new PersistenceException("Group policy is being added to does not exist with id " + policyId);
676             } else if (policyQueryList.size() > 1) {
677                 PolicyLogger.error(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB);
678                 throw new PersistenceException(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB);
679             }
680             return (PolicyEntity) policyQueryList.get(0);
681         }
682     }
683
684     @Override
685     public GroupEntity getGroup(long groupKey) {
686         logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + ") called");
687         if (groupKey < 0) {
688             throw new IllegalArgumentException("groupKey must be at least 0");
689         }
690         synchronized (emLock) {
691             checkBeforeOperationRun(true);
692             // check if group exists
693             Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey");
694             groupQuery.setParameter("groupKey", groupKey);
695             List<?> groupQueryList;
696             try {
697                 groupQueryList = groupQuery.list();
698             } catch (Exception e) {
699                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
700                         "Caught Exception trying to get group with groupQuery.getResultList()");
701                 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupKey);
702             }
703             if (groupQueryList.isEmpty()) {
704                 PolicyLogger.error("Group does not exist with groupKey " + groupKey);
705                 throw new PersistenceException("Group does not exist with groupKey " + groupKey);
706             } else if (groupQueryList.size() > 1) {
707                 PolicyLogger
708                         .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB);
709                 throw new PersistenceException(
710                         "Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB);
711             }
712             return (GroupEntity) groupQueryList.get(0);
713         }
714     }
715
716     @Override
717     public GroupEntity getGroup(String groupId) {
718         logger.debug("getGroup(String groupId) as getGroup(" + groupId + ") called");
719         if (PolicyDBDao.isNullOrEmpty(groupId)) {
720             throw new IllegalArgumentException("groupId must not be null or empty");
721         }
722         synchronized (emLock) {
723             checkBeforeOperationRun(true);
724             // check if group exists
725             Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId");
726             groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId);
727             List<?> groupQueryList;
728             try {
729                 groupQueryList = groupQuery.list();
730             } catch (Exception e) {
731                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
732                         "Caught Exception trying to get group with groupQuery.getResultList()");
733                 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupId);
734             }
735             if (groupQueryList.isEmpty()) {
736                 PolicyLogger.error("Group does not exist with id " + groupId);
737                 throw new PersistenceException("Group does not exist with id " + groupId);
738             } else if (groupQueryList.size() > 1) {
739                 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB);
740                 throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB);
741             }
742             return (GroupEntity) groupQueryList.get(0);
743         }
744     }
745
746     @Override
747     public List<?> getPdpsInGroup(long groupKey) {
748         logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + ") called");
749         if (groupKey < 0) {
750             throw new IllegalArgumentException("groupId must not be < 0");
751         }
752         synchronized (emLock) {
753             checkBeforeOperationRun(true);
754             Query pdpsQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group");
755             pdpsQuery.setParameter("group", getGroup(groupKey));
756             return pdpsQuery.list();
757         }
758     }
759
760     @Override
761     public PdpEntity getPdp(long pdpKey) {
762         logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + ") called");
763         if (pdpKey < 0) {
764             throw new IllegalArgumentException("pdpKey must be at least 0");
765         }
766         synchronized (emLock) {
767             checkBeforeOperationRun(true);
768             // check if group exists
769             Query pdpQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey");
770             pdpQuery.setParameter("pdpKey", pdpKey);
771             List<?> pdpQueryList;
772             try {
773                 pdpQueryList = pdpQuery.list();
774             } catch (Exception e) {
775                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
776                         "Caught Exception trying to get pdp with pdpQuery.getResultList()");
777                 throw new PersistenceException("Query failed trying to get pdp " + pdpKey);
778             }
779             if (pdpQueryList.isEmpty()) {
780                 PolicyLogger.error("Pdp does not exist with pdpKey " + pdpKey);
781                 throw new PersistenceException("Pdp does not exist with pdpKey " + pdpKey);
782             } else if (pdpQueryList.size() > 1) {
783                 PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB);
784                 throw new PersistenceException(
785                         "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB);
786             }
787             return (PdpEntity) pdpQueryList.get(0);
788         }
789     }
790
791     @Override
792     public boolean isTransactionOpen() {
793         logger.debug("isTransactionOpen() as isTransactionOpen() called");
794         synchronized (emLock) {
795             return session.isOpen() && session.getTransaction().isActive();
796         }
797     }
798
799     private String processConfigPath(String inputConfigPath) {
800         String configPath = inputConfigPath;
801         String webappsPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS);
802         if (webappsPath == null) {
803             logger.error("Webapps property does not exist");
804             throw new IllegalArgumentException("Webapps property does not exist");
805         }
806         configPath = configPath.replace("$URL", webappsPath);
807         // make sure the correct slashes are in
808         try {
809             configPath = Paths.get(configPath).toString();
810         } catch (InvalidPathException e) {
811             logger.error("Invalid config path: " + configPath, e);
812             throw new IllegalArgumentException("Invalid config path: " + configPath);
813         }
814         return configPath;
815     }
816
817     private String readConfigFile(String configPath) {
818         String configDataString = null;
819         InputStream configContentStream = null;
820         try {
821             configContentStream = new FileInputStream(configPath);
822             configDataString = IOUtils.toString(configContentStream);
823         } catch (FileNotFoundException e) {
824             logger.error("Caught FileNotFoundException on new FileInputStream(" + configPath + ")", e);
825             throw new IllegalArgumentException("The config file path does not exist");
826         } catch (IOException e2) {
827             logger.error("Caught IOException on newIOUtils.toString(" + configContentStream + ")", e2);
828             throw new IllegalArgumentException("The config file path cannot be read");
829         } finally {
830             IOUtils.closeQuietly(configContentStream);
831         }
832         if (configDataString == null) {
833             throw new IllegalArgumentException("The config file path cannot be read");
834         }
835         return configDataString;
836     }
837
838
839     @Override
840     public void close() {
841         synchronized (emLock) {
842             if (session.isOpen()) {
843                 if (session.getTransaction().isActive()) {
844                     session.getTransaction().rollback();
845                 }
846                 session.close();
847             }
848             if (transactionTimer != null) {
849                 transactionTimer.interrupt();
850             }
851         }
852     }
853
854     @Override
855     public void createGroup(String groupId, String groupName, String inputGroupDescription, String username) {
856         String groupDescription = inputGroupDescription;
857         logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + groupName + ", "
858                 + groupDescription + ") called");
859         if (PolicyDBDao.isNullOrEmpty(groupId, groupName, username)) {
860             throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty");
861         }
862         if (groupDescription == null) {
863             groupDescription = "";
864         }
865
866         synchronized (emLock) {
867             checkBeforeOperationRun();
868             Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
869             checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId);
870             checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
871             List<?> checkGroupQueryList;
872             try {
873                 checkGroupQueryList = checkGroupQuery.list();
874             } catch (Exception e) {
875                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
876                         "Caught Exception on checkGroupQuery.getResultList()");
877                 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
878             }
879             if (!checkGroupQueryList.isEmpty()) {
880                 PolicyLogger.error("The group being added already exists with id " + groupId);
881                 throw new PersistenceException("The group being added already exists with id " + groupId);
882             }
883             GroupEntity newGroup = new GroupEntity();
884             newGroup.setCreatedBy(username);
885             newGroup.setModifiedBy(username);
886             newGroup.setGroupName(groupName);
887             newGroup.setGroupId(groupId);
888             newGroup.setDescription(groupDescription);
889             if (isJunit) {
890                 newGroup.prePersist();
891             }
892             session.persist(newGroup);
893             session.flush();
894             this.groupId = newGroup.getGroupKey();
895         }
896     }
897
898     @Override
899     public void updateGroup(OnapPDPGroup group, String requestType, String username) {
900         logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + "," + requestType + ","
901                 + username + ") called");
902         if (group == null) {
903             throw new IllegalArgumentException("PDPGroup group must not be null");
904         }
905         if (PolicyDBDao.isNullOrEmpty(group.getId(), requestType)) {
906             throw new IllegalArgumentException("group.getId() and username must not be null or empty");
907         }
908
909         synchronized (emLock) {
910             PolicyDBDao policyDbDaoVar = new PolicyDBDao();
911             checkBeforeOperationRun();
912             Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
913             getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
914             getGroupQuery.setParameter(PolicyDBDao.DELETED, false);
915             List<?> getGroupQueryList;
916             try {
917                 getGroupQueryList = getGroupQuery.list();
918             } catch (Exception e) {
919                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
920                         "Caught Exception on getGroupQuery.getResultList()");
921                 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing");
922             }
923             if (getGroupQueryList.isEmpty()) {
924                 PolicyLogger.error("The group cannot be found to update with id " + group.getId());
925                 throw new PersistenceException("The group cannot be found to update with id " + group.getId());
926             } else if (getGroupQueryList.size() > 1) {
927                 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
928                 throw new PersistenceException(
929                         PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
930             }
931             GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0);
932             if (!PolicyDBDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) {
933                 groupToUpdateInDb.setModifiedBy(requestType);
934             }
935             if (group.getDescription() != null
936                     && !PolicyDBDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) {
937                 groupToUpdateInDb.setDescription(group.getDescription());
938             }
939             // let's find out what policies have been deleted
940             StdPDPGroup oldGroup = null;
941             try {
942                 oldGroup = (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getId());
943             } catch (PAPException e1) {
944                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR,
945                         "We cannot get the group from the papEngine to delete policies");
946             }
947             if (oldGroup == null) {
948                 PolicyLogger.error("We cannot get the group from the papEngine to delete policies");
949             } else {
950                 Set<String> newPolicySet = new HashSet<>(group.getPolicies().size());
951                 // a multiple of n runtime is faster than n^2, so I am using a
952                 // hashset to do the comparison
953                 for (PDPPolicy pol : group.getPolicies()) {
954                     newPolicySet.add(pol.getId());
955                 }
956                 for (PDPPolicy pol : oldGroup.getPolicies()) {
957                     // should be fast since getPolicies uses a HashSet in
958                     // StdPDPGroup
959                     if (!newPolicySet.contains(pol.getId())) {
960                         String[] scopeAndName = policyDbDaoVar.getNameScopeAndVersionFromPdpPolicy(pol.getId());
961                         PolicyEntity policyToDelete = null;
962                         try {
963                             if (scopeAndName != null) {
964                                 policyToDelete = getPolicy(scopeAndName[0], scopeAndName[1]);
965                                 if ("XACMLPapServlet.doDelete".equals(requestType)) {
966                                     Iterator<PolicyEntity> dbPolicyIt = groupToUpdateInDb.getPolicies().iterator();
967                                     String policyName = policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
968                                             policyToDelete.getPolicyName())[0];
969
970                                     logger.info("PolicyDBDao: delete policy from GroupEntity");
971                                     try {
972                                         while (dbPolicyIt.hasNext()) {
973                                             PolicyEntity dbpolicy = dbPolicyIt.next();
974                                             if (policyToDelete.getScope().equals(dbpolicy.getScope())
975                                                     && policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
976                                                             dbpolicy.getPolicyName())[0].equals(policyName)) {
977                                                 dbPolicyIt.remove();
978                                                 auditPdpOperations(username,
979                                                         dbpolicy.getScope() + "." + dbpolicy.getPolicyName(), "Delete");
980                                                 logger.info("PolicyDBDao: deleting policy from the existing group:\n "
981                                                         + "policyName is " + policyToDelete.getScope() + "."
982                                                         + policyToDelete.getPolicyName() + "\n" + "group is "
983                                                         + groupToUpdateInDb.getGroupId());
984                                             }
985                                         }
986                                     } catch (Exception e) {
987                                         logger.debug(e);
988                                         PolicyLogger.error("Could not delete policy with name: "
989                                                 + policyToDelete.getScope() + "." + policyToDelete.getPolicyName()
990                                                 + "\n ID: " + policyToDelete.getPolicyId());
991                                     }
992                                 }
993                             }
994                         } catch (Exception e) {
995                             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
996                                     "Could not get policy to remove: " + pol.getId());
997                             throw new PersistenceException("Could not get policy to remove: " + pol.getId());
998                         }
999                     }
1000                 }
1001             }
1002
1003             if (group.getName() != null
1004                     && !PolicyDBDao.stringEquals(group.getName(), groupToUpdateInDb.getgroupName())) {
1005                 // we need to check if the new id exists in the database
1006                 String newGrpId = PolicyDBDao.createNewPDPGroupId(group.getName());
1007                 Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1008                 checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, newGrpId);
1009                 checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1010                 List<?> checkGroupQueryList;
1011                 try {
1012                     checkGroupQueryList = checkGroupQuery.list();
1013                 } catch (Exception e) {
1014                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1015                             "Caught Exception on checkGroupQuery.getResultList()");
1016                     throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
1017                 }
1018                 if (!checkGroupQueryList.isEmpty()) {
1019                     PolicyLogger.error("The new group name already exists, group id " + newGrpId);
1020                     throw new PersistenceException("The new group name already exists, group id " + newGrpId);
1021                 }
1022                 groupToUpdateInDb.setGroupId(newGrpId);
1023                 groupToUpdateInDb.setGroupName(group.getName());
1024                 this.newGroupId = group.getId();
1025             }
1026             session.flush();
1027             this.groupId = groupToUpdateInDb.getGroupKey();
1028         }
1029     }
1030
1031     @Override
1032     public void addPdpToGroup(String pdpId, String groupIdVar, String pdpName, String pdpDescription, int pdpJmxPort,
1033             String username) {
1034         logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, "
1035                 + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + pdpId + ", "
1036                 + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + username
1037                 + ") called");
1038         if (PolicyDBDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) {
1039             throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty");
1040         }
1041         synchronized (emLock) {
1042             checkBeforeOperationRun();
1043             Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1044             checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar);
1045             checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1046             List<?> checkGroupQueryList;
1047             try {
1048                 checkGroupQueryList = checkGroupQuery.list();
1049             } catch (Exception e) {
1050                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1051                         "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()");
1052                 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
1053             }
1054             if (checkGroupQueryList.size() != 1) {
1055                 PolicyLogger.error("The group does not exist");
1056                 throw new PersistenceException("The group does not exist");
1057             }
1058             Query checkDuplicateQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1059             checkDuplicateQuery.setParameter(PolicyDBDao.PDP_ID, pdpId);
1060             checkDuplicateQuery.setParameter(PolicyDBDao.DELETED, false);
1061             List<?> checkDuplicateList;
1062             try {
1063                 checkDuplicateList = checkDuplicateQuery.list();
1064             } catch (Exception e) {
1065                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1066                         "Caught Exception trying to check for duplicate PDP " + pdpId
1067                                 + " on checkDuplicateQuery.getResultList()");
1068                 throw new PersistenceException("Query failed trying to check for duplicate PDP " + pdpId);
1069             }
1070             PdpEntity newPdp;
1071             if (!checkDuplicateList.isEmpty()) {
1072                 logger.warn("PDP already exists with id " + pdpId);
1073                 newPdp = (PdpEntity) checkDuplicateList.get(0);
1074             } else {
1075                 newPdp = new PdpEntity();
1076             }
1077
1078             newPdp.setCreatedBy(username);
1079             newPdp.setDeleted(false);
1080             newPdp.setDescription(pdpDescription);
1081             newPdp.setGroup((GroupEntity) checkGroupQueryList.get(0));
1082             newPdp.setJmxPort(pdpJmxPort);
1083             newPdp.setModifiedBy(username);
1084             newPdp.setPdpId(pdpId);
1085             newPdp.setPdpName(pdpName);
1086             if (isJunit) {
1087                 newPdp.prePersist();
1088             }
1089             session.persist(newPdp);
1090             session.flush();
1091             this.pdpId = newPdp.getPdpKey();
1092         }
1093     }
1094
1095     @Override
1096     public void updatePdp(OnapPDP pdp, String username) {
1097         logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + ") called");
1098         if (pdp == null) {
1099             throw new IllegalArgumentException("PDP pdp must not be null");
1100         }
1101         if (PolicyDBDao.isNullOrEmpty(pdp.getId(), username)) {
1102             throw new IllegalArgumentException("pdp.getId() and username must not be null or empty");
1103         }
1104
1105         synchronized (emLock) {
1106             checkBeforeOperationRun();
1107             Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1108             getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId());
1109             getPdpQuery.setParameter(PolicyDBDao.DELETED, false);
1110             List<?> getPdpQueryList;
1111             try {
1112                 getPdpQueryList = getPdpQuery.list();
1113             } catch (Exception e) {
1114                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1115                         "Caught Exception on getPdpQuery.getResultList()");
1116                 throw new PersistenceException("Query failed trying to get PDP " + pdp.getId());
1117             }
1118             if (getPdpQueryList.isEmpty()) {
1119                 PolicyLogger.error("The pdp cannot be found to update with id " + pdp.getId());
1120                 throw new PersistenceException("The pdp cannot be found to update with id " + pdp.getId());
1121             } else if (getPdpQueryList.size() > 1) {
1122                 PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1123                 throw new PersistenceException(
1124                         PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1125             }
1126             PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1127             if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1128                 pdpToUpdate.setModifiedBy(username);
1129             }
1130             if (pdp.getDescription() != null
1131                     && !PolicyDBDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) {
1132                 pdpToUpdate.setDescription(pdp.getDescription());
1133             }
1134             if (pdp.getName() != null && !PolicyDBDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) {
1135                 pdpToUpdate.setPdpName(pdp.getName());
1136             }
1137             if (pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())) {
1138                 pdpToUpdate.setJmxPort(pdp.getJmxPort());
1139             }
1140
1141             session.flush();
1142             this.pdpId = pdpToUpdate.getPdpKey();
1143         }
1144     }
1145
1146     @Override
1147     public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) {
1148         logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + "," + group + ","
1149                 + username + ") called");
1150         if (pdp == null || group == null) {
1151             throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null");
1152         }
1153         if (PolicyDBDao.isNullOrEmpty(username, pdp.getId(), group.getId())) {
1154             throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty");
1155         }
1156
1157         synchronized (emLock) {
1158             checkBeforeOperationRun();
1159             // check if pdp exists
1160             Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1161             getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId());
1162             getPdpQuery.setParameter(PolicyDBDao.DELETED, false);
1163             List<?> getPdpQueryList;
1164             try {
1165                 getPdpQueryList = getPdpQuery.list();
1166             } catch (Exception e) {
1167                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1168                         "Caught Exception on getPdpQuery.getResultList()");
1169                 throw new PersistenceException("Query failed trying to get pdp to move with id " + pdp.getId());
1170             }
1171             if (getPdpQueryList.isEmpty()) {
1172                 PolicyLogger.error("The pdp cannot be found to move with id " + pdp.getId());
1173                 throw new PersistenceException("The pdp cannot be found to move with id " + pdp.getId());
1174             } else if (getPdpQueryList.size() > 1) {
1175                 PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1176                 throw new PersistenceException(
1177                         PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1178             }
1179
1180             // check if new group exists
1181             Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1182             checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1183             checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1184             List<?> checkGroupQueryList;
1185             try {
1186                 checkGroupQueryList = checkGroupQuery.list();
1187             } catch (Exception e) {
1188                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1189                         "Caught Exception trying to get group on checkGroupQuery.getResultList()");
1190                 throw new PersistenceException("Query failed trying to get new group " + group.getId());
1191             }
1192             if (checkGroupQueryList.size() != 1) {
1193                 PolicyLogger.error("The group " + group.getId() + " does not exist");
1194                 throw new PersistenceException("The group " + group.getId() + " does not exist");
1195             }
1196             GroupEntity groupToMoveInto = (GroupEntity) checkGroupQueryList.get(0);
1197             PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1198             pdpToUpdate.setGroup(groupToMoveInto);
1199             if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1200                 pdpToUpdate.setModifiedBy(username);
1201             }
1202
1203             session.flush();
1204             this.pdpId = pdpToUpdate.getPdpKey();
1205         }
1206     }
1207
1208     @Override
1209     public void changeDefaultGroup(OnapPDPGroup group, String username) {
1210         logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + ","
1211                 + username + ") called");
1212         if (group == null) {
1213             throw new IllegalArgumentException("PDPGroup group must not be null");
1214         }
1215         if (PolicyDBDao.isNullOrEmpty(group.getId(), username)) {
1216             throw new IllegalArgumentException("group.getId() and username must not be null or empty");
1217         }
1218
1219         synchronized (emLock) {
1220             checkBeforeOperationRun();
1221             Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1222             getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1223             getGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1224             List<?> getGroupQueryList;
1225             try {
1226                 getGroupQueryList = getGroupQuery.list();
1227             } catch (Exception e) {
1228                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1229                         "Caught Exception on getGroupQuery.getResultList()");
1230                 throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId());
1231             }
1232             if (getGroupQueryList.isEmpty()) {
1233                 PolicyLogger.error("The group cannot be found to set default with id " + group.getId());
1234                 throw new PersistenceException("The group cannot be found to set default with id " + group.getId());
1235             } else if (getGroupQueryList.size() > 1) {
1236                 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1237                 throw new PersistenceException(
1238                         PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
1239             }
1240             GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0);
1241             newDefaultGroup.setDefaultGroup(true);
1242             if (!PolicyDBDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) {
1243                 newDefaultGroup.setModifiedBy(username);
1244             }
1245
1246             session.flush();
1247             this.groupId = newDefaultGroup.getGroupKey();
1248             Query setAllGroupsNotDefault = session.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup "
1249                     + "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey");
1250             // not going to set modified by for all groups
1251             setAllGroupsNotDefault.setParameter("defaultGroup", false);
1252             setAllGroupsNotDefault.setParameter(PolicyDBDao.DELETED, false);
1253             setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey());
1254             try {
1255                 logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default");
1256             } catch (Exception e) {
1257                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1258                         "Caught Exception on setAllGroupsNotDefault.executeUpdate()");
1259                 throw new PersistenceException("Could not set all other groups default to false");
1260             }
1261             session.flush();
1262         }
1263     }
1264
1265     @Override
1266     public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDBException {
1267         logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup(" + group + ", "
1268                 + moveToGroup + "," + username + ") called");
1269         if (group == null) {
1270             throw new IllegalArgumentException("PDPGroup group cannot be null");
1271         }
1272         if (PolicyDBDao.isNullOrEmpty(username, group.getId())) {
1273             throw new IllegalArgumentException("group.getId() and and username must not be null or empty");
1274         }
1275
1276         if (group.isDefaultGroup()) {
1277             PolicyLogger.error("The default group " + group.getId() + " was attempted to be deleted. It cannot be.");
1278             throw new PolicyDBException("You cannot delete the default group.");
1279         }
1280         synchronized (emLock) {
1281             checkBeforeOperationRun();
1282             Query deleteGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1283             deleteGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
1284             deleteGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1285             List<?> deleteGroupQueryList;
1286             try {
1287                 deleteGroupQueryList = deleteGroupQuery.list();
1288             } catch (Exception e) {
1289                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1290                         "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()");
1291                 throw new PersistenceException("Query failed trying to check if group exists");
1292             }
1293             if (deleteGroupQueryList.isEmpty()) {
1294                 logger.warn(PolicyDBDao.GROUP_NOT_FOUND + group.getId());
1295                 return;
1296             } else if (deleteGroupQueryList.size() > 1) {
1297                 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1298                 throw new PersistenceException(
1299                         PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1300             }
1301
1302             Query pdpsInGroupQuery =
1303                     session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted");
1304             pdpsInGroupQuery.setParameter("group", (deleteGroupQueryList.get(0)));
1305             pdpsInGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1306             List<?> pdpsInGroupList;
1307             try {
1308                 pdpsInGroupList = pdpsInGroupQuery.list();
1309             } catch (Exception e) {
1310                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1311                         "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()");
1312                 throw new PersistenceException("Query failed trying to get PDPs in group");
1313             }
1314             if (!pdpsInGroupList.isEmpty()) {
1315                 if (moveToGroup != null) {
1316                     Query checkMoveToGroupQuery = session
1317                             .createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted");
1318                     checkMoveToGroupQuery.setParameter(PolicyDBDao.GROUP_ID, moveToGroup.getId());
1319                     checkMoveToGroupQuery.setParameter(PolicyDBDao.DELETED, false);
1320                     List<?> checkMoveToGroupList;
1321                     try {
1322                         checkMoveToGroupList = checkMoveToGroupQuery.list();
1323                     } catch (Exception e) {
1324                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1325                                 "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList");
1326                         throw new PersistenceException("Query failed trying to check if group exists");
1327                     }
1328                     if (checkMoveToGroupList.isEmpty()) {
1329                         PolicyLogger.error(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId());
1330                         throw new PersistenceException(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId());
1331                     } else if (checkMoveToGroupList.size() > 1) {
1332                         PolicyLogger.error(
1333                                 PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1334                         throw new PersistenceException(
1335                                 PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1336                     } else {
1337                         GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0);
1338                         for (Object pdpObject : pdpsInGroupList) {
1339                             PdpEntity pdp = (PdpEntity) pdpObject;
1340                             pdp.setGroup(newGroup);
1341                             if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) {
1342                                 pdp.setModifiedBy(username);
1343                             }
1344                             try {
1345                                 session.flush();
1346                                 this.newGroupId = newGroup.getGroupId();
1347                             } catch (PersistenceException e) {
1348                                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1349                                         "Caught PersistenceException trying to set pdp group to null on em.flush()");
1350                                 throw new PersistenceException("Query failed trying to set pdp group to ");
1351                             }
1352                         }
1353                     }
1354                 } else {
1355                     PolicyLogger.error("Group " + group.getId()
1356                             + " is trying to be delted with PDPs. No group was provided to move them to");
1357                     throw new PolicyDBException("Group has PDPs. Must provide a group for them to move to");
1358                 }
1359             }
1360
1361             // delete group here
1362             GroupEntity groupToDelete = (GroupEntity) deleteGroupQueryList.get(0);
1363             groupToDelete.setDeleted(true);
1364             if (!PolicyDBDao.stringEquals(groupToDelete.getModifiedBy(), username)) {
1365                 groupToDelete.setModifiedBy(username);
1366             }
1367             session.flush();
1368             this.groupId = groupToDelete.getGroupKey();
1369         }
1370     }
1371
1372     @Override
1373     public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, String username)
1374             throws PolicyDBException {
1375         logger.info(
1376                 "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup("
1377                         + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + ") called");
1378         if (PolicyDBDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) {
1379             throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty");
1380         }
1381         synchronized (emLock) {
1382             checkBeforeOperationRun();
1383             // check if group exists
1384             Query groupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
1385             groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar);
1386             groupQuery.setParameter(PolicyDBDao.DELETED, false);
1387             List<?> groupQueryList;
1388             try {
1389                 groupQueryList = groupQuery.list();
1390             } catch (Exception e) {
1391                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1392                         "Caught Exception trying to check if group exists groupQuery.getResultList()");
1393                 throw new PersistenceException("Query failed trying to check if group " + groupIdVar + " exists");
1394             }
1395             if (groupQueryList.isEmpty()) {
1396                 PolicyLogger.error("Group policy is being added to does not exist with id " + groupIdVar);
1397                 throw new PersistenceException("Group policy is being added to does not exist with id " + groupIdVar);
1398             } else if (groupQueryList.size() > 1) {
1399                 PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1400                 throw new PersistenceException(
1401                         PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1402             }
1403
1404             // we need to convert the form of the policy id that is used groups
1405             // into the form that is used
1406             // for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml)
1407             PolicyDBDao policyDbDao = new PolicyDBDao();
1408             String[] policyNameScopeAndVersion = policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar);
1409             if (policyNameScopeAndVersion == null) {
1410                 throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version");
1411             }
1412             Query policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName "
1413                     + "AND p.scope=:scope AND p.deleted=:deleted");
1414             policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]);
1415             policyQuery.setParameter(PolicyDBDao.SCOPE, policyNameScopeAndVersion[1]);
1416             policyQuery.setParameter(PolicyDBDao.DELETED, false);
1417             List<?> policyQueryList;
1418             try {
1419                 policyQueryList = policyQuery.list();
1420             } catch (Exception e) {
1421                 logger.debug(e);
1422                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1423                         "Caught Exception trying to check if policy exists policyQuery.getResultList()");
1424                 throw new PersistenceException(
1425                         "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + " exists");
1426             }
1427             if (policyQueryList.isEmpty()) {
1428                 PolicyLogger.error("Policy being added to the group does not exist with policy id "
1429                         + policyNameScopeAndVersion[0]);
1430                 throw new PersistenceException("Policy being added to the group does not exist with policy id "
1431                         + policyNameScopeAndVersion[0]);
1432             } else if (policyQueryList.size() > 1) {
1433                 PolicyLogger.error(
1434                         PolicyDBDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1435                 throw new PersistenceException(
1436                         PolicyDBDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1437             }
1438             logger.info("PolicyDBDao: Getting group and policy from database");
1439             GroupEntity group = (GroupEntity) groupQueryList.get(0);
1440             PolicyEntity policy = (PolicyEntity) policyQueryList.get(0);
1441             Iterator<PolicyEntity> policyIt = group.getPolicies().iterator();
1442             String policyName = policyDbDao.getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0];
1443
1444             logger.info("PolicyDBDao: policyName retrieved is " + policyName);
1445             try {
1446                 while (policyIt.hasNext()) {
1447                     PolicyEntity pol = policyIt.next();
1448                     if (policy.getScope().equals(pol.getScope())
1449                             && policyDbDao.getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0]
1450                                     .equals(policyName)) {
1451                         policyIt.remove();
1452                     }
1453                 }
1454             } catch (Exception e) {
1455                 logger.debug(e);
1456                 PolicyLogger.error("Could not delete old versions for policy " + policy.getPolicyName() + ", ID: "
1457                         + policy.getPolicyId());
1458             }
1459             group.addPolicyToGroup(policy);
1460             auditPdpOperations(username, policy.getScope() + "." + policy.getPolicyName(), "Push");
1461             session.flush();
1462
1463             // After adding policy to the db group we need to make sure the
1464             // filesytem group is in sync with the db group
1465             try {
1466                 StdPDPGroup pdpGroup =
1467                         (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getGroupId());
1468                 return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group);
1469             } catch (PAPException e) {
1470                 logger.debug(e);
1471                 PolicyLogger.error("PolicyDBDao: Could not synchronize the filesystem group with the database group. "
1472                         + e.getMessage());
1473             }
1474             return null;
1475         }
1476     }
1477
1478     // this means delete pdp not just remove from group
1479     @Override
1480     public void removePdpFromGroup(String pdpId, String username) {
1481         logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpId + "," + username
1482                 + ") called");
1483         if (PolicyDBDao.isNullOrEmpty(pdpId, username)) {
1484             throw new IllegalArgumentException("pdpID and username must not be null or empty");
1485         }
1486         synchronized (emLock) {
1487             checkBeforeOperationRun();
1488             Query pdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
1489             pdpQuery.setParameter(PolicyDBDao.PDP_ID, pdpId);
1490             pdpQuery.setParameter(PolicyDBDao.DELETED, false);
1491             List<?> pdpList;
1492             try {
1493                 pdpList = pdpQuery.list();
1494             } catch (Exception e) {
1495                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
1496                         "Caught Exception trying to check if pdp exists  pdpQuery.getResultList()");
1497                 throw new PersistenceException("Query failed trying to check if pdp " + pdpId + " exists");
1498             }
1499             if (pdpList.size() > 1) {
1500                 PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1501                 throw new PersistenceException(
1502                         "Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
1503             } else if (pdpList.isEmpty()) {
1504                 PolicyLogger.error("Pdp being removed does not exist with id " + pdpId);
1505                 return;
1506             }
1507             PdpEntity pdp = (PdpEntity) pdpList.get(0);
1508             if (!isJunit) {
1509                 pdp.setGroup(null);
1510             }
1511
1512             if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) {
1513                 pdp.setModifiedBy(username);
1514             }
1515             pdp.setDeleted(true);
1516
1517             session.flush();
1518             this.pdpId = pdp.getPdpKey();
1519         }
1520     }
1521
1522     private static String evaluateXPath(String expression, String xml) {
1523         InputSource source = new InputSource(new StringReader(xml));
1524
1525         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1526         String description = "";
1527         try {
1528             DocumentBuilder db = dbf.newDocumentBuilder();
1529             Document document = db.parse(source);
1530
1531             XPathFactory xpathFactory = XPathFactory.newInstance();
1532             XPath xpath = xpathFactory.newXPath();
1533
1534             description = xpath.evaluate(expression, document);
1535         } catch (Exception e) {
1536             logger.error("Exception Occured while evaluating path" + e);
1537         }
1538         return description;
1539     }
1540
1541     public static boolean isJunit() {
1542         return isJunit;
1543     }
1544
1545     public static void setJunit(boolean isJunit) {
1546         PolicyDbDaoTransactionInstance.isJunit = isJunit;
1547     }
1548
1549     /**
1550      * Audit pdp operations.
1551      *
1552      * @param username the username
1553      * @param policyID the policy ID
1554      * @param action the action
1555      */
1556     public void auditPdpOperations(String username, String policyID, String action) {
1557         PolicyAuditlog log = new PolicyAuditlog();
1558         log.setUserName(username);
1559         log.setActions(action);
1560         log.setPolicyName(policyID);
1561         log.setDateAndTime(new Date());
1562         session.save(log);
1563     }
1564 }