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