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