Update css file name in conf.py
[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-2020 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                 if (policyDataString != null) {
553                     logger.warn("isJUnit will overwrite policyDataString");
554                 }
555                 // Using parentPath object to set policy data.
556                 policyDataString = policy.policyAdapter.getParentPath();
557             }
558             String configPath = "";
559             if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
560                 configPath = evaluateXPath(
561                         "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/"
562                                 + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
563                         policyDataString);
564             } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
565                 configPath = evaluateXPath(
566                         "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, "
567                                 + policy.policyAdapter.getActionAttribute()
568                                 + ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()",
569                         policyDataString);
570             } else if (DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
571                 configPath = evaluateXPath(
572                         "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/"
573                                 + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
574                         policyDataString);
575             }
576
577             String prefix = null;
578             if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())
579                     || DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
580                 prefix = configPath.substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(),
581                         configPath.lastIndexOf(policy.policyAdapter.getPolicyName()));
582                 if (PolicyDbDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) {
583                     String configData = "";
584                     try {
585                         String newConfigPath = configPath;
586                         try {
587                             newConfigPath = processConfigPath(newConfigPath);
588                         } catch (Exception e2) {
589                             logger.error("Could not process config path: " + newConfigPath, e2);
590                         }
591                         configData = readConfigFile(newConfigPath);
592                     } catch (Exception e) {
593                         logger.error("Could not read config body data for " + configPath, e);
594                     }
595                     policy.policyAdapter.setConfigBodyData(configData);
596                 }
597             } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
598                 prefix = "Action_";
599             } else if ("Decision".equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
600                 prefix = "Decision_";
601             }
602
603             if (!(policy.policyAdapter.getData() instanceof PolicyType)
604                     && !(policy.policyAdapter.getData() instanceof PolicySetType)) {
605                 PolicyLogger.error("The data field is not an instance of PolicyType");
606                 throw new IllegalArgumentException("The data field is not an instance of PolicyType");
607             }
608             String finalName = policyScope + "." + prefix + policy.policyAdapter.getPolicyName() + "."
609                     + policy.policyAdapter.getHighestVersion() + ".xml";
610             if (policy.policyAdapter.getConfigType() == null || "".equals(policy.policyAdapter.getConfigType())) {
611                 // get the config file extension
612                 String ext = "";
613                 if (configPath != null && !"".equalsIgnoreCase(configPath)) {
614                     ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());
615                 }
616
617                 if (ext.contains("txt")) {
618                     policy.policyAdapter.setConfigType(PolicyDbDao.OTHER_CONFIG);
619                 } else if (ext.contains("json")) {
620                     policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG);
621                 } else if (ext.contains("xml")) {
622                     policy.policyAdapter.setConfigType(PolicyDbDao.XML_CONFIG);
623                 } else if (ext.contains("properties")) {
624                     policy.policyAdapter.setConfigType(PolicyDbDao.PROPERTIES_CONFIG);
625                 } else {
626                     if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDbDao.ACTION)) {
627                         policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG);
628                     }
629                 }
630             }
631
632             createPolicy(policy.policyAdapter, username, policyScope, finalName, policyDataString);
633         } finally {
634             if (policyXmlStream != null) {
635                 try {
636                     policyXmlStream.close();
637                 } catch (IOException e) {
638                     logger.error("Exception Occured while closing input stream" + e);
639                 }
640             }
641         }
642     }
643
644     public PolicyEntity getPolicy(int policyId) {
645         return getPolicy(policyId, null, null);
646     }
647
648     public PolicyEntity getPolicy(String policyName, String scope) {
649         return getPolicy(-1, policyName, scope);
650     }
651
652     private PolicyEntity getPolicy(int policyIdVar, String policyName, String scope) {
653         logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar + "," + policyName
654                 + BRACKET_CALLED);
655         if (policyIdVar < 0 && PolicyDbDao.isNullOrEmpty(policyName, scope)) {
656             throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank");
657         }
658
659         synchronized (emLock) {
660             checkBeforeOperationRun(true);
661             // check if group exists
662             String locPolicyId;
663             Query policyQuery;
664             if (!PolicyDbDao.isNullOrEmpty(policyName, scope)) {
665                 locPolicyId = policyName;
666                 policyQuery =
667                         session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope");
668                 policyQuery.setParameter("name", locPolicyId);
669                 policyQuery.setParameter("scope", scope);
670             } else {
671                 locPolicyId = String.valueOf(policyIdVar);
672                 policyQuery = session.getNamedQuery("PolicyEntity.FindById");
673                 policyQuery.setParameter("id", locPolicyId);
674             }
675             List<?> policyQueryList;
676             try {
677                 policyQueryList = policyQuery.list();
678             } catch (Exception e) {
679                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
680                         "Caught Exception trying to get policy with policyQuery.getResultList()");
681                 throw new PersistenceException("Query failed trying to get policy " + locPolicyId);
682             }
683
684             if (policyQueryList.isEmpty()) {
685                 PolicyLogger.error("Policy does not exist with id " + locPolicyId);
686                 throw new PersistenceException("Group policy is being added to does not exist with id " + locPolicyId);
687             } else if (policyQueryList.size() > 1) {
688                 PolicyLogger.error(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB);
689                 throw new PersistenceException(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB);
690             }
691             return (PolicyEntity) policyQueryList.get(0);
692         }
693     }
694
695     @Override
696     public GroupEntity getGroup(long groupKey) {
697         logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + BRACKET_CALLED);
698         if (groupKey < 0) {
699             throw new IllegalArgumentException("groupKey must be at least 0");
700         }
701         synchronized (emLock) {
702             checkBeforeOperationRun(true);
703             // check if group exists
704             Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey");
705             groupQuery.setParameter("groupKey", groupKey);
706             List<?> groupQueryList;
707             try {
708                 groupQueryList = groupQuery.list();
709             } catch (Exception e) {
710                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
711                         "Caught Exception trying to get group with groupQuery.getResultList()");
712                 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupKey);
713             }
714             if (groupQueryList.isEmpty()) {
715                 PolicyLogger.error("Group does not exist with groupKey " + groupKey);
716                 throw new PersistenceException("Group does not exist with groupKey " + groupKey);
717             } else if (groupQueryList.size() > 1) {
718                 PolicyLogger
719                         .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB);
720                 throw new PersistenceException(
721                         "Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB);
722             }
723             return (GroupEntity) groupQueryList.get(0);
724         }
725     }
726
727     @Override
728     public GroupEntity getGroup(String groupId) {
729         logger.debug("getGroup(String groupId) as getGroup(" + groupId + BRACKET_CALLED);
730         if (PolicyDbDao.isNullOrEmpty(groupId)) {
731             throw new IllegalArgumentException("groupId must not be null or empty");
732         }
733         synchronized (emLock) {
734             checkBeforeOperationRun(true);
735             // check if group exists
736             Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId");
737             groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId);
738             List<?> groupQueryList;
739             try {
740                 groupQueryList = groupQuery.list();
741             } catch (Exception e) {
742                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
743                         "Caught Exception trying to get group with groupQuery.getResultList()");
744                 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupId);
745             }
746             if (groupQueryList.isEmpty()) {
747                 PolicyLogger.error("Group does not exist with id " + groupId);
748                 throw new PersistenceException("Group does not exist with id " + groupId);
749             } else if (groupQueryList.size() > 1) {
750                 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB);
751                 throw new PersistenceException(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB);
752             }
753             return (GroupEntity) groupQueryList.get(0);
754         }
755     }
756
757     @Override
758     public List<?> getPdpsInGroup(long groupKey) {
759         logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + BRACKET_CALLED);
760         if (groupKey < 0) {
761             throw new IllegalArgumentException("groupId must not be < 0");
762         }
763         synchronized (emLock) {
764             checkBeforeOperationRun(true);
765             Query pdpsQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group");
766             pdpsQuery.setParameter(GROUP, getGroup(groupKey));
767             return pdpsQuery.list();
768         }
769     }
770
771     @Override
772     public PdpEntity getPdp(long pdpKey) {
773         logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + BRACKET_CALLED);
774         if (pdpKey < 0) {
775             throw new IllegalArgumentException("pdpKey must be at least 0");
776         }
777         synchronized (emLock) {
778             checkBeforeOperationRun(true);
779             // check if group exists
780             Query pdpQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey");
781             pdpQuery.setParameter("pdpKey", pdpKey);
782             List<?> pdpQueryList;
783             try {
784                 pdpQueryList = pdpQuery.list();
785             } catch (Exception e) {
786                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
787                         "Caught Exception trying to get pdp with pdpQuery.getResultList()");
788                 throw new PersistenceException("Query failed trying to get pdp " + pdpKey);
789             }
790             if (pdpQueryList.isEmpty()) {
791                 PolicyLogger.error("Pdp does not exist with pdpKey " + pdpKey);
792                 throw new PersistenceException("Pdp does not exist with pdpKey " + pdpKey);
793             } else if (pdpQueryList.size() > 1) {
794                 PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB);
795                 throw new PersistenceException(
796                         "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB);
797             }
798             return (PdpEntity) pdpQueryList.get(0);
799         }
800     }
801
802     @Override
803     public boolean isTransactionOpen() {
804         logger.debug("isTransactionOpen() as isTransactionOpen() called");
805         synchronized (emLock) {
806             return session.isOpen() && session.getTransaction().isActive();
807         }
808     }
809
810     private String processConfigPath(String inputConfigPath) {
811         String configPath = inputConfigPath;
812         String webappsPath = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS);
813         if (webappsPath == null) {
814             logger.error("Webapps property does not exist");
815             throw new IllegalArgumentException("Webapps property does not exist");
816         }
817         configPath = configPath.replace("$URL", webappsPath);
818         // make sure the correct slashes are in
819         try {
820             configPath = Paths.get(configPath).toString();
821         } catch (InvalidPathException e) {
822             logger.error("Invalid config path: " + configPath, e);
823             throw new IllegalArgumentException("Invalid config path: " + configPath);
824         }
825         return configPath;
826     }
827
828     private String readConfigFile(String configPath) {
829         String configDataString = null;
830         InputStream configContentStream = null;
831         try {
832             configContentStream = new FileInputStream(configPath);
833             configDataString = IOUtils.toString(configContentStream);
834         } catch (FileNotFoundException e) {
835             logger.error("Caught FileNotFoundException on new FileInputStream(" + configPath + ")", e);
836             throw new IllegalArgumentException("The config file path does not exist");
837         } catch (IOException e2) {
838             logger.error("Caught IOException on newIOUtils.toString(" + configContentStream + ")", e2);
839             throw new IllegalArgumentException("The config file path cannot be read");
840         } finally {
841             IOUtils.closeQuietly(configContentStream);
842         }
843         if (configDataString == null) {
844             throw new IllegalArgumentException("The config file path cannot be read");
845         }
846         return configDataString;
847     }
848
849     @Override
850     public void close() {
851         synchronized (emLock) {
852             if (session.isOpen()) {
853                 if (session.getTransaction().isActive()) {
854                     session.getTransaction().rollback();
855                 }
856                 session.close();
857             }
858             if (transactionTimer != null) {
859                 transactionTimer.interrupt();
860             }
861         }
862     }
863
864     @Override
865     public void createGroup(String groupId, String groupName, String inputGroupDescription, String username) {
866         String groupDescription = inputGroupDescription;
867         logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + groupName + ", "
868                 + groupDescription + BRACKET_CALLED);
869         if (PolicyDbDao.isNullOrEmpty(groupId, groupName, username)) {
870             throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty");
871         }
872         if (groupDescription == null) {
873             groupDescription = "";
874         }
875
876         synchronized (emLock) {
877             checkBeforeOperationRun();
878             Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
879             checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId);
880             checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
881             List<?> checkGroupQueryList;
882             try {
883                 checkGroupQueryList = checkGroupQuery.list();
884             } catch (Exception e) {
885                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
886                         "Caught Exception on checkGroupQuery.getResultList()");
887                 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
888             }
889             if (!checkGroupQueryList.isEmpty()) {
890                 PolicyLogger.error("The group being added already exists with id " + groupId);
891                 throw new PersistenceException("The group being added already exists with id " + groupId);
892             }
893             GroupEntity newGroup = new GroupEntity();
894             newGroup.setCreatedBy(username);
895             newGroup.setModifiedBy(username);
896             newGroup.setGroupName(groupName);
897             newGroup.setGroupId(groupId);
898             newGroup.setDescription(groupDescription);
899             if (isJunit) {
900                 newGroup.prePersist();
901             }
902             session.persist(newGroup);
903             session.flush();
904             this.groupId = newGroup.getGroupKey();
905         }
906     }
907
908     @Override
909     public void updateGroup(OnapPDPGroup group, String requestType, String username) {
910         logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + "," + requestType + ","
911                 + username + BRACKET_CALLED);
912         if (group == null) {
913             throw new IllegalArgumentException("PDPGroup group must not be null");
914         }
915         if (PolicyDbDao.isNullOrEmpty(group.getId(), requestType)) {
916             throw new IllegalArgumentException("group.getId() and username must not be null or empty");
917         }
918
919         synchronized (emLock) {
920             PolicyDbDao policyDbDaoVar = new PolicyDbDao();
921             checkBeforeOperationRun();
922             Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
923             getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
924             getGroupQuery.setParameter(PolicyDbDao.DELETED, false);
925             List<?> getGroupQueryList;
926             try {
927                 getGroupQueryList = getGroupQuery.list();
928             } catch (Exception e) {
929                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
930                         "Caught Exception on getGroupQuery.getResultList()");
931                 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing");
932             }
933             if (getGroupQueryList.isEmpty()) {
934                 PolicyLogger.error("The group cannot be found to update with id " + group.getId());
935                 throw new PersistenceException("The group cannot be found to update with id " + group.getId());
936             } else if (getGroupQueryList.size() > 1) {
937                 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
938                 throw new PersistenceException(
939                         PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
940             }
941             GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0);
942             if (!PolicyDbDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) {
943                 groupToUpdateInDb.setModifiedBy(requestType);
944             }
945             if (group.getDescription() != null
946                     && !PolicyDbDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) {
947                 groupToUpdateInDb.setDescription(group.getDescription());
948             }
949             // let's find out what policies have been deleted
950             StdPDPGroup oldGroup = null;
951             try {
952                 oldGroup = (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getId());
953             } catch (PAPException e1) {
954                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR,
955                         "We cannot get the group from the papEngine to delete policies");
956             }
957             if (oldGroup == null) {
958                 PolicyLogger.error("We cannot get the group from the papEngine to delete policies");
959             } else {
960                 Set<String> newPolicySet = new HashSet<>(group.getPolicies().size());
961                 // a multiple of n runtime is faster than n^2, so I am using a
962                 // hashset to do the comparison
963                 for (PDPPolicy pol : group.getPolicies()) {
964                     newPolicySet.add(pol.getId());
965                 }
966                 for (PDPPolicy pol : oldGroup.getPolicies()) {
967                     // should be fast since getPolicies uses a HashSet in
968                     // StdPDPGroup
969                     if (!newPolicySet.contains(pol.getId())) {
970                         String[] scopeAndName = policyDbDaoVar.getNameScopeAndVersionFromPdpPolicy(pol.getId());
971                         PolicyEntity policyToDelete = null;
972                         try {
973                             if (scopeAndName != null) {
974                                 policyToDelete = getPolicy(scopeAndName[0], scopeAndName[1]);
975                                 if ("XACMLPapServlet.doDelete".equals(requestType)) {
976                                     Iterator<PolicyEntity> dbPolicyIt = groupToUpdateInDb.getPolicies().iterator();
977                                     String policyName = policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
978                                             policyToDelete.getPolicyName())[0];
979
980                                     logger.info("PolicyDBDao: delete policy from GroupEntity");
981                                     try {
982                                         while (dbPolicyIt.hasNext()) {
983                                             PolicyEntity dbpolicy = dbPolicyIt.next();
984                                             if (policyToDelete.getScope().equals(dbpolicy.getScope())
985                                                     && policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName(
986                                                             dbpolicy.getPolicyName())[0].equals(policyName)) {
987                                                 dbPolicyIt.remove();
988                                                 auditPdpOperations(username,
989                                                         dbpolicy.getScope() + "." + dbpolicy.getPolicyName(), "Delete");
990                                                 logger.info("PolicyDBDao: deleting policy from the existing group:\n "
991                                                         + "policyName is " + policyToDelete.getScope() + "."
992                                                         + policyToDelete.getPolicyName() + "\n" + "group is "
993                                                         + groupToUpdateInDb.getGroupId());
994                                             }
995                                         }
996                                     } catch (Exception e) {
997                                         logger.debug(e);
998                                         PolicyLogger.error("Could not delete policy with name: "
999                                                 + policyToDelete.getScope() + "." + policyToDelete.getPolicyName()
1000                                                 + "\n ID: " + policyToDelete.getPolicyId());
1001                                     }
1002                                 }
1003                             }
1004                         } catch (Exception e) {
1005                             PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1006                                     "Could not get policy to remove: " + pol.getId());
1007                             throw new PersistenceException("Could not get policy to remove: " + pol.getId());
1008                         }
1009                     }
1010                 }
1011             }
1012
1013             if (group.getName() != null
1014                     && !PolicyDbDao.stringEquals(group.getName(), groupToUpdateInDb.getGroupName())) {
1015                 // we need to check if the new id exists in the database
1016                 String newGrpId = PolicyDbDao.createNewPdpGroupId(group.getName());
1017                 Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1018                 checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, newGrpId);
1019                 checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1020                 List<?> checkGroupQueryList;
1021                 try {
1022                     checkGroupQueryList = checkGroupQuery.list();
1023                 } catch (Exception e) {
1024                     PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1025                             "Caught Exception on checkGroupQuery.getResultList()");
1026                     throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
1027                 }
1028                 if (!checkGroupQueryList.isEmpty()) {
1029                     PolicyLogger.error("The new group name already exists, group id " + newGrpId);
1030                     throw new PersistenceException("The new group name already exists, group id " + newGrpId);
1031                 }
1032                 groupToUpdateInDb.setGroupId(newGrpId);
1033                 groupToUpdateInDb.setGroupName(group.getName());
1034                 this.newGroupId = group.getId();
1035             }
1036             session.flush();
1037             this.groupId = groupToUpdateInDb.getGroupKey();
1038         }
1039     }
1040
1041     @Override
1042     public void addPdpToGroup(String pdpId, String groupIdVar, String pdpName, String pdpDescription, int pdpJmxPort,
1043             String username) {
1044         logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, "
1045                 + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + pdpId + ", "
1046                 + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + username
1047                 + BRACKET_CALLED);
1048         if (PolicyDbDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) {
1049             throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty");
1050         }
1051         synchronized (emLock) {
1052             checkBeforeOperationRun();
1053             Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1054             checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar);
1055             checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1056             List<?> checkGroupQueryList;
1057             try {
1058                 checkGroupQueryList = checkGroupQuery.list();
1059             } catch (Exception e) {
1060                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1061                         "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()");
1062                 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
1063             }
1064             if (checkGroupQueryList.size() != 1) {
1065                 PolicyLogger.error("The group does not exist");
1066                 throw new PersistenceException("The group does not exist");
1067             }
1068             Query checkDuplicateQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1069             checkDuplicateQuery.setParameter(PolicyDbDao.PDP_ID, pdpId);
1070             checkDuplicateQuery.setParameter(PolicyDbDao.DELETED, false);
1071             List<?> checkDuplicateList;
1072             try {
1073                 checkDuplicateList = checkDuplicateQuery.list();
1074             } catch (Exception e) {
1075                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1076                         "Caught Exception trying to check for duplicate PDP " + pdpId
1077                                 + " on checkDuplicateQuery.getResultList()");
1078                 throw new PersistenceException("Query failed trying to check for duplicate PDP " + pdpId);
1079             }
1080             PdpEntity newPdp;
1081             if (!checkDuplicateList.isEmpty()) {
1082                 logger.warn("PDP already exists with id " + pdpId);
1083                 newPdp = (PdpEntity) checkDuplicateList.get(0);
1084             } else {
1085                 newPdp = new PdpEntity();
1086             }
1087
1088             newPdp.setCreatedBy(username);
1089             newPdp.setDeleted(false);
1090             newPdp.setDescription(pdpDescription);
1091             newPdp.setGroup((GroupEntity) checkGroupQueryList.get(0));
1092             newPdp.setJmxPort(pdpJmxPort);
1093             newPdp.setModifiedBy(username);
1094             newPdp.setPdpId(pdpId);
1095             newPdp.setPdpName(pdpName);
1096             if (isJunit) {
1097                 newPdp.prePersist();
1098             }
1099             session.persist(newPdp);
1100             session.flush();
1101             this.pdpId = newPdp.getPdpKey();
1102         }
1103     }
1104
1105     @Override
1106     public void updatePdp(OnapPDP pdp, String username) {
1107         logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + BRACKET_CALLED);
1108         if (pdp == null) {
1109             throw new IllegalArgumentException("PDP pdp must not be null");
1110         }
1111         if (PolicyDbDao.isNullOrEmpty(pdp.getId(), username)) {
1112             throw new IllegalArgumentException("pdp.getId() and username must not be null or empty");
1113         }
1114
1115         synchronized (emLock) {
1116             checkBeforeOperationRun();
1117             Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1118             getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId());
1119             getPdpQuery.setParameter(PolicyDbDao.DELETED, false);
1120             List<?> getPdpQueryList;
1121             try {
1122                 getPdpQueryList = getPdpQuery.list();
1123             } catch (Exception e) {
1124                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1125                         "Caught Exception on getPdpQuery.getResultList()");
1126                 throw new PersistenceException("Query failed trying to get PDP " + pdp.getId());
1127             }
1128             if (getPdpQueryList.isEmpty()) {
1129                 PolicyLogger.error("The pdp cannot be found to update with id " + pdp.getId());
1130                 throw new PersistenceException("The pdp cannot be found to update with id " + pdp.getId());
1131             } else if (getPdpQueryList.size() > 1) {
1132                 PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1133                 throw new PersistenceException(
1134                         PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1135             }
1136             PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1137             if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1138                 pdpToUpdate.setModifiedBy(username);
1139             }
1140             if (pdp.getDescription() != null
1141                     && !PolicyDbDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) {
1142                 pdpToUpdate.setDescription(pdp.getDescription());
1143             }
1144             if (pdp.getName() != null && !PolicyDbDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) {
1145                 pdpToUpdate.setPdpName(pdp.getName());
1146             }
1147             if (pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())) {
1148                 pdpToUpdate.setJmxPort(pdp.getJmxPort());
1149             }
1150
1151             session.flush();
1152             this.pdpId = pdpToUpdate.getPdpKey();
1153         }
1154     }
1155
1156     @Override
1157     public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) {
1158         logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + "," + group + ","
1159                 + username + BRACKET_CALLED);
1160         if (pdp == null || group == null) {
1161             throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null");
1162         }
1163         if (PolicyDbDao.isNullOrEmpty(username, pdp.getId(), group.getId())) {
1164             throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty");
1165         }
1166
1167         synchronized (emLock) {
1168             checkBeforeOperationRun();
1169             // check if pdp exists
1170             Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1171             getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId());
1172             getPdpQuery.setParameter(PolicyDbDao.DELETED, false);
1173             List<?> getPdpQueryList;
1174             try {
1175                 getPdpQueryList = getPdpQuery.list();
1176             } catch (Exception e) {
1177                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1178                         "Caught Exception on getPdpQuery.getResultList()");
1179                 throw new PersistenceException("Query failed trying to get pdp to move with id " + pdp.getId());
1180             }
1181             if (getPdpQueryList.isEmpty()) {
1182                 PolicyLogger.error("The pdp cannot be found to move with id " + pdp.getId());
1183                 throw new PersistenceException("The pdp cannot be found to move with id " + pdp.getId());
1184             } else if (getPdpQueryList.size() > 1) {
1185                 PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1186                 throw new PersistenceException(
1187                         PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1188             }
1189
1190             // check if new group exists
1191             Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1192             checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
1193             checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1194             List<?> checkGroupQueryList;
1195             try {
1196                 checkGroupQueryList = checkGroupQuery.list();
1197             } catch (Exception e) {
1198                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1199                         "Caught Exception trying to get group on checkGroupQuery.getResultList()");
1200                 throw new PersistenceException("Query failed trying to get new group " + group.getId());
1201             }
1202             if (checkGroupQueryList.size() != 1) {
1203                 PolicyLogger.error("The group " + group.getId() + " does not exist");
1204                 throw new PersistenceException("The group " + group.getId() + " does not exist");
1205             }
1206             GroupEntity groupToMoveInto = (GroupEntity) checkGroupQueryList.get(0);
1207             PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
1208             pdpToUpdate.setGroup(groupToMoveInto);
1209             if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
1210                 pdpToUpdate.setModifiedBy(username);
1211             }
1212
1213             session.flush();
1214             this.pdpId = pdpToUpdate.getPdpKey();
1215         }
1216     }
1217
1218     @Override
1219     public void changeDefaultGroup(OnapPDPGroup group, String username) {
1220         logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + ","
1221                 + username + BRACKET_CALLED);
1222         if (group == null) {
1223             throw new IllegalArgumentException("PDPGroup group must not be null");
1224         }
1225         if (PolicyDbDao.isNullOrEmpty(group.getId(), username)) {
1226             throw new IllegalArgumentException("group.getId() and username must not be null or empty");
1227         }
1228
1229         synchronized (emLock) {
1230             checkBeforeOperationRun();
1231             Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1232             getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
1233             getGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1234             List<?> getGroupQueryList;
1235             try {
1236                 getGroupQueryList = getGroupQuery.list();
1237             } catch (Exception e) {
1238                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1239                         "Caught Exception on getGroupQuery.getResultList()");
1240                 throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId());
1241             }
1242             if (getGroupQueryList.isEmpty()) {
1243                 PolicyLogger.error("The group cannot be found to set default with id " + group.getId());
1244                 throw new PersistenceException("The group cannot be found to set default with id " + group.getId());
1245             } else if (getGroupQueryList.size() > 1) {
1246                 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1247                 throw new PersistenceException(
1248                         PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
1249             }
1250             GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0);
1251             newDefaultGroup.setDefaultGroup(true);
1252             if (!PolicyDbDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) {
1253                 newDefaultGroup.setModifiedBy(username);
1254             }
1255
1256             session.flush();
1257             this.groupId = newDefaultGroup.getGroupKey();
1258             Query setAllGroupsNotDefault = session.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup "
1259                     + "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey");
1260             // not going to set modified by for all groups
1261             setAllGroupsNotDefault.setParameter("defaultGroup", false);
1262             setAllGroupsNotDefault.setParameter(PolicyDbDao.DELETED, false);
1263             setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey());
1264             try {
1265                 logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default");
1266             } catch (Exception e) {
1267                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1268                         "Caught Exception on setAllGroupsNotDefault.executeUpdate()");
1269                 throw new PersistenceException("Could not set all other groups default to false");
1270             }
1271             session.flush();
1272         }
1273     }
1274
1275     @Override
1276     public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDbException {
1277         logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup(" + group + ", "
1278                 + moveToGroup + "," + username + BRACKET_CALLED);
1279         if (group == null) {
1280             throw new IllegalArgumentException("PDPGroup group cannot be null");
1281         }
1282         if (PolicyDbDao.isNullOrEmpty(username, group.getId())) {
1283             throw new IllegalArgumentException("group.getId() and and username must not be null or empty");
1284         }
1285
1286         if (group.isDefaultGroup()) {
1287             PolicyLogger.error("The default group " + group.getId() + " was attempted to be deleted. It cannot be.");
1288             throw new PolicyDbException("You cannot delete the default group.");
1289         }
1290         synchronized (emLock) {
1291             checkBeforeOperationRun();
1292             Query deleteGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1293             deleteGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
1294             deleteGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1295             List<?> deleteGroupQueryList;
1296             try {
1297                 deleteGroupQueryList = deleteGroupQuery.list();
1298             } catch (Exception e) {
1299                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1300                         "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()");
1301                 throw new PersistenceException("Query failed trying to check if group exists");
1302             }
1303             if (deleteGroupQueryList.isEmpty()) {
1304                 logger.warn(PolicyDbDao.GROUP_NOT_FOUND + group.getId());
1305                 return;
1306             } else if (deleteGroupQueryList.size() > 1) {
1307                 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1308                 throw new PersistenceException(
1309                         PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1310             }
1311
1312             Query pdpsInGroupQuery =
1313                     session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted");
1314             pdpsInGroupQuery.setParameter(GROUP, (deleteGroupQueryList.get(0)));
1315             pdpsInGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1316             List<?> pdpsInGroupList;
1317             try {
1318                 pdpsInGroupList = pdpsInGroupQuery.list();
1319             } catch (Exception e) {
1320                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1321                         "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()");
1322                 throw new PersistenceException("Query failed trying to get PDPs in group");
1323             }
1324             if (!pdpsInGroupList.isEmpty()) {
1325                 if (moveToGroup != null) {
1326                     Query checkMoveToGroupQuery = session
1327                             .createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted");
1328                     checkMoveToGroupQuery.setParameter(PolicyDbDao.GROUP_ID, moveToGroup.getId());
1329                     checkMoveToGroupQuery.setParameter(PolicyDbDao.DELETED, false);
1330                     List<?> checkMoveToGroupList;
1331                     try {
1332                         checkMoveToGroupList = checkMoveToGroupQuery.list();
1333                     } catch (Exception e) {
1334                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1335                                 "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList");
1336                         throw new PersistenceException("Query failed trying to check if group exists");
1337                     }
1338                     if (checkMoveToGroupList.isEmpty()) {
1339                         PolicyLogger.error(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId());
1340                         throw new PersistenceException(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId());
1341                     } else if (checkMoveToGroupList.size() > 1) {
1342                         PolicyLogger.error(
1343                                 PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1344                         throw new PersistenceException(
1345                                 PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1346                     } else {
1347                         GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0);
1348                         for (Object pdpObject : pdpsInGroupList) {
1349                             PdpEntity pdp = (PdpEntity) pdpObject;
1350                             pdp.setGroup(newGroup);
1351                             if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) {
1352                                 pdp.setModifiedBy(username);
1353                             }
1354                             try {
1355                                 session.flush();
1356                                 this.newGroupId = newGroup.getGroupId();
1357                             } catch (PersistenceException e) {
1358                                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1359                                         "Caught PersistenceException trying to set pdp group to null on em.flush()");
1360                                 throw new PersistenceException("Query failed trying to set pdp group to ");
1361                             }
1362                         }
1363                     }
1364                 } else {
1365                     PolicyLogger.error("Group " + group.getId()
1366                             + " is trying to be delted with PDPs. No group was provided to move them to");
1367                     throw new PolicyDbException("Group has PDPs. Must provide a group for them to move to");
1368                 }
1369             }
1370
1371             // delete group here
1372             GroupEntity groupToDelete = (GroupEntity) deleteGroupQueryList.get(0);
1373             groupToDelete.setDeleted(true);
1374             if (!PolicyDbDao.stringEquals(groupToDelete.getModifiedBy(), username)) {
1375                 groupToDelete.setModifiedBy(username);
1376             }
1377             session.flush();
1378             this.groupId = groupToDelete.getGroupKey();
1379         }
1380     }
1381
1382     @Override
1383     public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, String username)
1384             throws PolicyDbException {
1385         logger.info(
1386                 "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup("
1387                         + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + BRACKET_CALLED);
1388         if (PolicyDbDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) {
1389             throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty");
1390         }
1391         synchronized (emLock) {
1392             checkBeforeOperationRun();
1393             // check if group exists
1394             Query groupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
1395             groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar);
1396             groupQuery.setParameter(PolicyDbDao.DELETED, false);
1397             List<?> groupQueryList;
1398             try {
1399                 groupQueryList = groupQuery.list();
1400             } catch (Exception e) {
1401                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1402                         "Caught Exception trying to check if group exists groupQuery.getResultList()");
1403                 throw new PersistenceException("Query failed trying to check if group " + groupIdVar + EXISTS);
1404             }
1405             if (groupQueryList.isEmpty()) {
1406                 PolicyLogger.error("Group policy is being added to does not exist with id " + groupIdVar);
1407                 throw new PersistenceException("Group policy is being added to does not exist with id " + groupIdVar);
1408             } else if (groupQueryList.size() > 1) {
1409                 PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1410                 throw new PersistenceException(
1411                         PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1412             }
1413
1414             // we need to convert the form of the policy id that is used groups
1415             // into the form that is used
1416             // for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml)
1417             PolicyDbDao policyDbDao = new PolicyDbDao();
1418             String[] policyNameScopeAndVersion = policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar);
1419             if (policyNameScopeAndVersion == null) {
1420                 throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version");
1421             }
1422             Query policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName "
1423                     + "AND p.scope=:scope AND p.deleted=:deleted");
1424             policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]);
1425             policyQuery.setParameter(PolicyDbDao.SCOPE, policyNameScopeAndVersion[1]);
1426             policyQuery.setParameter(PolicyDbDao.DELETED, false);
1427             List<?> policyQueryList;
1428             try {
1429                 policyQueryList = policyQuery.list();
1430             } catch (Exception e) {
1431                 logger.debug(e);
1432                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1433                         "Caught Exception trying to check if policy exists policyQuery.getResultList()");
1434                 throw new PersistenceException(
1435                         "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + EXISTS);
1436             }
1437             if (policyQueryList.isEmpty()) {
1438                 PolicyLogger.error("Policy being added to the group does not exist with policy id "
1439                         + policyNameScopeAndVersion[0]);
1440                 throw new PersistenceException("Policy being added to the group does not exist with policy id "
1441                         + policyNameScopeAndVersion[0]);
1442             } else if (policyQueryList.size() > 1) {
1443                 PolicyLogger.error(
1444                         PolicyDbDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1445                 throw new PersistenceException(
1446                         PolicyDbDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1447             }
1448             logger.info("PolicyDBDao: Getting group and policy from database");
1449             GroupEntity group = (GroupEntity) groupQueryList.get(0);
1450             PolicyEntity policy = (PolicyEntity) policyQueryList.get(0);
1451             Iterator<PolicyEntity> policyIt = group.getPolicies().iterator();
1452             String policyName = policyDbDao.getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0];
1453
1454             logger.info("PolicyDBDao: policyName retrieved is " + policyName);
1455             try {
1456                 while (policyIt.hasNext()) {
1457                     PolicyEntity pol = policyIt.next();
1458                     if (policy.getScope().equals(pol.getScope())
1459                             && policyDbDao.getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0]
1460                                     .equals(policyName)) {
1461                         policyIt.remove();
1462                     }
1463                 }
1464             } catch (Exception e) {
1465                 logger.debug(e);
1466                 PolicyLogger.error("Could not delete old versions for policy " + policy.getPolicyName() + ", ID: "
1467                         + policy.getPolicyId());
1468             }
1469             group.addPolicyToGroup(policy);
1470             auditPdpOperations(username, policy.getScope() + "." + policy.getPolicyName(), "Push");
1471             session.flush();
1472
1473             // After adding policy to the db group we need to make sure the
1474             // filesytem group is in sync with the db group
1475             try {
1476                 StdPDPGroup pdpGroup =
1477                         (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getGroupId());
1478                 return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group);
1479             } catch (PAPException e) {
1480                 logger.debug(e);
1481                 PolicyLogger.error("PolicyDBDao: Could not synchronize the filesystem group with the database group. "
1482                         + e.getMessage());
1483             }
1484             return null;
1485         }
1486     }
1487
1488     // this means delete pdp not just remove from group
1489     @Override
1490     public void removePdpFromGroup(String pdpId, String username) {
1491         logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpId + "," + username
1492                 + BRACKET_CALLED);
1493         if (PolicyDbDao.isNullOrEmpty(pdpId, username)) {
1494             throw new IllegalArgumentException("pdpID and username must not be null or empty");
1495         }
1496         synchronized (emLock) {
1497             checkBeforeOperationRun();
1498             Query pdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
1499             pdpQuery.setParameter(PolicyDbDao.PDP_ID, pdpId);
1500             pdpQuery.setParameter(PolicyDbDao.DELETED, false);
1501             List<?> pdpList;
1502             try {
1503                 pdpList = pdpQuery.list();
1504             } catch (Exception e) {
1505                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
1506                         "Caught Exception trying to check if pdp exists  pdpQuery.getResultList()");
1507                 throw new PersistenceException("Query failed trying to check if pdp " + pdpId + EXISTS);
1508             }
1509             if (pdpList.size() > 1) {
1510                 PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1511                 throw new PersistenceException(
1512                         "Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
1513             } else if (pdpList.isEmpty()) {
1514                 PolicyLogger.error("Pdp being removed does not exist with id " + pdpId);
1515                 return;
1516             }
1517             PdpEntity pdp = (PdpEntity) pdpList.get(0);
1518             if (!isJunit) {
1519                 pdp.setGroup(null);
1520             }
1521
1522             if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) {
1523                 pdp.setModifiedBy(username);
1524             }
1525             pdp.setDeleted(true);
1526
1527             session.flush();
1528             this.pdpId = pdp.getPdpKey();
1529         }
1530     }
1531
1532     private static String evaluateXPath(String expression, String xml) {
1533         InputSource source = new InputSource(new StringReader(xml));
1534
1535         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1536         String description = "";
1537         try {
1538             DocumentBuilder db = dbf.newDocumentBuilder();
1539             Document document = db.parse(source);
1540
1541             XPathFactory xpathFactory = XPathFactory.newInstance();
1542             XPath xpath = xpathFactory.newXPath();
1543
1544             description = xpath.evaluate(expression, document);
1545         } catch (Exception e) {
1546             logger.error("Exception Occured while evaluating path" + e);
1547         }
1548         return description;
1549     }
1550
1551     public static boolean isJunit() {
1552         return isJunit;
1553     }
1554
1555     public static void setJunit(boolean isJunit) {
1556         PolicyDbDaoTransactionInstance.isJunit = isJunit;
1557     }
1558
1559     /**
1560      * Audit pdp operations.
1561      *
1562      * @param username the username
1563      * @param policyID the policy ID
1564      * @param action the action
1565      */
1566     public void auditPdpOperations(String username, String policyID, String action) {
1567         PolicyAuditlog log = new PolicyAuditlog();
1568         log.setUserName(username);
1569         log.setActions(action);
1570         log.setPolicyName(policyID);
1571         log.setDateAndTime(new Date());
1572         session.save(log);
1573     }
1574 }