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