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