2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.pap.xacml.rest.components;
23 import java.io.ByteArrayInputStream;
25 import java.io.FileInputStream;
26 import java.io.FileNotFoundException;
27 import java.io.FileWriter;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.StringReader;
31 import java.io.UnsupportedEncodingException;
32 import java.net.HttpURLConnection;
33 import java.net.MalformedURLException;
34 import java.net.ProtocolException;
37 import java.nio.charset.StandardCharsets;
38 import java.nio.file.Files;
39 import java.nio.file.InvalidPathException;
40 import java.nio.file.Path;
41 import java.nio.file.Paths;
42 import java.security.InvalidKeyException;
43 import java.security.Key;
44 import java.security.NoSuchAlgorithmException;
45 import java.util.Base64;
46 import java.util.Date;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.Iterator;
50 import java.util.LinkedList;
51 import java.util.List;
54 import java.util.UUID;
56 import javax.crypto.BadPaddingException;
57 import javax.crypto.Cipher;
58 import javax.crypto.IllegalBlockSizeException;
59 import javax.crypto.NoSuchPaddingException;
60 import javax.crypto.spec.SecretKeySpec;
61 import javax.persistence.EntityManager;
62 import javax.persistence.EntityManagerFactory;
63 import javax.persistence.LockModeType;
64 import javax.persistence.PersistenceException;
65 import javax.persistence.Query;
66 import javax.persistence.RollbackException;
67 import javax.xml.parsers.DocumentBuilder;
68 import javax.xml.parsers.DocumentBuilderFactory;
69 import javax.xml.xpath.XPath;
70 import javax.xml.xpath.XPathFactory;
72 import org.apache.commons.io.FilenameUtils;
73 import org.apache.commons.io.IOUtils;
74 import org.elasticsearch.common.Strings;
75 import org.onap.policy.common.logging.eelf.MessageCodes;
76 import org.onap.policy.common.logging.eelf.PolicyLogger;
77 import org.onap.policy.common.logging.flexlogger.FlexLogger;
78 import org.onap.policy.common.logging.flexlogger.Logger;
79 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
80 import org.onap.policy.rest.XACMLRestProperties;
81 import org.onap.policy.rest.adapter.PolicyRestAdapter;
82 import org.onap.policy.rest.dao.PolicyDBException;
83 import org.onap.policy.rest.jpa.ActionBodyEntity;
84 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
85 import org.onap.policy.rest.jpa.DatabaseLockEntity;
86 import org.onap.policy.rest.jpa.GroupEntity;
87 import org.onap.policy.rest.jpa.PdpEntity;
88 import org.onap.policy.rest.jpa.PolicyDBDaoEntity;
89 import org.onap.policy.rest.jpa.PolicyEntity;
90 import org.onap.policy.rest.util.Webapps;
91 import org.onap.policy.xacml.api.pap.OnapPDP;
92 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
93 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
94 import org.onap.policy.xacml.std.pap.StdPDPGroup;
95 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
96 import org.onap.policy.xacml.util.XACMLPolicyWriter;
97 import org.w3c.dom.Document;
98 import org.xml.sax.InputSource;
100 import com.att.research.xacml.api.pap.PAPException;
101 import com.att.research.xacml.api.pap.PDP;
102 import com.att.research.xacml.api.pap.PDPPolicy;
103 import com.att.research.xacml.util.XACMLProperties;
105 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
107 public class PolicyDBDao {
108 private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class);
109 private List<?> otherServers;
110 private EntityManagerFactory emf;
111 private static PolicyDBDao currentInstance = null;
112 private PAPPolicyEngine papEngine;
114 public static final String JSON_CONFIG = "JSON";
115 public static final String XML_CONFIG = "XML";
116 public static final String PROPERTIES_CONFIG = "PROPERTIES";
117 public static final String OTHER_CONFIG = "OTHER";
118 public static final String AUDIT_USER = "audit";
121 * Get an instance of a PolicyDBDao. It creates one if it does not exist.
122 * Only one instance is allowed to be created per server.
123 * @param emf The EntityFactoryManager to be used for database connections
124 * @return The new instance of PolicyDBDao or throw exception if the given emf is null.
125 * @throws IllegalStateException if a PolicyDBDao has already been constructed. Call getPolicyDBDaoInstance() to get this.
127 public static PolicyDBDao getPolicyDBDaoInstance(EntityManagerFactory emf){
128 logger.debug("getPolicyDBDaoInstance(EntityManagerFactory emf) as getPolicyDBDaoInstance("+emf+") called");
129 if(currentInstance == null){
131 currentInstance = new PolicyDBDao(emf);
132 return currentInstance;
134 throw new IllegalStateException("The EntityManagerFactory is Null");
136 return currentInstance;
140 * Gets the current instance of PolicyDBDao.
141 * @return The instance of PolicyDBDao or throws exception if the given instance is null.
142 * @throws IllegalStateException if a PolicyDBDao instance is null. Call createPolicyDBDaoInstance(EntityManagerFactory emf) to get this.
144 public static PolicyDBDao getPolicyDBDaoInstance(){
145 logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called");
146 if(currentInstance != null){
147 return currentInstance;
149 throw new IllegalStateException("The PolicyDBDao.currentInstance is Null. Use getPolicyDBDao(EntityManagerFactory emf)");
151 public void setPapEngine(PAPPolicyEngine papEngine2){
152 this.papEngine = (PAPPolicyEngine) papEngine2;
154 private PolicyDBDao(EntityManagerFactory emf){
155 logger.debug("PolicyDBDao(EntityManagerFactory emf) as PolicyDBDao("+emf+") called");
158 //not needed in this release
160 PolicyLogger.error("This server's PolicyDBDao instance could not be registered and may not reveive updates");
163 otherServers = getRemotePolicyDBDaoList();
164 if(logger.isDebugEnabled()){
165 logger.debug("Number of remote PolicyDBDao instances: "+otherServers.size());
167 if(otherServers.isEmpty()){
168 logger.warn("List of PolicyDBDao servers is empty or could not be retrieved");
172 //not static because we are going to be using the instance's emf
173 //waitTime in ms to wait for lock, or -1 to wait forever (no)
174 private void startTransactionSynced(EntityManager entityMgr,int waitTime){
175 logger.debug("\n\nstartTransactionSynced(EntityManager entityMgr,int waitTime) as "
176 + "\n startTransactionSynced("+entityMgr+","+waitTime+") called\n\n");
177 DatabaseLockEntity lock = null;
179 entityMgr.setProperty("javax.persistence.query.timeout", waitTime);
180 entityMgr.getTransaction().begin();
182 if(logger.isDebugEnabled()){
183 Map<String,Object> properties = entityMgr.getProperties();
184 logger.debug("\n\nstartTransactionSynced():"
185 + "\n entityManager.getProperties() = " + properties
189 if(logger.isDebugEnabled()){
190 logger.debug("\n\nstartTransactionSynced():"
191 + "\n ATTEMPT to get the DB lock"
194 lock = entityMgr.find(DatabaseLockEntity.class, 1, LockModeType.PESSIMISTIC_WRITE);
195 if(logger.isDebugEnabled()){
196 logger.debug("\n\nstartTransactionSynced():"
197 + "\n GOT the DB lock"
200 } catch(Exception e){
201 System.out.println("Could not get lock entity");
202 logger.error("Exception Occured"+e);
205 throw new IllegalStateException("The lock row does not exist in the table. Please create a primary key with value = 1.");
210 * Gets the list of other registered PolicyDBDaos from the database
211 * @return List (type PolicyDBDaoEntity) of other PolicyDBDaos
213 private List<?> getRemotePolicyDBDaoList(){
214 logger.debug("getRemotePolicyDBDaoList() as getRemotePolicyDBDaoList() called");
215 List<?> policyDBDaoEntityList = new LinkedList<>();
216 EntityManager em = emf.createEntityManager();
217 startTransactionSynced(em, 1000);
219 Query getPolicyDBDaoEntityQuery = em.createNamedQuery("PolicyDBDaoEntity.findAll");
220 policyDBDaoEntityList = getPolicyDBDaoEntityQuery.getResultList();
222 } catch(Exception e){
223 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Exception querying for other registered PolicyDBDaos");
224 logger.warn("List of remote PolicyDBDaos will be empty", e);
227 em.getTransaction().commit();
228 } catch(Exception e){
229 logger.warn("List of remote PolicyDBDaos will be empty", e);
231 em.getTransaction().rollback();
232 } catch(Exception e2){
233 logger.debug("List of remote PolicyDBDaos will be empty", e2);
237 return policyDBDaoEntityList;
240 public PolicyDBDaoTransaction getNewTransaction(){
241 logger.debug("getNewTransaction() as getNewTransaction() called");
242 return (PolicyDBDaoTransaction)(new PolicyDBDaoTransactionInstance());
246 * Because the normal transactions are not used in audits, we can use the same transaction
247 * mechanism to get a transaction and obtain the emlock and the DB lock. We just need to
248 * provide different transaction timeout values in ms because the audit will run longer
249 * than normal transactions.
251 public PolicyDBDaoTransaction getNewAuditTransaction(){
252 logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called");
253 //Use the standard transaction wait time in ms
254 int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
255 //Use the (extended) audit timeout time in ms
256 int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
257 return (PolicyDBDaoTransaction)(new PolicyDBDaoTransactionInstance(auditTimeoutMs, auditWaitMs));
262 * Checks if two strings are equal. Null strings ARE allowed.
263 * @param one A String or null to compare
264 * @param two A String or null to compare
266 private static boolean stringEquals(String one, String two){
267 logger.debug("stringEquals(String one, String two) as stringEquals("+one+", "+two+") called");
268 if(one == null && two == null){
271 if(one == null || two == null){
274 return one.equals(two);
278 * Computes the scope in dotted format based on an absolute path and a path that divides the scope.
279 * @param fullPath An absolute path including scope folders and other folders(does not have to be absolute, must just contain scope and other folders before)
280 * @param pathToExclude The path that acts as a division between the scope and the other folders
281 * @return The scope in dotted format (org.onap)
283 private static String computeScope(String fullPath, String pathToExclude){
284 logger.debug("computeScope(String fullPath, String pathToExclude) as computeScope("+fullPath+", "+pathToExclude+") called");
285 int excludeIndex = fullPath.indexOf(pathToExclude);
286 String scopePath = fullPath.substring(excludeIndex+pathToExclude.length());
287 String scope = scopePath.replace('\\', '.');
288 scope = scope.replace('/', '.');
289 if(scope.charAt(0) == '.'){
290 scope = scope.substring(1);
292 if(scope.charAt(scope.length()-1) == '.'){
293 scope = scope.substring(0, scope.length()-1);
299 * Returns the url of this local pap server, removing the username and password, if they are present
300 * @return The url of this local pap server
302 private String[] getPapUrlUserPass(){
303 logger.debug("getPapUrl() as getPapUrl() called");
304 String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
308 return splitPapUrlUserPass(url);
312 private String[] splitPapUrlUserPass(String url){
313 String[] urlUserPass = new String[3];
314 String[] commaSplit = url.split(",");
315 urlUserPass[0] = commaSplit[0];
316 if(commaSplit.length > 2){
317 urlUserPass[1] = commaSplit[1];
318 urlUserPass[2] = commaSplit[2];
320 if(urlUserPass[1] == null || urlUserPass[1].equals("")){
321 String usernamePropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
322 if(usernamePropertyValue != null){
323 urlUserPass[1] = usernamePropertyValue;
326 if(urlUserPass[2] == null || urlUserPass[2].equals("")){
327 String passwordPropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
328 if(passwordPropertyValue != null){
329 urlUserPass[2] = passwordPropertyValue;
332 //if there is no comma, for some reason there is no username and password, so don't try to cut them off
336 private static String encryptPassword(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
337 Cipher cipher = Cipher.getInstance("AES");
338 cipher.init(Cipher.ENCRYPT_MODE, aesKey());
339 byte[] encryption = cipher.doFinal(password.getBytes("UTF-8"));
340 logger.debug("Encryption value is " + encryption);
341 return new String(Base64.getMimeEncoder().encode(encryption),"UTF-8");
344 private static String decryptPassword(String encryptedPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
345 Cipher cipher = Cipher.getInstance("AES");
346 cipher.init(Cipher.DECRYPT_MODE, aesKey());
347 byte[] password = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword.getBytes("UTF-8")));
348 return new String(password,"UTF-8");
350 private static Key aesKey(){
351 byte[] aesValue = (new String("njrmbklcxtoplawf")).getBytes();
352 return new SecretKeySpec(aesValue,"AES");
355 * Register the PolicyDBDao instance in the PolicyDBDaoEntity table
356 * @return Boolean, were we able to register?
358 private boolean register(){
359 logger.debug("register() as register() called");
360 String[] url = getPapUrlUserPass();
361 EntityManager em = emf.createEntityManager();
363 startTransactionSynced(em, 1000);
364 } catch(IllegalStateException e){
365 logger.debug ("\nPolicyDBDao.register() caught an IllegalStateException: \n" +e + "\n");
366 DatabaseLockEntity lock;
367 lock = em.find(DatabaseLockEntity.class, 1);
369 lock = new DatabaseLockEntity();
374 em.getTransaction().commit();
376 } catch(Exception e2){
377 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "COULD NOT CREATE DATABASELOCK ROW. WILL TRY ONE MORE TIME");
380 em = emf.createEntityManager();
382 startTransactionSynced(em, 1000);
383 } catch(Exception e3){
384 String msg = "DATABASE LOCKING NOT WORKING. CONCURRENCY CONTROL NOT WORKING";
385 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e3, "PolicyDBDao", msg);
386 throw new IllegalStateException("msg" + "\n" + e3);
390 logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n");
391 PolicyDBDaoEntity foundPolicyDBDaoEntity = em.find(PolicyDBDaoEntity.class, url[0]);
392 Query getPolicyDBDaoEntityQuery = em.createQuery("SELECT e FROM PolicyDBDaoEntity e WHERE e.policyDBDaoUrl=:url");
393 getPolicyDBDaoEntityQuery.setParameter("url", url[0]);
394 if(foundPolicyDBDaoEntity == null){
395 PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity();
396 em.persist(newPolicyDBDaoEntity);
397 newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]);
398 newPolicyDBDaoEntity.setDescription("PAP server at "+url[0]);
399 newPolicyDBDaoEntity.setUsername(url[1]);
401 newPolicyDBDaoEntity.setPassword(encryptPassword(url[2]));
402 } catch(Exception e){
404 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not encrypt PAP password");
407 em.getTransaction().commit();
408 } catch(Exception e){
411 em.getTransaction().rollback();
412 } catch(Exception e2){
414 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Could not add new PolicyDBDao to the database");
418 //just want to update in order to change modified date
419 String encryptedPassword = null;
421 encryptedPassword = encryptPassword(url[2]);
422 } catch(Exception e){
424 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not encrypt PAP password");
426 if(url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())){
427 foundPolicyDBDaoEntity.setUsername(url[1]);
429 if(encryptedPassword != null && !stringEquals(encryptedPassword, foundPolicyDBDaoEntity.getPassword())){
430 foundPolicyDBDaoEntity.setPassword(encryptedPassword);
432 foundPolicyDBDaoEntity.preUpdate();
434 em.getTransaction().commit();
435 } catch(Exception e){
438 em.getTransaction().rollback();
439 } catch(Exception e2){
441 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Could not update PolicyDBDao in the database");
446 logger.debug("\nPolicyDBDao.register(). Success!!\n");
449 public void notifyOthers(long entityId,String entityType){
450 notifyOthers(entityId,entityType,null);
452 public void notifyOthers(long entityId, String entityType, String newGroupId){
453 logger.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers("+entityId+","+entityType+","+newGroupId+") called");
454 LinkedList<Thread> notifyThreads = new LinkedList<>();
456 //we're going to run notifications in parallel threads to speed things up
457 for(Object obj : otherServers){
459 Thread newNotifyThread = new Thread(new NotifyOtherThread(obj, entityId, entityType, newGroupId));
461 newNotifyThread.start();
463 notifyThreads.add(newNotifyThread);
466 //we want to wait for all notifications to complete or timeout before we unlock the interface and allow more changes
467 for(Thread t : notifyThreads){
470 } catch (Exception e) {
471 logger.warn("Could not join a notifcation thread" + e);
478 private class NotifyOtherThread implements Runnable {
479 public NotifyOtherThread(Object obj, long entityId, String entityType, String newGroupId){
481 this.entityId = entityId;
482 this.entityType = entityType;
483 this.newGroupId = newGroupId;
486 private long entityId;
487 private String entityType;
488 private String newGroupId;
491 //naming of 'o' is for backwards compatibility with the rest of the function
492 PolicyDBDaoEntity dbdEntity = (PolicyDBDaoEntity)obj;
493 String o = dbdEntity.getPolicyDBDaoUrl();
494 String username = dbdEntity.getUsername();
497 password = decryptPassword(dbdEntity.getPassword());
498 } catch(Exception e){
500 //if we can't decrypt, might as well try it anyway
501 password = dbdEntity.getPassword();
503 Base64.Encoder encoder = Base64.getEncoder();
504 String encoding = encoder.encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
505 HttpURLConnection connection = null;
506 UUID requestID = UUID.randomUUID();
509 String papUrl = getPapUrlUserPass()[0];
511 papUrl = "undefined";
513 logger.debug("We are going to try to notify "+o);
514 //is this our own url?
517 ourUrl = splitPapUrlUserPass((String)o)[0];
525 if(papUrl.equals(ourUrl)){
526 logger.debug(((String)o)+" is our url, skipping notify");
529 if(newGroupId == null){
530 url = new URL(((String)o)+"?policydbdaourl="+papUrl+"&entityid="+entityId+"&entitytype="+entityType);
532 url = new URL(((String)o)+"?policydbdaourl="+papUrl+"&entityid="+entityId+"&entitytype="+entityType+"&extradata="+newGroupId);
534 } catch (MalformedURLException e) {
535 logger.warn("Caught MalformedURLException on: new URL()", e);
539 // Open up the connection
541 logger.info("PolicyDBDao: NotifyOtherThread: notifying other PAPs of an update");
542 logger.info("Connecting with url: "+url);
544 connection = (HttpURLConnection)url.openConnection();
545 } catch (Exception e) {
546 logger.warn("Caught exception on: url.openConnection()",e);
550 // Setup our method and headers
553 connection.setRequestMethod("PUT");
554 } catch (ProtocolException e) {
555 //why would this error ever occur?
556 logger.warn("Caught ProtocolException on connection.setRequestMethod(\"PUT\");",e);
559 connection.setRequestProperty("Authorization", "Basic " + encoding);
560 connection.setRequestProperty("Accept", "text/x-java-properties");
561 connection.setRequestProperty("Content-Type", "text/x-java-properties");
562 connection.setRequestProperty("requestID", requestID.toString());
565 readTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_NOTIFY_TIMEOUT));
567 } catch(Exception e){
568 logger.error("xacml.rest.pap.notify.timeoutms property not set, using a default.", e);
571 connection.setReadTimeout(readTimeout);
572 connection.setConnectTimeout(readTimeout);
573 connection.setUseCaches(false);
575 // Adding this in. It seems the HttpUrlConnection class does NOT
576 // properly forward our headers for POST re-direction. It does so
577 // for a GET re-direction.
579 // So we need to handle this ourselves.
581 connection.setInstanceFollowRedirects(false);
582 connection.setDoOutput(true);
583 connection.setDoInput(true);
585 connection.connect();
586 } catch (Exception e) {
587 logger.warn("Caught exception on: connection.connect()",e);
591 if (connection.getResponseCode() == 200) {
592 logger.info("PolicyDBDao: NotifyOtherThread received response 200 from pap server on notify");
594 logger.warn("PolicyDBDao: NotifyOtherThread connection response code not 200, received: "+connection.getResponseCode());
596 } catch (Exception e) {
597 logger.warn("Caught Exception on: connection.getResponseCode() ", e);
600 connection.disconnect();
604 private static String evaluateXPath(String expression, String xml) {
605 InputSource source = new InputSource(new StringReader(xml));
607 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
608 String description = "";
610 DocumentBuilder db = dbf.newDocumentBuilder();
611 Document document = db.parse(source);
613 XPathFactory xpathFactory = XPathFactory.newInstance();
614 XPath xpath = xpathFactory.newXPath();
617 description = xpath.evaluate(expression, document);
619 logger.error("Exception Occured while evaluating path"+e);
625 private static String getDescriptionFromXacml(String xacmlData){
626 String openTag = "<Description>";
627 String closeTag = "</Description>";
628 int descIndex = xacmlData.indexOf(openTag);
629 int endDescIndex = xacmlData.indexOf(closeTag);
630 String desc = xacmlData.substring(descIndex+openTag.length(),endDescIndex);
634 private final String POLICY_NOTIFICATION = "policy";
635 private final String PDP_NOTIFICATION = "pdp";
636 private final String GROUP_NOTIFICATION = "group";
637 public void handleIncomingHttpNotification(String url, String entityId, String entityType, String extraData, XACMLPapServlet xacmlPapServlet){
638 logger.info("DBDao url: " + url + " has reported an update on "+entityType+" entity "+entityId);
639 PolicyDBDaoTransaction transaction = this.getNewTransaction();
640 //although its named retries, this is the total number of tries
643 retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INCOMINGNOTIFICATION_TRIES));
645 } catch(Exception e){
646 logger.error("xacml.rest.pap.incomingnotification.tries property not set, using a default of 3."+e);
649 //if someone sets it to some dumb value, we need to make sure it will try at least once
653 int pauseBetweenRetries = 1000;
656 case POLICY_NOTIFICATION:
657 for(int i=0; i<retries;i++){
659 handleIncomingPolicyChange(url, entityId,extraData);
661 } catch(Exception e){
663 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught exception on handleIncomingPolicyChange("+url+", "+entityId+", "+extraData+")");
666 Thread.sleep(pauseBetweenRetries);
667 }catch(InterruptedException ie){
668 Thread.currentThread().interrupt();
673 case PDP_NOTIFICATION:
674 for(int i=0; i<retries;i++){
676 handleIncomingPdpChange(url, entityId, transaction);
678 } catch(Exception e){
680 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught exception on handleIncomingPdpChange("+url+", "+entityId+", "+transaction+")");
683 Thread.sleep(pauseBetweenRetries);
684 }catch(InterruptedException ie){
685 Thread.currentThread().interrupt();
690 case GROUP_NOTIFICATION:
691 for(int i=0; i<retries;i++){
693 handleIncomingGroupChange(entityId, extraData, transaction, xacmlPapServlet);
697 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught exception on handleIncomingGroupChange("+url+", "+entityId+", "+extraData+", "+transaction+", "+xacmlPapServlet+")");
700 Thread.sleep(pauseBetweenRetries);
701 }catch(InterruptedException ie){
702 Thread.currentThread().interrupt();
708 //no changes should be being made in this function, we still need to close
709 transaction.rollbackTransaction();
711 private void handleIncomingGroupChange(String groupId, String extraData,PolicyDBDaoTransaction transaction,XACMLPapServlet xacmlPapServlet) throws PAPException, PolicyDBException{
712 GroupEntity groupRecord = null;
713 long groupIdLong = -1;
715 groupIdLong = Long.parseLong(groupId);
716 } catch(NumberFormatException e){
717 throw new IllegalArgumentException("groupId "+groupId+" cannot be parsed into a long");
720 groupRecord = transaction.getGroup(groupIdLong);
721 } catch(Exception e){
722 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get pdp group record with transaction.getGroup("+groupIdLong+");");
723 throw new PAPException("Could not get local group "+groupIdLong);
725 if(groupRecord == null){
726 throw new PersistenceException("The group record returned is null");
728 //compare to local fs
729 //does group folder exist
730 OnapPDPGroup localGroup = null;
732 localGroup = papEngine.getGroup(groupRecord.getGroupId());
733 } catch (Exception e) {
734 logger.warn("Caught PAPException trying to get local pdp group with papEngine.getGroup("+groupId+");",e);
736 if(localGroup == null && extraData != null){
737 //here we can try to load an old group id from the extraData
739 localGroup = papEngine.getGroup(extraData);
741 logger.warn("Caught PAPException trying to get local pdp group with papEngine.getGroup("+extraData+");",e);
744 if(localGroup != null && groupRecord.isDeleted()){
745 OnapPDPGroup newLocalGroup = null;
746 if(extraData != null){
748 newLocalGroup = papEngine.getGroup(extraData);
749 } catch (PAPException e) {
750 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to get new pdp group with papEngine.getGroup("+extraData+");");
754 papEngine.removeGroup(localGroup, newLocalGroup);
755 } catch (NullPointerException | PAPException e) {
756 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to get remove pdp group with papEngine.removeGroup("+localGroup+", "+newLocalGroup+");");
757 throw new PAPException("Could not remove group "+groupId);
760 else if(localGroup == null){
761 //creating a new group
763 papEngine.newGroup(groupRecord.getgroupName(), groupRecord.getDescription());
764 } catch (NullPointerException | PAPException e) {
765 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to create pdp group with papEngine.newGroup(groupRecord.getgroupName(), groupRecord.getDescription());");
766 throw new PAPException("Could not create group "+groupRecord);
769 localGroup = papEngine.getGroup(groupRecord.getGroupId());
770 } catch (PAPException e1) {
771 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Caught PAPException trying to get pdp group we just created with papEngine.getGroup(groupRecord.getGroupId());\nAny PDPs or policies in the new group may not have been added");
774 //add possible pdps to group
775 List<?> pdpsInGroup = transaction.getPdpsInGroup(Long.parseLong(groupRecord.getGroupId()));
776 for(Object pdpO : pdpsInGroup){
777 PdpEntity pdp = (PdpEntity)pdpO;
779 papEngine.newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());
780 } catch (NullPointerException | PAPException e) {
781 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());");
782 throw new PAPException("Could not create pdp "+pdp);
785 //add possible policies to group (filesystem only, apparently)
787 if(!(localGroup instanceof StdPDPGroup)){
788 throw new PAPException("group is not a StdPDPGroup");
791 //because it will be comparing the new group to its own version
792 StdPDPGroup localGroupClone = new StdPDPGroup(localGroup.getId(),localGroup.isDefaultGroup(),localGroup.getName(),localGroup.getDescription(),((StdPDPGroup)localGroup).getDirectory());
793 localGroupClone.setOnapPdps(localGroup.getOnapPdps());
794 localGroupClone.setPipConfigs(localGroup.getPipConfigs());
795 localGroupClone.setStatus(localGroup.getStatus());
796 //we are updating a group or adding a policy or changing default
797 //set default if it should be
798 if(!localGroupClone.isDefaultGroup() && groupRecord.isDefaultGroup()){
800 papEngine.setDefaultGroup(localGroup);
802 } catch (PAPException e) {
803 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to set default group with papEngine.SetDefaultGroup("+localGroupClone+");");
804 throw new PAPException("Could not set default group to "+localGroupClone);
807 boolean needToUpdate = false;
808 if(updateGroupPoliciesInFileSystem(localGroupClone,localGroup, groupRecord, transaction)){
811 if(!stringEquals(localGroupClone.getId(),groupRecord.getGroupId()) || !stringEquals(localGroupClone.getName(),groupRecord.getgroupName())){
813 //we do not want to change the id, the papEngine will do this for us, it needs to know the old id
814 localGroupClone.setName(groupRecord.getgroupName());
817 if(!stringEquals(localGroupClone.getDescription(),groupRecord.getDescription())){
818 localGroupClone.setDescription(groupRecord.getDescription());
824 papEngine.updateGroup(localGroupClone);
825 } catch (PAPException e) {
826 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to update group with papEngine.updateGroup("+localGroupClone+");");
827 throw new PAPException("Could not update group "+localGroupClone);
832 //call command that corresponds to the change that was made
834 //this will also handle removes, since incoming pdpGroup has no policies internally, we are just going to add them all in from the db
835 private boolean updateGroupPoliciesInFileSystem(OnapPDPGroup pdpGroup,OnapPDPGroup oldPdpGroup, GroupEntity groupRecord, PolicyDBDaoTransaction transaction) throws PAPException, PolicyDBException{
836 if(!(pdpGroup instanceof StdPDPGroup)){
837 throw new PAPException("group is not a StdPDPGroup");
839 StdPDPGroup group = (StdPDPGroup)pdpGroup;
840 //this must always be true since we don't explicitly know when a delete is occuring
841 boolean didUpdate = true;
842 HashMap<String,PDPPolicy> currentPolicySet = new HashMap<String,PDPPolicy>(oldPdpGroup.getPolicies().size());
843 HashSet<PDPPolicy> newPolicySet = new HashSet<>();
844 for(PDPPolicy pdpPolicy : oldPdpGroup.getPolicies()){
845 currentPolicySet.put(pdpPolicy.getId(), pdpPolicy);
847 for(PolicyEntity policy : groupRecord.getPolicies()){
848 String pdpPolicyName = getPdpPolicyName(policy.getPolicyName(), policy.getScope());
849 if(group.getPolicy(pdpPolicyName) == null){
851 if(currentPolicySet.containsKey(pdpPolicyName)){
852 newPolicySet.add(currentPolicySet.get(pdpPolicyName));
854 logger.info("PolicyDBDao: Adding the new policy to the PDP group after notification: " + pdpPolicyName);
855 InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes());
856 group.copyPolicyToFile(pdpPolicyName,policyStream);
857 ((StdPDPPolicy)(group.getPolicy(pdpPolicyName))).setName(removeExtensionAndVersionFromPolicyName(pdpPolicyName));
859 policyStream.close();
860 } catch (IOException e) {
862 PolicyLogger.error(e.getMessage() +e);
867 logger.info("PolicyDBDao: Adding updated policies to group after notification.");
869 newPolicySet.addAll(group.getPolicies());
870 group.setPolicies(newPolicySet);
877 * This method is called during all pushPolicy transactions and makes sure the file system
878 * group is in sync with the database groupentity
880 private StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity) throws PAPException, PolicyDBException{
882 HashMap<String,PDPPolicy> currentPolicyMap = new HashMap<>();
883 HashSet<String> newPolicyIdSet = new HashSet<>();
884 HashSet<PDPPolicy> newPolicySet = new HashSet<>();
886 for(PDPPolicy pdpPolicy : pdpGroup.getPolicies()){
887 currentPolicyMap.put(pdpPolicy.getId(), pdpPolicy);
890 for(PolicyEntity policy : groupentity.getPolicies()){
891 String pdpPolicyId = getPdpPolicyName(policy.getPolicyName(), policy.getScope());
892 newPolicyIdSet.add(pdpPolicyId);
894 if(currentPolicyMap.containsKey(pdpPolicyId)){
895 newPolicySet.add(currentPolicyMap.get(pdpPolicyId));
898 //convert PolicyEntity object to PDPPolicy
899 String name = pdpPolicyId.replace(".xml", "");
900 name = name.substring(0, name.lastIndexOf('.'));
901 InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes());
902 pdpGroup.copyPolicyToFile(pdpPolicyId,name,policyStream);
903 URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri();
904 StdPDPPolicy newPolicy = null;
906 newPolicy = new StdPDPPolicy(pdpPolicyId, true, removeExtensionAndVersionFromPolicyName(pdpPolicyId),location);
907 newPolicySet.add(newPolicy);
908 } catch (Exception e) {
910 PolicyLogger.error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + e.getMessage());
917 for(String id : currentPolicyMap.keySet()) {
918 if(!newPolicyIdSet.contains(id)){
920 Files.delete(Paths.get(currentPolicyMap.get(id).getLocation()));
921 } catch (Exception e) {
923 PolicyLogger.error("PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. " + e.getMessage());
928 logger.info("PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync");
929 pdpGroup.setPolicies(newPolicySet);
934 private String removeExtensionAndVersionFromPolicyName(String originalPolicyName) throws PolicyDBException{
935 return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0];
939 * Splits apart the policy name and version from a policy file path
940 * @param originalPolicyName: a policy file name ex: Config_policy.2.xml
941 * @return An array [0]: The policy name, [1]: the policy version, as a string
943 private String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException{
944 String policyName = originalPolicyName;
945 String[] nameAndVersion = new String[2];
947 policyName = removeFileExtension(policyName);
948 nameAndVersion[0] = policyName.substring(0,policyName.lastIndexOf('.'));
949 if(isNullOrEmpty(nameAndVersion[0])){
950 throw new PolicyDBException();
952 } catch(Exception e){
953 nameAndVersion[0] = originalPolicyName;
957 nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.')+1);
958 if(isNullOrEmpty(nameAndVersion[1])){
959 throw new PolicyDBException();
961 } catch(Exception e){
962 nameAndVersion[1] = "1";
965 return nameAndVersion;
968 private void handleIncomingPdpChange(String url, String pdpId, PolicyDBDaoTransaction transaction) throws PAPException{
972 pdpIdLong = Long.parseLong(pdpId);
973 }catch(NumberFormatException e){
974 throw new IllegalArgumentException("pdpId "+pdpId+" cannot be parsed into a long");
976 PdpEntity pdpRecord = null;
978 pdpRecord = transaction.getPdp(pdpIdLong);
980 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get pdp record with transaction.getPdp("+pdpIdLong+");");
981 throw new PAPException("Could not get local pdp "+pdpIdLong);
983 if(pdpRecord == null){
984 throw new PersistenceException("The pdpRecord returned is null");
988 localPdp = papEngine.getPDP(pdpRecord.getPdpId());
989 } catch (PAPException e) {
990 logger.warn("Caught PAPException trying to get local pdp with papEngine.getPDP("+pdpId+");",e);
992 if(localPdp != null && pdpRecord.isDeleted()){
994 papEngine.removePDP((OnapPDP) localPdp);
995 } catch (PAPException e) {
996 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to get remove pdp with papEngine.removePDP("+localPdp+");");
997 throw new PAPException("Could not remove pdp "+pdpId);
1000 else if(localPdp == null){
1003 OnapPDPGroup localGroup = null;
1005 localGroup = papEngine.getGroup(pdpRecord.getGroup().getGroupId());
1006 } catch (PAPException e1) {
1007 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Caught PAPException trying to get local group to add pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());");
1008 throw new PAPException("Could not get local group");
1011 papEngine.newPDP(pdpRecord.getPdpId(), localGroup, pdpRecord.getPdpName(), pdpRecord.getDescription(), pdpRecord.getJmxPort());
1012 } catch (NullPointerException | PAPException e) {
1013 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to create pdp with papEngine.newPDP("+pdpRecord.getPdpId()+", "+localGroup+", "+pdpRecord.getPdpName()+", "+pdpRecord.getDescription()+", "+pdpRecord.getJmxPort()+");");
1014 throw new PAPException("Could not create pdp "+pdpRecord);
1017 boolean needToUpdate = false;
1018 if(!stringEquals(localPdp.getId(),pdpRecord.getPdpId()) || !stringEquals(localPdp.getName(),pdpRecord.getPdpName())){
1019 //again, we don't want to change the id, the papEngine will do this
1020 localPdp.setName(pdpRecord.getPdpName());
1021 needToUpdate = true;
1023 if(!stringEquals(localPdp.getDescription(),pdpRecord.getDescription())){
1024 localPdp.setDescription(pdpRecord.getDescription());
1025 needToUpdate = true;
1027 String localPdpGroupId = null;
1029 localPdpGroupId = papEngine.getPDPGroup((OnapPDP) localPdp).getId();
1030 } catch(PAPException e){
1031 //could be null or something, just warn at this point
1032 logger.warn("Caught PAPException trying to get id of local group that pdp is in with localPdpGroupId = papEngine.getPDPGroup(localPdp).getId();",e);
1034 if(!stringEquals(localPdpGroupId,pdpRecord.getGroup().getGroupId())){
1035 OnapPDPGroup newPdpGroup = null;
1037 newPdpGroup = papEngine.getGroup(pdpRecord.getGroup().getGroupId());
1038 }catch(PAPException e){
1039 //ok, now we have an issue. Time to stop things
1040 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to get id of local group to move pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());");
1041 throw new PAPException("Could not get local group");
1044 papEngine.movePDP((OnapPDP) localPdp, newPdpGroup);
1045 }catch(PAPException e){
1046 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to move pdp with papEngine.movePDP(localPdp, newPdpGroup);");
1047 throw new PAPException("Could not move pdp "+localPdp);
1050 if(((PdpEntity) localPdp).getJmxPort() != pdpRecord.getJmxPort()){
1051 ((PdpEntity) localPdp).setJmxPort(pdpRecord.getJmxPort());
1052 needToUpdate = true;
1056 papEngine.updatePDP((OnapPDP) localPdp);
1057 } catch (PAPException e) {
1058 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to update pdp with papEngine.updatePdp("+localPdp+");");
1059 throw new PAPException("Could not update pdp "+localPdp);
1063 //compare to local situation
1064 //call command to update
1066 private void handleIncomingPolicyChange(String url, String policyId,String oldPathString){
1067 String policyName = null;
1068 EntityManager em = emf.createEntityManager();
1069 Query getPolicyEntityQuery = em.createNamedQuery("PolicyEntity.FindById");
1070 getPolicyEntityQuery.setParameter("id", Long.valueOf(policyId));
1072 @SuppressWarnings("unchecked")
1073 List<PolicyEntity> policies = getPolicyEntityQuery.getResultList();
1074 PolicyEntity policy = null;
1075 if (!policies.isEmpty()){
1076 policy = policies.get(0);
1078 String action = "unknown action";
1081 policyName = policy.getPolicyName();
1082 logger.info("Deleting old Policy Config File for " + policy.getPolicyName());
1084 Path subFile = null;
1086 if (policy.getConfigurationData()!= null){
1087 subFile = getPolicySubFile(policy.getConfigurationData().getConfigurationName(), "Config");
1088 }else if(policy.getActionBodyEntity()!= null){
1089 subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), "Action");
1092 if(subFile != null){
1093 Files.deleteIfExists(subFile);
1095 if (policy.getConfigurationData()!= null){
1096 writePolicySubFile(policy, "Config");
1097 }else if(policy.getActionBodyEntity()!= null){
1098 writePolicySubFile(policy, "Action");
1101 } catch (IOException e1) {
1102 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Error occurred while performing [" + action + "] of Policy File: " + policyName);
1106 private String getPdpPolicyName(String name, String scope){
1107 String finalName = "";
1110 finalName += removeFileExtension(name);
1111 finalName += ".xml";
1114 private String removeFileExtension(String fileName){
1115 return fileName.substring(0, fileName.lastIndexOf('.'));
1118 private Path getPolicySubFile(String filename, String subFileType){
1119 logger.info("getPolicySubFile(" + filename + ", " + subFileType + ")");
1120 Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), subFileType);
1123 filename = FilenameUtils.removeExtension(filename);
1125 for(File tmpFile : filePath.toFile().listFiles()){
1126 if (FilenameUtils.removeExtension(tmpFile.getName()).equals(filename)){
1131 Path finalPath = null;
1133 finalPath = Paths.get(file.getAbsolutePath());
1136 logger.info("end of getPolicySubFile: " + finalPath);
1140 private boolean writePolicySubFile(PolicyEntity policy, String policyType){
1141 logger.info("writePolicySubFile with policyName[" + policy.getPolicyName() + "] and policyType[" + policyType + "]");
1143 String subTypeName = null;
1144 String subTypeBody = null;
1145 if (policyType.equalsIgnoreCase("config")){
1147 subTypeName = FilenameUtils.removeExtension(policy.getConfigurationData().getConfigurationName());
1148 subTypeBody = policy.getConfigurationData().getConfigBody();
1150 String configType = policy.getConfigurationData().getConfigType();
1153 if (configType != null) {
1154 if (configType.equals(JSON_CONFIG)) {
1155 subTypeName = subTypeName + ".json";
1157 if (configType.equals(XML_CONFIG)) {
1158 subTypeName = subTypeName + ".xml";
1160 if (configType.equals(PROPERTIES_CONFIG)) {
1161 subTypeName = subTypeName + ".properties";
1163 if (configType.equals(OTHER_CONFIG)) {
1164 subTypeName = subTypeName + ".txt";
1168 }else if (policyType.equalsIgnoreCase("action")){
1170 subTypeName = policy.getActionBodyEntity().getActionBodyName();
1171 subTypeBody = policy.getActionBodyEntity().getActionBody();
1175 Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), type);
1177 if(subTypeBody == null){
1180 boolean success = false;
1182 Files.deleteIfExists(Paths.get(filePath.toString(), subTypeName));
1183 File file = Paths.get(filePath.toString(),subTypeName).toFile();
1184 file.createNewFile();
1185 FileWriter fileWriter = new FileWriter(file, false); // false to overwrite
1186 fileWriter.write(subTypeBody);
1190 } catch (Exception e) {
1191 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Exception occured while creating Configuration File for Policy : " + policy.getPolicyName());
1198 public void auditLocalDatabase(PAPPolicyEngine papEngine2){
1199 logger.debug("PolicyDBDao.auditLocalDatabase() is called");
1201 deleteAllGroupTables();
1202 auditGroups(papEngine2);
1203 } catch(Exception e){
1204 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "auditLocalDatabase() error");
1205 logger.error("Exception Occured"+e);
1210 public StdPDPGroup auditLocalFileSystem(StdPDPGroup group){
1212 logger.info("Starting Local File System group audit");
1213 EntityManager em = emf.createEntityManager();
1214 em.getTransaction().begin();
1216 StdPDPGroup updatedGroup = null;
1218 Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
1219 groupQuery.setParameter("groupId", group.getId());
1220 groupQuery.setParameter("deleted", false);
1221 List<?> groupQueryList = groupQuery.getResultList();
1222 if(groupQueryList!=null && !groupQueryList.isEmpty()){
1223 GroupEntity dbgroup = (GroupEntity)groupQueryList.get(0);
1224 updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup);
1225 logger.info("Group was updated during file system audit: " + updatedGroup.toString());
1227 } catch (PAPException | PolicyDBException e) {
1229 } catch (Exception e) {
1231 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if group exists groupQuery.getResultList()");
1232 throw new PersistenceException("Query failed trying to check if group "+group.getId()+" exists");
1235 em.getTransaction().commit();
1238 return updatedGroup;
1242 public void deleteAllGroupTables(){
1243 logger.debug("PolicyDBDao.deleteAllGroupTables() called");
1244 EntityManager em = emf.createEntityManager();
1245 em.getTransaction().begin();
1247 Query deletePdpEntityEntityTableUpdate = em.createNamedQuery("PdpEntity.deleteAll");
1248 deletePdpEntityEntityTableUpdate.executeUpdate();
1250 Query deleteGroupEntityTableUpdate = em.createNamedQuery("GroupEntity.deleteAll");
1251 deleteGroupEntityTableUpdate.executeUpdate();
1253 em.getTransaction().commit();
1257 @SuppressWarnings("unchecked")
1258 public void auditGroups(PAPPolicyEngine papEngine2){
1259 logger.debug("PolicyDBDao.auditGroups() called");
1261 EntityManager em = emf.createEntityManager();
1262 em.getTransaction().begin();
1263 final String AUDIT_STR = "Audit";
1266 Set<OnapPDPGroup> groups = papEngine2.getOnapPDPGroups();
1268 for (OnapPDPGroup grp : groups){
1270 GroupEntity groupEntity = new GroupEntity();
1271 em.persist(groupEntity);
1272 groupEntity.setGroupName(grp.getName());
1273 groupEntity.setDescription(grp.getDescription());
1274 groupEntity.setDefaultGroup(grp.isDefaultGroup());
1275 groupEntity.setCreatedBy(AUDIT_STR);
1276 groupEntity.setGroupId(createNewPDPGroupId(grp.getId()));
1277 groupEntity.setModifiedBy(AUDIT_STR);
1278 Set<OnapPDP> pdps = grp.getOnapPdps();
1280 for(OnapPDP pdp : pdps){
1281 PdpEntity pdpEntity = new PdpEntity();
1282 em.persist(pdpEntity);
1283 pdpEntity.setGroup(groupEntity);
1284 pdpEntity.setJmxPort(pdp.getJmxPort());
1285 pdpEntity.setPdpId(pdp.getId());
1286 pdpEntity.setPdpName(pdp.getName());
1287 pdpEntity.setModifiedBy(AUDIT_STR);
1288 pdpEntity.setCreatedBy(AUDIT_STR);
1292 Set<PDPPolicy> policies = grp.getPolicies();
1294 for(PDPPolicy policy : policies){
1296 String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId());
1297 List<PolicyEntity> policyEntityList;
1298 Query getPolicyEntitiesQuery = em.createNamedQuery("PolicyEntity.findByNameAndScope");
1299 getPolicyEntitiesQuery.setParameter("name", stringArray[0]);
1300 getPolicyEntitiesQuery.setParameter("scope", stringArray[1]);
1302 policyEntityList = getPolicyEntitiesQuery.getResultList();
1303 PolicyEntity policyEntity = null;
1304 if(!policyEntityList.isEmpty()){
1305 policyEntity = policyEntityList.get(0);
1307 if(policyEntity != null){
1308 groupEntity.addPolicyToGroup(policyEntity);
1310 }catch(Exception e2){
1311 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Exception auditGroups inner catch");
1314 }catch(Exception e1){
1315 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Exception auditGroups middle catch");
1318 }catch(Exception e){
1319 em.getTransaction().rollback();
1320 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Exception auditGroups outer catch");
1325 em.getTransaction().commit();
1330 private String getConfigFile(String filename, PolicyRestAdapter policy){
1332 return getConfigFile(filename, (String)null);
1334 return getConfigFile(filename, policy.getConfigType());
1336 //copied from ConfigPolicy.java and modified
1337 // Here we are adding the extension for the configurations file based on the
1338 // config type selection for saving.
1339 private String getConfigFile(String filename, String configType) {
1340 logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile("+filename+", "+configType+") called");
1341 filename = FilenameUtils.removeExtension(filename);
1342 String id = configType;
1345 if (id.equals(ConfigPolicy.JSON_CONFIG) || id.contains("Firewall")) {
1346 filename = filename + ".json";
1348 if (id.equals(ConfigPolicy.XML_CONFIG)) {
1349 filename = filename + ".xml";
1351 if (id.equals(ConfigPolicy.PROPERTIES_CONFIG)) {
1352 filename = filename + ".properties";
1354 if (id.equals(ConfigPolicy.OTHER_CONFIG)) {
1355 filename = filename + ".txt";
1361 private String[] getNameScopeAndVersionFromPdpPolicy(String fileName){
1362 String[] splitByDots = fileName.split("\\.");
1363 if(splitByDots.length < 3){
1364 //should we throw something
1367 String policyName = splitByDots[splitByDots.length-3];
1368 String version = splitByDots[splitByDots.length-2];
1369 //policy names now include version
1371 for(int i=0;i<splitByDots.length-3;i++){
1372 scope += ".".concat(splitByDots[i]);
1374 //remove the first dot
1375 if(scope.length() > 0){
1376 scope = scope.substring(1);
1378 String[] returnArray = new String[3];
1379 returnArray[0] = policyName + "." + version + ".xml";
1380 returnArray[2] = version;
1381 returnArray[1] = scope;
1385 //copied from StdEngine.java
1386 public static String createNewPDPGroupId(String name) {
1388 // replace "bad" characters with sequences that will be ok for file names and properties keys.
1389 id = id.replace(" ", "_sp_");
1390 id = id.replace("\t", "_tab_");
1391 id = id.replace("\\", "_bksl_");
1392 id = id.replace("/", "_sl_");
1393 id = id.replace(":", "_col_");
1394 id = id.replace("*", "_ast_");
1395 id = id.replace("?", "_q_");
1396 id = id.replace("\"", "_quo_");
1397 id = id.replace("<", "_lt_");
1398 id = id.replace(">", "_gt_");
1399 id = id.replace("|", "_bar_");
1400 id = id.replace("=", "_eq_");
1401 id = id.replace(",", "_com_");
1402 id = id.replace(";", "_scom_");
1408 * Checks if any of the given strings are empty or null
1409 * @param strings One or more Strings (or nulls) to check if they are null or empty
1410 * @return true if one or more of the given strings are empty or null
1412 private static boolean isNullOrEmpty(String... strings){
1413 for(String s : strings){
1414 if(!(s instanceof String)){
1425 private class PolicyDBDaoTransactionInstance implements PolicyDBDaoTransaction {
1426 private EntityManager em;
1427 private final Object emLock = new Object();
1432 private boolean operationRun = false;
1433 private final Thread transactionTimer;
1435 private PolicyDBDaoTransactionInstance(){
1436 //call the constructor with arguments
1437 this(Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)),
1438 Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)));
1440 //timeout is how long the transaction can sit before rolling back
1441 //wait time is how long to wait for the transaction to start before throwing an exception
1442 private PolicyDBDaoTransactionInstance(int transactionTimeout, int transactionWaitTime){
1443 if(logger.isDebugEnabled()){
1444 logger.debug("\n\nPolicyDBDaoTransactionInstance() as PolicyDBDaoTransactionInstance() called:"
1445 + "\n transactionTimeout = " + transactionTimeout
1446 + "\n transactionWaitTime = " + transactionWaitTime + "\n\n");
1448 this.em = emf.createEntityManager();
1453 synchronized(emLock){
1455 startTransactionSynced(this.em,transactionWaitTime);
1456 } catch(Exception e){
1458 throw new PersistenceException("Could not lock transaction within "+transactionWaitTime+" milliseconds");
1461 class TransactionTimer implements Runnable {
1463 private int sleepTime;
1464 public TransactionTimer(int timeout){
1465 this.sleepTime = timeout;
1469 if(logger.isDebugEnabled()){
1470 Date date= new java.util.Date();
1471 logger.debug("\n\nTransactionTimer.run() - SLEEPING: "
1472 + "\n sleepTime (ms) = " + sleepTime
1473 + "\n TimeStamp = " + date.getTime()
1477 Thread.sleep(sleepTime);
1478 } catch (InterruptedException e) {
1479 //probably, the transaction was completed, the last thing we want to do is roll back
1480 if(logger.isDebugEnabled()){
1481 Date date= new java.util.Date();
1482 logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: "
1483 + "\n TimeStamp = " + date.getTime()
1486 Thread.currentThread().interrupt();
1489 if(logger.isDebugEnabled()){
1490 Date date= new java.util.Date();
1491 logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: "
1492 + "\n TimeStamp = " + date.getTime()
1495 rollbackTransaction();
1500 transactionTimer = new Thread(new TransactionTimer(transactionTimeout),"transactionTimerThread");
1501 transactionTimer.start();
1506 private void checkBeforeOperationRun(){
1507 checkBeforeOperationRun(false);
1509 private void checkBeforeOperationRun(boolean justCheckOpen){
1510 if(!isTransactionOpen()){
1511 PolicyLogger.error("There is no transaction currently open");
1512 throw new IllegalStateException("There is no transaction currently open");
1514 if(operationRun && !justCheckOpen){
1515 PolicyLogger.error("An operation has already been performed and the current transaction should be committed");
1516 throw new IllegalStateException("An operation has already been performed and the current transaction should be committed");
1518 operationRun = true;
1521 public void commitTransaction() {
1522 synchronized(emLock){
1523 logger.debug("commitTransaction() as commitTransaction() called");
1524 if(!isTransactionOpen()){
1525 logger.warn("There is no open transaction to commit");
1528 } catch(Exception e){
1529 logger.error("Exception Occured"+e);
1534 em.getTransaction().commit();
1535 } catch(RollbackException e){
1536 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught RollbackException on em.getTransaction().commit()");
1537 throw new PersistenceException("The commit failed. Message:\n"+e.getMessage());
1542 if(newGroupId != null){
1544 notifyOthers(policyId,POLICY_NOTIFICATION,newGroupId);
1545 } catch(Exception e){
1546 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+policyId+","+POLICY_NOTIFICATION+","+newGroupId+")");
1550 notifyOthers(policyId,POLICY_NOTIFICATION);
1551 } catch(Exception e){
1552 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+policyId+","+POLICY_NOTIFICATION+")");
1557 //we don't want commit to fail just because this does
1558 if(newGroupId != null){
1560 notifyOthers(groupId,GROUP_NOTIFICATION,newGroupId);
1561 } catch(Exception e){
1562 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+groupId+","+GROUP_NOTIFICATION+","+newGroupId+")");
1566 notifyOthers(groupId,GROUP_NOTIFICATION);
1567 } catch(Exception e){
1568 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+groupId+","+GROUP_NOTIFICATION+")");
1573 //we don't want commit to fail just because this does
1575 notifyOthers(pdpId,PDP_NOTIFICATION);
1576 } catch(Exception e){
1577 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+pdpId+","+PDP_NOTIFICATION+")");
1581 if(transactionTimer instanceof Thread){
1582 transactionTimer.interrupt();
1587 public void rollbackTransaction() {
1588 logger.debug("rollbackTransaction() as rollbackTransaction() called");
1589 synchronized(emLock){
1590 if(isTransactionOpen()){
1593 em.getTransaction().rollback();
1594 } catch(Exception e){
1595 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not rollback transaction");
1599 }catch(Exception e){
1600 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not close EntityManager");
1606 }catch(Exception e){
1607 logger.warn("Could not close already closed transaction", e);
1612 if(transactionTimer instanceof Thread){
1613 transactionTimer.interrupt();
1619 private void createPolicy(PolicyRestAdapter policy, String username, String policyScope, String policyName, String policyDataString) {
1620 logger.debug("createPolicy(PolicyRestAdapter policy, String username, String policyScope, String policyName, String policyDataString) as createPolicy("+policy+", "+username+", "+policyScope+", "+policyName+", "+policyDataString+") called");
1621 synchronized(emLock){
1622 checkBeforeOperationRun();
1623 String configName = policyName;
1624 if(policyName.contains("Config_")){
1625 policyName = policyName.replace(".Config_", ":Config_");
1626 }else if(policyName.contains("Action_")){
1627 policyName = policyName.replace(".Action_", ":Action_");
1628 }else if(policyName.contains("Decision_")){
1629 policyName = policyName.replace(".Decision_", ":Decision_");
1631 policyName = policyName.split(":")[1];
1632 Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
1633 createPolicyQuery.setParameter("scope", policyScope);
1634 createPolicyQuery.setParameter("policyName", policyName);
1635 List<?> createPolicyQueryList = createPolicyQuery.getResultList();
1636 PolicyEntity newPolicyEntity;
1638 if(createPolicyQueryList.size() < 1){
1639 newPolicyEntity = new PolicyEntity();
1641 } else if(createPolicyQueryList.size() > 1){
1642 PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database");
1643 throw new PersistenceException("Somehow, more than one policy with the same scope, name, and deleted status were found in the database");
1645 newPolicyEntity = (PolicyEntity)createPolicyQueryList.get(0);
1649 ActionBodyEntity newActionBodyEntity = null;
1650 if(policy.getPolicyType().equals("Action")){
1651 boolean abupdate = false;
1652 if(newPolicyEntity.getActionBodyEntity() == null){
1653 newActionBodyEntity = new ActionBodyEntity();
1655 newActionBodyEntity = em.find(ActionBodyEntity.class, newPolicyEntity.getActionBodyEntity().getActionBodyId());
1659 if(newActionBodyEntity != null){
1661 em.persist(newActionBodyEntity);
1663 //build the file path
1664 //trim the .xml off the end
1665 String policyNameClean = FilenameUtils.removeExtension(configName);
1666 String actionBodyName = policyNameClean + ".json";
1667 Path actionBodyPath = Paths.get(Webapps.getActionHome(), actionBodyName);
1668 if(logger.isDebugEnabled()){
1669 logger.debug("\nPolicyDBDao.createPolicy"
1670 + "\n actionBodyPath = " + actionBodyPath);
1672 //get the action body
1673 String actionBodyString = null;
1674 String actionBodyPathStr = null;
1675 InputStream fileContentStream = null;
1677 if (Files.exists(actionBodyPath)) {
1679 actionBodyPathStr = (actionBodyPath != null ? actionBodyPath.toString() : null);
1680 fileContentStream = new FileInputStream(actionBodyPathStr);
1681 actionBodyString = IOUtils.toString(fileContentStream);
1682 if(logger.isDebugEnabled()){
1683 logger.debug("\nPolicyDBDao.createPolicy"
1684 + "\n actionBodyPathStr = " + actionBodyPathStr
1685 + "\n actionBodyString = " + actionBodyString);
1687 } catch (FileNotFoundException e) {
1688 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught FileNotFoundException on new actionBodyPathStr FileInputStream("+actionBodyPathStr+")");
1689 throw new IllegalArgumentException("The actionBodyPathStr file path " + actionBodyPathStr + " does not exist"
1690 + "\nEXCEPTION: " + e);
1691 } catch(IOException e2){
1692 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Caught IOException on actionBodyPath newIOUtils.toString("+fileContentStream+")");
1693 throw new IllegalArgumentException("The actionBodyPath file path cannot be read" + fileContentStream
1694 + "\nEXCEPTION: " + e2);
1696 IOUtils.closeQuietly(fileContentStream);
1699 if(actionBodyString == null){
1700 throw new IllegalArgumentException("The file path (" + actionBodyPathStr + ") cannot be read");
1703 actionBodyString = "{}";
1706 newActionBodyEntity.setActionBody(actionBodyString);
1707 newActionBodyEntity.setActionBodyName(actionBodyName);
1708 newActionBodyEntity.setModifiedBy("PolicyDBDao.createPolicy()");
1709 newActionBodyEntity.setDeleted(false);
1711 newActionBodyEntity.setCreatedBy("PolicyDBDao.createPolicy()");
1713 if(logger.isDebugEnabled()){
1714 logger.debug("\nPolicyDBDao.createPolicy"
1715 + "\n newActionBodyEntity.getActionBody() = " + newActionBodyEntity.getActionBody()
1716 + "\n newActionBodyEntity.getActionBodyName() = " + newActionBodyEntity.getActionBodyName()
1717 + "\n newActionBodyEntity.getModifiedBy() = " + newActionBodyEntity.getModifiedBy()
1718 + "\n newActionBodyEntity.getCreatedBy() = " + newActionBodyEntity.getCreatedBy()
1719 + "\n newActionBodyEntity.isDeleted() = " + newActionBodyEntity.isDeleted()
1720 + "\n FLUSHING to DB");
1722 //push the actionBodyEntity to the DB
1725 //newActionBodyEntity == null
1726 //We have a actionBody in the policy but we found no actionBody in the DB
1727 String msg = "\n\nPolicyDBDao.createPolicy - Incoming Action policy had an "
1728 + "actionBody, but it could not be found in the DB for update."
1729 + "\n policyScope = " + policyScope
1730 + "\n policyName = " + policyName + "\n\n";
1731 PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, but it could not be found in the DB for update: policyName = " + policyName);
1732 throw new IllegalArgumentException(msg);
1736 ConfigurationDataEntity newConfigurationDataEntity;
1737 if(policy.getPolicyType().equals("Config")){
1738 boolean configUpdate;
1739 if(newPolicyEntity.getConfigurationData() == null){
1740 newConfigurationDataEntity = new ConfigurationDataEntity();
1741 configUpdate = false;
1743 newConfigurationDataEntity = em.find(ConfigurationDataEntity.class, newPolicyEntity.getConfigurationData().getConfigurationDataId());
1744 configUpdate = true;
1747 if(newConfigurationDataEntity != null){
1749 em.persist(newConfigurationDataEntity);
1751 if(!stringEquals(newConfigurationDataEntity.getConfigurationName(),getConfigFile(configName,policy))){
1752 newConfigurationDataEntity.setConfigurationName(getConfigFile(configName,policy));
1754 if(newConfigurationDataEntity.getConfigType() == null || !newConfigurationDataEntity.getConfigType().equals(policy.getConfigType())){
1755 newConfigurationDataEntity.setConfigType(policy.getConfigType());
1758 newConfigurationDataEntity.setCreatedBy(username);
1760 if(newConfigurationDataEntity.getModifiedBy() == null || !newConfigurationDataEntity.getModifiedBy().equals(username)){
1761 newConfigurationDataEntity.setModifiedBy(username);
1763 if(newConfigurationDataEntity.getDescription() == null || !newConfigurationDataEntity.getDescription().equals("")){
1764 newConfigurationDataEntity.setDescription("");
1766 if(newConfigurationDataEntity.getConfigBody() == null || newConfigurationDataEntity.getConfigBody().isEmpty() ||
1767 (!newConfigurationDataEntity.getConfigBody().equals(policy.getConfigBodyData()))){
1768 //hopefully one of these won't be null
1769 if(policy.getConfigBodyData() == null || policy.getConfigBodyData().isEmpty()){
1770 newConfigurationDataEntity.setConfigBody(policy.getJsonBody());
1772 newConfigurationDataEntity.setConfigBody(policy.getConfigBodyData());
1775 if(newConfigurationDataEntity.isDeleted() == true){
1776 newConfigurationDataEntity.setDeleted(false);
1781 //We have a configurationData body in the policy but we found no configurationData body in the DB
1782 String msg = "\n\nPolicyDBDao.createPolicy - Incoming Config policy had a "
1783 + "configurationData body, but it could not be found in the DB for update."
1784 + "\n policyScope = " + policyScope
1785 + "\n policyName = " + policyName + "\n\n";
1786 PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Config policy had a configurationData body, but it could not be found in the DB for update: policyName = " + policyName);
1787 throw new IllegalArgumentException(msg);
1791 newConfigurationDataEntity = null;
1794 em.persist(newPolicyEntity);
1797 policyId = newPolicyEntity.getPolicyId();
1799 if(!stringEquals(newPolicyEntity.getPolicyName(),policyName)){
1800 newPolicyEntity.setPolicyName(policyName);
1802 if(!stringEquals(newPolicyEntity.getCreatedBy(),username)){
1803 newPolicyEntity.setCreatedBy(username);
1805 if(!stringEquals(newPolicyEntity.getDescription(),policy.getPolicyDescription())){
1806 newPolicyEntity.setDescription(policy.getPolicyDescription());
1808 if(!stringEquals(newPolicyEntity.getModifiedBy(),username)){
1809 newPolicyEntity.setModifiedBy(username);
1811 if(!stringEquals(newPolicyEntity.getPolicyData(),policyDataString)){
1812 newPolicyEntity.setPolicyData(policyDataString);
1814 if(!stringEquals(newPolicyEntity.getScope(),policyScope)){
1815 newPolicyEntity.setScope(policyScope);
1817 if(newPolicyEntity.isDeleted() == true){
1818 newPolicyEntity.setDeleted(false);
1820 newPolicyEntity.setConfigurationData(newConfigurationDataEntity);
1821 newPolicyEntity.setActionBodyEntity(newActionBodyEntity);
1825 this.policyId = newPolicyEntity.getPolicyId();
1831 @SuppressWarnings("unused")
1832 public PolicyEntity getPolicy(int policyID){
1833 return getPolicy(policyID,null,null);
1835 public PolicyEntity getPolicy(String policyName,String scope){
1836 return getPolicy(-1,policyName,scope);
1838 private PolicyEntity getPolicy(int policyID, String policyName,String scope){
1839 logger.debug("getPolicy(int policyId, String policyName) as getPolicy("+policyID+","+policyName+") called");
1840 if(policyID < 0 && isNullOrEmpty(policyName,scope)){
1841 throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank");
1844 synchronized(emLock){
1845 checkBeforeOperationRun(true);
1846 //check if group exists
1849 if(!isNullOrEmpty(policyName,scope)){
1850 policyId = policyName;
1851 policyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope");
1852 policyQuery.setParameter("name", policyId);
1853 policyQuery.setParameter("scope", scope);
1855 policyId = String.valueOf(policyID);
1856 policyQuery = em.createNamedQuery("PolicyEntity.FindById");
1857 policyQuery.setParameter("id", policyId);
1859 List<?> policyQueryList;
1861 policyQueryList = policyQuery.getResultList();
1862 }catch(Exception e){
1863 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get policy with policyQuery.getResultList()");
1864 throw new PersistenceException("Query failed trying to get policy "+policyId);
1866 if(policyQueryList.size() < 1){
1867 PolicyLogger.error("Policy does not exist with id "+policyId);
1868 throw new PersistenceException("Group policy is being added to does not exist with id "+policyId);
1869 } else if(policyQueryList.size() > 1){
1870 PolicyLogger.error("Somehow, more than one policy with the id "+policyId+" were found in the database");
1871 throw new PersistenceException("Somehow, more than one policy with the id "+policyId+" were found in the database");
1873 return (PolicyEntity)policyQueryList.get(0);
1878 public void renamePolicy(String oldPath, String newPath,String username){
1879 /* String[] oldPolicy = getScopeAndNameAndType(oldPath);
1880 String[] newPolicy = getScopeAndNameAndType(newPath);
1881 if(oldPolicy == null || newPolicy == null){
1882 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW+"Could not parse one or more of the path names: "
1883 +oldPath+", "+newPath);
1884 throw new IllegalArgumentException("Could not parse one or more of the path names");
1886 synchronized (emLock) {
1887 checkBeforeOperationRun();
1889 PolicyEntity existingPolicy;
1890 boolean existingPolicyDeleted = false;
1891 List<?> groups = null;
1893 existingPolicy = getPolicy(newPolicy[1],newPolicy[0]);
1894 } catch(Exception e){
1895 existingPolicy = null;
1897 if(existingPolicy != null && !existingPolicy.isDeleted()){
1898 logger.error("The policy named "+existingPolicy.getPolicyName()+" already exists, cannot rename policy: "+newPolicy);
1899 throw new IllegalArgumentException("The policy named "+existingPolicy.getPolicyName()+" already exists, cannot rename policy: "+newPolicy);
1900 } else if(existingPolicy != null && existingPolicy.isDeleted()){
1902 Query getGroups = em.createQuery("SELECT g FROM GroupEntity g JOIN g.policies p WHERE p.policyId=:pid");
1904 getGroups.setParameter("pid", existingPolicy.getPolicyId());
1905 groups = getGroups.getResultList();
1906 }catch(Exception e){
1907 groups = new LinkedList<>();
1909 for(Object o : groups){
1910 GroupEntity group = (GroupEntity)o;
1911 group.removePolicyFromGroup(existingPolicy);
1915 }catch(Exception e){
1916 logger.error("Error while removing the policy from groups: "+existingPolicy.getPolicyName());
1919 em.remove(existingPolicy);
1921 }catch(Exception e){
1922 logger.error("Could not remove the existing deleted policy: "+existingPolicy.getPolicyName());
1924 existingPolicyDeleted = true;
1925 //create the new policy
1926 //for each of the groups, add the new policy
1929 PolicyEntity policyToRename;
1931 policyToRename = getPolicy(oldPolicy[1],oldPolicy[0]);
1932 } catch(Exception e){
1933 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "PolicyDBDao", "Could not get policy record to rename: "
1935 throw new PersistenceException("Could not get policy record to rename");
1937 String policyDataString = null;
1938 InputStream fileContentStream = null;
1939 String policyFilePath = Paths.get(oldPath).toAbsolutePath().toString();
1940 //I want to try the old path first, then if it doesn't work, try the new path
1941 for(int i=0;i<2;i++){
1943 fileContentStream = new FileInputStream(policyFilePath);
1944 policyDataString = IOUtils.toString(fileContentStream);
1945 } catch (FileNotFoundException e) {
1946 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught FileNotFoundException on new FileInputStream("+policyFilePath+")");
1947 //if we can't find the oldPath, we'll try the new path
1949 policyFilePath = Paths.get(newPath).toAbsolutePath().toString();
1952 throw new IllegalArgumentException("The file path does not exist");
1953 } catch(IOException e2){
1954 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Caught IOException on newIOUtils.toString("+fileContentStream+")");
1955 throw new IllegalArgumentException("The file path cannot be read");
1957 IOUtils.closeQuietly(fileContentStream);
1959 if(policyDataString == null){
1960 throw new IllegalArgumentException("The file path cannot be read");
1965 policyToRename.setPolicyName(newPolicy[1]);
1966 policyToRename.setPolicyData(policyDataString);
1967 policyToRename.setScope(newPolicy[0]);
1968 policyToRename.setModifiedBy(username);
1969 if(policyToRename.getConfigurationData() != null){
1970 String configType = policyToRename.getConfigurationData().getConfigType();
1971 policyToRename.getConfigurationData().setConfigurationName(getConfigFile(newPolicy[1], configType));
1972 policyToRename.getConfigurationData().setModifiedBy(username);
1974 if(policyToRename.getActionBodyEntity() != null){
1975 String newActionName = newPolicy[0]+"."+removeFileExtension(newPolicy[1])+".json";
1976 policyToRename.getActionBodyEntity().setActionBodyName(newActionName);
1977 policyToRename.getActionBodyEntity().setModifiedBy(username);
1979 if(existingPolicyDeleted){
1980 for(Object o : groups){
1982 GroupEntity group = (GroupEntity)o;
1983 group.addPolicyToGroup(policyToRename);
1987 this.policyId = policyToRename.getPolicyId();
1988 this.newGroupId = oldPath;
1993 public GroupEntity getGroup(long groupKey){
1994 logger.debug("getGroup(int groupKey) as getGroup("+groupKey+") called");
1996 throw new IllegalArgumentException("groupKey must be at least 0");
1998 synchronized(emLock){
1999 checkBeforeOperationRun(true);
2000 //check if group exists
2001 Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey");
2002 groupQuery.setParameter("groupKey", groupKey);
2003 List<?> groupQueryList;
2005 groupQueryList = groupQuery.getResultList();
2006 }catch(Exception e){
2007 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get group with groupQuery.getResultList()");
2008 throw new PersistenceException("Query failed trying to get group "+groupKey);
2010 if(groupQueryList.size() < 1){
2011 PolicyLogger.error("Group does not exist with groupKey "+groupKey);
2012 throw new PersistenceException("Group does not exist with groupKey "+groupKey);
2013 } else if(groupQueryList.size() > 1){
2014 PolicyLogger.error("Somehow, more than one group with the groupKey "+groupKey+" were found in the database");
2015 throw new PersistenceException("Somehow, more than one group with the groupKey "+groupKey+" were found in the database");
2017 return (GroupEntity)groupQueryList.get(0);
2022 public GroupEntity getGroup(String groupId){
2023 logger.debug("getGroup(String groupId) as getGroup("+groupId+") called");
2024 if(isNullOrEmpty(groupId)){
2025 throw new IllegalArgumentException("groupId must not be null or empty");
2027 synchronized(emLock){
2028 checkBeforeOperationRun(true);
2029 //check if group exists
2030 Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId");
2031 groupQuery.setParameter("groupId", groupId);
2032 List<?> groupQueryList;
2034 groupQueryList = groupQuery.getResultList();
2035 }catch(Exception e){
2036 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get group with groupQuery.getResultList()");
2037 throw new PersistenceException("Query failed trying to get group "+groupId);
2039 if(groupQueryList.size() < 1){
2040 PolicyLogger.error("Group does not exist with id "+groupId);
2041 throw new PersistenceException("Group does not exist with id "+groupId);
2042 } else if(groupQueryList.size() > 1){
2043 PolicyLogger.error("Somehow, more than one group with the id "+groupId+" were found in the database");
2044 throw new PersistenceException("Somehow, more than one group with the id "+groupId+" were found in the database");
2046 return (GroupEntity)groupQueryList.get(0);
2050 public List<?> getPdpsInGroup(long groupKey){
2051 logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup("+groupKey+") called");
2053 throw new IllegalArgumentException("groupId must not be < 0");
2055 synchronized(emLock){
2056 checkBeforeOperationRun(true);
2057 Query pdpsQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group");
2058 pdpsQuery.setParameter("group", getGroup(groupKey));
2059 return pdpsQuery.getResultList();
2063 public PdpEntity getPdp(long pdpKey){
2064 logger.debug("getPdp(int pdpKey) as getPdp("+pdpKey+") called");
2066 throw new IllegalArgumentException("pdpKey must be at least 0");
2068 synchronized(emLock){
2069 checkBeforeOperationRun(true);
2070 //check if group exists
2071 Query pdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey");
2072 pdpQuery.setParameter("pdpKey", pdpKey);
2073 List<?> pdpQueryList;
2075 pdpQueryList = pdpQuery.getResultList();
2076 }catch(Exception e){
2077 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get pdp with pdpQuery.getResultList()");
2078 throw new PersistenceException("Query failed trying to get pdp "+pdpKey);
2080 if(pdpQueryList.size() < 1){
2081 PolicyLogger.error("Pdp does not exist with pdpKey "+pdpKey);
2082 throw new PersistenceException("Pdp does not exist with pdpKey "+pdpKey);
2083 } else if(pdpQueryList.size() > 1){
2084 PolicyLogger.error("Somehow, more than one pdp with the pdpKey "+pdpKey+" were found in the database");
2085 throw new PersistenceException("Somehow, more than one pdp with the pdpKey "+pdpKey+" were found in the database");
2087 return (PdpEntity)pdpQueryList.get(0);
2091 public void deletePolicy(String policyToDeletes){
2092 /*synchronized(emLock){
2093 checkBeforeOperationRun();
2094 logger.debug("deletePolicy(String policyToDeletes) as deletePolicy("+policyToDeletes+") called");
2095 String[] scopeNameAndType = getScopeAndNameAndType(policyToDeletes);
2096 if(scopeNameAndType == null){
2097 throw new IllegalArgumentException("Could not parse file path");
2099 String realScope = scopeNameAndType[0];
2100 String realName = scopeNameAndType[1];
2101 Query deletePolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName AND p.deleted=:deleted");
2102 deletePolicyQuery.setParameter("scope",realScope);
2103 deletePolicyQuery.setParameter("policyName", realName);
2104 deletePolicyQuery.setParameter("deleted", false);
2105 List<?> deletePolicyQueryList = deletePolicyQuery.getResultList();
2106 if(deletePolicyQueryList.size() < 1){
2107 logger.warn("The policy being deleted could not be found.");
2109 } else if(deletePolicyQueryList.size() > 1){
2110 PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database");
2111 throw new PersistenceException("Somehow, more than one policy with the same scope, name, and deleted status were found in the database");
2113 PolicyEntity policyToDelete = (PolicyEntity)deletePolicyQueryList.get(0);
2114 policyToDelete.setDeleted(true);
2115 if(policyToDelete.getConfigurationData() != null){
2116 ConfigurationDataEntity cde = em.find(ConfigurationDataEntity.class,policyToDelete.getConfigurationData().getConfigurationDataId());
2118 cde.setDeleted(true);
2121 if(policyToDelete.getActionBodyEntity() != null){
2122 ActionBodyEntity abe = em.find(ActionBodyEntity.class,policyToDelete.getActionBodyEntity().getActionBodyId());
2124 abe.setDeleted(true);
2129 this.policyId = policyToDelete.getPolicyId();
2138 public boolean isTransactionOpen() {
2139 logger.debug("isTransactionOpen() as isTransactionOpen() called");
2140 synchronized(emLock){
2141 return em.isOpen() && em.getTransaction().isActive();
2147 public void clonePolicy(String oldPolicyPath, String newPolicyPath, String username){
2148 /*String[] oldPolicyData = getScopeAndNameAndType(oldPolicyPath);
2149 String[] newPolicyData = getScopeAndNameAndType(newPolicyPath);
2150 if(oldPolicyData == null || newPolicyData == null){
2151 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW+"Could not parse one or more of the path names: "
2152 +oldPolicyPath+", "+newPolicyPath);
2153 throw new IllegalArgumentException("Could not parse the oldPolicyPath or newPolicyPath");
2155 PolicyEntity oldPolicy;
2157 oldPolicy = getPolicy(oldPolicyData[1],oldPolicyData[0]);
2158 }catch(Exception e){
2159 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "PolicyDBDao", "Could not get policy record to clone: "
2161 throw new PersistenceException("Could not get policy record to clone");
2163 ConfigurationDataEntity clonedConfig = null;
2164 if(oldPolicy.getConfigurationData() != null){
2165 clonedConfig = new ConfigurationDataEntity();
2166 em.persist(clonedConfig);
2167 clonedConfig.setConfigBody(oldPolicy.getConfigurationData().getConfigBody());
2168 clonedConfig.setConfigType(oldPolicy.getConfigurationData().getConfigType());
2169 clonedConfig.setCreatedBy(username);
2170 clonedConfig.setConfigurationName(getConfigFile(newPolicyData[1], oldPolicy.getConfigurationData().getConfigType()));
2171 clonedConfig.setDescription(oldPolicy.getConfigurationData().getDescription());
2172 clonedConfig.setModifiedBy(username);
2175 ActionBodyEntity clonedAction = null;
2176 if(oldPolicy.getActionBodyEntity() != null){
2177 clonedAction = new ActionBodyEntity();
2178 em.persist(clonedAction);
2179 clonedAction.setActionBody(oldPolicy.getActionBodyEntity().getActionBody());
2180 clonedAction.setActionBodyName(newPolicyData[0]+"."+newPolicyData[1]+".json");
2181 clonedAction.setCreatedBy(username);
2182 clonedAction.setModifiedBy(username);
2189 private String processConfigPath(String configPath){
2190 String webappsPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS);
2191 if(webappsPath == null){
2192 logger.error("Webapps property does not exist");
2193 throw new IllegalArgumentException("Webapps property does not exist");
2195 configPath = configPath.replace("$URL", webappsPath);
2196 //make sure the correct slashes are in
2198 configPath = Paths.get(configPath).toString();
2199 } catch(InvalidPathException e){
2200 logger.error("Invalid config path: "+configPath, e);
2201 throw new IllegalArgumentException("Invalid config path: "+configPath);
2205 private String readConfigFile(String configPath){
2206 String configDataString = null;
2207 InputStream configContentStream = null;
2209 configContentStream = new FileInputStream(configPath);
2210 configDataString = IOUtils.toString(configContentStream);
2211 } catch (FileNotFoundException e) {
2212 logger.error("Caught FileNotFoundException on new FileInputStream("+configPath+")",e);
2213 throw new IllegalArgumentException("The config file path does not exist");
2214 } catch(IOException e2){
2215 logger.error("Caught IOException on newIOUtils.toString("+configContentStream+")",e2);
2216 throw new IllegalArgumentException("The config file path cannot be read");
2218 IOUtils.closeQuietly(configContentStream);
2220 if(configDataString == null){
2221 throw new IllegalArgumentException("The config file path cannot be read");
2223 return configDataString;
2227 public void createPolicy(Policy policy, String username){
2228 InputStream policyXmlStream = null;
2230 logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy("+policy+","+username+") called");
2231 String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, ".");
2232 //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP
2233 //and this transaction is intercepted up stream.
2234 String policyDataString;
2236 policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType)policy.getCorrectPolicyDataObject());
2237 policyDataString = IOUtils.toString(policyXmlStream);
2238 } catch (IOException e) {
2239 policyDataString = "could not read";
2240 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught IOException on IOUtils.toString("+policyXmlStream+")");
2241 throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter.");
2243 IOUtils.closeQuietly(policyXmlStream);
2244 String configPath = "";
2245 if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Config")) {
2246 configPath = evaluateXPath("/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", policyDataString);
2247 } else if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Action")) {
2248 configPath = evaluateXPath("/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, " +policy.policyAdapter.getActionAttribute()+ ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()", policyDataString);
2251 String prefix = null;
2252 if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Config")) {
2254 prefix = configPath.substring(configPath.indexOf(policyScope+".")+policyScope.concat(".").length(), configPath.lastIndexOf(policy.policyAdapter.getPolicyName()));
2255 if(isNullOrEmpty(policy.policyAdapter.getConfigBodyData())){
2256 String configData = "";
2258 String newConfigPath = configPath;
2260 newConfigPath = processConfigPath(newConfigPath);
2261 }catch(Exception e2){
2262 logger.error("Could not process config path: "+newConfigPath,e2);
2264 configData = readConfigFile(newConfigPath);
2265 }catch(Exception e){
2266 logger.error("Could not read config body data for "+configPath,e);
2268 policy.policyAdapter.setConfigBodyData(configData);
2270 } else if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Action")) {
2272 } else if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Decision")) {
2273 prefix = "Decision_";
2276 if(!(policy.policyAdapter.getData() instanceof PolicyType)){
2277 PolicyLogger.error("The data field is not an instance of PolicyType");
2278 throw new IllegalArgumentException("The data field is not an instance of PolicyType");
2280 String finalName = policyScope + "." + prefix+policy.policyAdapter.getPolicyName()+"."+((PolicyType)policy.policyAdapter.getData()).getVersion()+".xml";
2281 if(policy.policyAdapter.getConfigType() == null || policy.policyAdapter.getConfigType().equals("")){
2282 //get the config file extension
2284 if (configPath != null) {
2285 if (!configPath.equalsIgnoreCase("")) {
2286 ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());;
2290 if(ext.contains("txt")){
2291 policy.policyAdapter.setConfigType(OTHER_CONFIG);
2292 } else if(ext.contains("json")){
2293 policy.policyAdapter.setConfigType(JSON_CONFIG);
2294 } else if(ext.contains("xml")){
2295 policy.policyAdapter.setConfigType(XML_CONFIG);
2296 } else if(ext.contains("properties")){
2297 policy.policyAdapter.setConfigType(PROPERTIES_CONFIG);
2299 if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Action")){
2300 policy.policyAdapter.setConfigType(JSON_CONFIG);
2305 createPolicy(policy.policyAdapter, username, policyScope,finalName,policyDataString);
2307 if(policyXmlStream != null){
2309 policyXmlStream.close();
2310 } catch (IOException e) {
2311 logger.error("Exception Occured while closing input stream"+e);
2318 public void close(){
2319 synchronized(emLock){
2321 if(em.getTransaction().isActive()){
2322 em.getTransaction().rollback();
2326 if(transactionTimer instanceof Thread){
2327 transactionTimer.interrupt();
2335 public void createGroup(String groupId, String groupName, String groupDescription, String username) {
2336 logger.debug("deletePolicy(String policyToDeletes) as createGroup("+groupId+", "+groupName+", "+groupDescription+") called");
2337 if(isNullOrEmpty(groupId, groupName, username)){
2338 throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty");
2340 if(!(groupDescription instanceof String)){
2341 groupDescription = "";
2344 synchronized(emLock){
2345 checkBeforeOperationRun();
2346 Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
2347 checkGroupQuery.setParameter("groupId", groupId);
2348 checkGroupQuery.setParameter("deleted", false);
2349 List<?> checkGroupQueryList;
2351 checkGroupQueryList = checkGroupQuery.getResultList();
2352 } catch(Exception e){
2353 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on checkGroupQuery.getResultList()");
2354 throw new PersistenceException("Query failed trying to check for existing group");
2356 if(checkGroupQueryList.size() > 0){
2357 PolicyLogger.error("The group being added already exists with id "+groupId);
2358 throw new PersistenceException("The group being added already exists with id "+groupId);
2360 GroupEntity newGroup = new GroupEntity();
2361 em.persist(newGroup);
2362 newGroup.setCreatedBy(username);
2363 newGroup.setModifiedBy(username);
2364 newGroup.setGroupName(groupName);
2365 newGroup.setGroupId(groupId);
2366 newGroup.setDescription(groupDescription);
2369 this.groupId = newGroup.getGroupKey();
2374 public void updateGroup(OnapPDPGroup group, String username){
2375 logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup("+group+","+username+") called");
2377 throw new IllegalArgumentException("PDPGroup group must not be null");
2379 if(isNullOrEmpty(group.getId(), username)){
2380 throw new IllegalArgumentException("group.getId() and username must not be null or empty");
2383 synchronized(emLock){
2384 checkBeforeOperationRun();
2385 Query getGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
2386 getGroupQuery.setParameter("groupId", group.getId());
2387 getGroupQuery.setParameter("deleted", false);
2388 List<?> getGroupQueryList;
2390 getGroupQueryList = getGroupQuery.getResultList();
2391 } catch(Exception e){
2392 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getGroupQuery.getResultList()");
2393 throw new PersistenceException("Query failed trying to get group "+group.getId()+" for editing");
2395 if(getGroupQueryList.size() < 1){
2396 PolicyLogger.error("The group cannot be found to update with id "+group.getId());
2397 throw new PersistenceException("The group cannot be found to update with id "+group.getId());
2398 } else if(getGroupQueryList.size() > 1){
2399 PolicyLogger.error("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database");
2400 throw new PersistenceException("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database");
2402 GroupEntity groupToUpdateInDB = (GroupEntity)getGroupQueryList.get(0);
2403 if(!stringEquals(groupToUpdateInDB.getModifiedBy(), username)){
2404 groupToUpdateInDB.setModifiedBy(username);
2406 if(group.getDescription() != null && !stringEquals(group.getDescription(),groupToUpdateInDB.getDescription())){
2407 groupToUpdateInDB.setDescription(group.getDescription());
2409 //let's find out what policies have been deleted
2410 StdPDPGroup oldGroup = null;
2412 oldGroup = (StdPDPGroup) papEngine.getGroup(group.getId());
2413 } catch (PAPException e1) {
2414 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "We cannot get the group from the papEngine to delete policies");
2416 if(oldGroup == null){
2417 PolicyLogger.error("We cannot get the group from the papEngine to delete policies");
2419 Set<String> newPolicySet = new HashSet<>(group.getPolicies().size());
2420 //a multiple of n runtime is faster than n^2, so I am using a hashset to do the comparison
2421 for(PDPPolicy pol: group.getPolicies()){
2422 newPolicySet.add(pol.getId());
2424 for(PDPPolicy pol : oldGroup.getPolicies()){
2425 //should be fast since getPolicies uses a HashSet in StdPDPGroup
2426 if(!newPolicySet.contains(pol.getId())){
2427 String[] scopeAndName = getNameScopeAndVersionFromPdpPolicy(pol.getId());
2428 PolicyEntity policyToDelete = null;
2430 if(scopeAndName!=null){
2431 policyToDelete = getPolicy(scopeAndName[0],scopeAndName[1]);
2433 if ("XACMLPapServlet.doDelete".equals(username)) {
2435 Iterator<PolicyEntity> dbPolicyIt = groupToUpdateInDB.getPolicies().iterator();
2436 String policyName = getPolicyNameAndVersionFromPolicyFileName(policyToDelete.getPolicyName())[0];
2438 logger.info("PolicyDBDao: delete policy from GroupEntity");
2440 while(dbPolicyIt.hasNext()){
2441 PolicyEntity dbpolicy = dbPolicyIt.next();
2442 if(policyToDelete.getScope().equals(dbpolicy.getScope()) &&
2443 getPolicyNameAndVersionFromPolicyFileName(dbpolicy.getPolicyName())[0].equals(policyName)) {
2444 dbPolicyIt.remove();
2446 logger.info("PolicyDBDao: deleting policy from the existing group:\n "
2447 + "policyName is " + policyToDelete.getScope()+"."+policyToDelete.getPolicyName() + "\n"
2448 + "group is " + groupToUpdateInDB.getGroupId());
2451 }catch(Exception e){
2453 PolicyLogger.error("Could not delete policy with name: "+ policyToDelete.getScope()+"."+policyToDelete.getPolicyName()+"\n ID: "+ policyToDelete.getPolicyId());
2458 }catch(Exception e){
2459 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not get policy to remove: "+pol.getId());
2460 throw new PersistenceException("Could not get policy to remove: "+pol.getId());
2466 if(group.getName() != null && !stringEquals(group.getName(),groupToUpdateInDB.getgroupName())){
2467 //we need to check if the new id exists in the database
2468 String newGroupId = createNewPDPGroupId(group.getName());
2469 Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
2470 checkGroupQuery.setParameter("groupId", newGroupId);
2471 checkGroupQuery.setParameter("deleted", false);
2472 List<?> checkGroupQueryList;
2474 checkGroupQueryList = checkGroupQuery.getResultList();
2475 } catch(Exception e){
2476 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on checkGroupQuery.getResultList()");
2477 throw new PersistenceException("Query failed trying to check for existing group");
2479 if(checkGroupQueryList.size() != 0){
2480 PolicyLogger.error("The new group name already exists, group id "+newGroupId);
2481 throw new PersistenceException("The new group name already exists, group id "+newGroupId);
2483 groupToUpdateInDB.setGroupId(newGroupId);
2484 groupToUpdateInDB.setGroupName(group.getName());
2485 this.newGroupId = group.getId();
2489 this.groupId = groupToUpdateInDB.getGroupKey();
2494 public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) {
2495 logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup("+pdpID+", "+groupID+", "+pdpName+", "+pdpDescription+", "+pdpJmxPort+", "+username+") called");
2496 if(isNullOrEmpty(pdpID, groupID,pdpName,username)){
2497 throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty");
2499 if(!(pdpDescription instanceof String)){
2500 pdpDescription = "";
2502 synchronized(emLock){
2503 checkBeforeOperationRun();
2504 Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
2505 checkGroupQuery.setParameter("groupId", groupID);
2506 checkGroupQuery.setParameter("deleted", false);
2507 List<?> checkGroupQueryList;
2509 checkGroupQueryList = checkGroupQuery.getResultList();
2510 } catch(Exception e){
2511 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()");
2512 throw new PersistenceException("Query failed trying to check for existing group");
2514 if(checkGroupQueryList.size() != 1){
2515 PolicyLogger.error("The group does not exist");
2516 throw new PersistenceException("The group does not exist");
2518 Query checkDuplicateQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted");
2519 checkDuplicateQuery.setParameter("pdpId", pdpID);
2520 checkDuplicateQuery.setParameter("deleted", false);
2521 List<?> checkDuplicateList;
2523 checkDuplicateList = checkDuplicateQuery.getResultList();
2524 } catch(Exception e){
2525 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check for duplicate PDP "+pdpID+" on checkDuplicateQuery.getResultList()");
2526 throw new PersistenceException("Query failed trying to check for duplicate PDP "+pdpID);
2529 if(checkDuplicateList.size() > 0){
2530 logger.warn("PDP already exists with id "+pdpID);
2531 newPdp = (PdpEntity)checkDuplicateList.get(0);
2533 newPdp = new PdpEntity();
2537 newPdp.setCreatedBy(username);
2538 newPdp.setDeleted(false);
2539 newPdp.setDescription(pdpDescription);
2540 newPdp.setGroup((GroupEntity)checkGroupQueryList.get(0));
2541 newPdp.setJmxPort(pdpJmxPort);
2542 newPdp.setModifiedBy(username);
2543 newPdp.setPdpId(pdpID);
2544 newPdp.setPdpName(pdpName);
2547 this.pdpId = newPdp.getPdpKey();
2554 public void updatePdp(OnapPDP pdp, String username){
2555 logger.debug("updatePdp(PDP pdp, String username) as updatePdp("+pdp+","+username+") called");
2557 throw new IllegalArgumentException("PDP pdp must not be null");
2559 if(isNullOrEmpty(pdp.getId(),username)){
2560 throw new IllegalArgumentException("pdp.getId() and username must not be null or empty");
2563 synchronized(emLock){
2564 checkBeforeOperationRun();
2565 Query getPdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted");
2566 getPdpQuery.setParameter("pdpId", pdp.getId());
2567 getPdpQuery.setParameter("deleted", false);
2568 List<?> getPdpQueryList;
2570 getPdpQueryList = getPdpQuery.getResultList();
2571 } catch(Exception e){
2572 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getPdpQuery.getResultList()");
2573 throw new PersistenceException("Query failed trying to get PDP "+pdp.getId());
2575 if(getPdpQueryList.size() < 1){
2576 PolicyLogger.error("The pdp cannot be found to update with id "+pdp.getId());
2577 throw new PersistenceException("The pdp cannot be found to update with id "+pdp.getId());
2578 } else if(getPdpQueryList.size() > 1){
2579 PolicyLogger.error("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database");
2580 throw new PersistenceException("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database");
2582 PdpEntity pdpToUpdate = (PdpEntity)getPdpQueryList.get(0);
2583 if(!stringEquals(pdpToUpdate.getModifiedBy(), username)){
2584 pdpToUpdate.setModifiedBy(username);
2586 if(pdp.getDescription() != null && !stringEquals(pdp.getDescription(),pdpToUpdate.getDescription())){
2587 pdpToUpdate.setDescription(pdp.getDescription());
2589 if(pdp.getName() != null && !stringEquals(pdp.getName(),pdpToUpdate.getPdpName())){
2590 pdpToUpdate.setPdpName(pdp.getName());
2592 if(pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())){
2593 pdpToUpdate.setJmxPort(pdp.getJmxPort());
2597 this.pdpId = pdpToUpdate.getPdpKey();
2602 public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username){
2603 logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp("+pdp+","+group+","+username+") called");
2604 if(pdp == null || group == null){
2605 throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null");
2607 if(isNullOrEmpty(username,pdp.getId(),group.getId())){
2608 throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty");
2611 synchronized(emLock){
2612 checkBeforeOperationRun();
2613 //check if pdp exists
2614 Query getPdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted");
2615 getPdpQuery.setParameter("pdpId", pdp.getId());
2616 getPdpQuery.setParameter("deleted", false);
2617 List<?> getPdpQueryList;
2619 getPdpQueryList = getPdpQuery.getResultList();
2620 } catch(Exception e){
2621 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getPdpQuery.getResultList()");
2622 throw new PersistenceException("Query failed trying to get pdp to move with id "+pdp.getId());
2624 if(getPdpQueryList.size() < 1){
2625 PolicyLogger.error("The pdp cannot be found to move with id "+pdp.getId());
2626 throw new PersistenceException("The pdp cannot be found to move with id "+pdp.getId());
2627 } else if(getPdpQueryList.size() > 1){
2628 PolicyLogger.error("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database");
2629 throw new PersistenceException("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database");
2632 //check if new group exists
2633 Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
2634 checkGroupQuery.setParameter("groupId", group.getId());
2635 checkGroupQuery.setParameter("deleted", false);
2636 List<?> checkGroupQueryList;
2638 checkGroupQueryList = checkGroupQuery.getResultList();
2639 } catch(Exception e){
2640 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get group on checkGroupQuery.getResultList()");
2641 throw new PersistenceException("Query failed trying to get new group "+group.getId());
2643 if(checkGroupQueryList.size() != 1){
2644 PolicyLogger.error("The group "+group.getId()+" does not exist");
2645 throw new PersistenceException("The group "+group.getId()+" does not exist");
2647 GroupEntity groupToMoveInto = (GroupEntity)checkGroupQueryList.get(0);
2648 PdpEntity pdpToUpdate = (PdpEntity)getPdpQueryList.get(0);
2649 pdpToUpdate.setGroup(groupToMoveInto);
2650 if(!stringEquals(pdpToUpdate.getModifiedBy(), username)){
2651 pdpToUpdate.setModifiedBy(username);
2655 this.pdpId = pdpToUpdate.getPdpKey();
2660 public void changeDefaultGroup(OnapPDPGroup group, String username){
2661 logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup("+group+","+username+") called");
2663 throw new IllegalArgumentException("PDPGroup group must not be null");
2665 if(isNullOrEmpty(group.getId(),username)){
2666 throw new IllegalArgumentException("group.getId() and username must not be null or empty");
2669 synchronized(emLock){
2670 checkBeforeOperationRun();
2671 Query getGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
2672 getGroupQuery.setParameter("groupId", group.getId());
2673 getGroupQuery.setParameter("deleted", false);
2674 List<?> getGroupQueryList;
2676 getGroupQueryList = getGroupQuery.getResultList();
2677 } catch(Exception e){
2678 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getGroupQuery.getResultList()");
2679 throw new PersistenceException("Query failed trying to get group "+group.getId());
2681 if(getGroupQueryList.size() < 1){
2682 PolicyLogger.error("The group cannot be found to set default with id "+group.getId());
2683 throw new PersistenceException("The group cannot be found to set default with id "+group.getId());
2684 } else if(getGroupQueryList.size() > 1){
2685 PolicyLogger.error("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database");
2686 throw new PersistenceException("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database");
2688 GroupEntity newDefaultGroup = (GroupEntity)getGroupQueryList.get(0);
2689 newDefaultGroup.setDefaultGroup(true);
2690 if(!stringEquals(newDefaultGroup.getModifiedBy(), username)){
2691 newDefaultGroup.setModifiedBy(username);
2695 this.groupId = newDefaultGroup.getGroupKey();
2696 Query setAllGroupsNotDefault = em.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup WHERE g.deleted=:deleted AND g.groupKey<>:groupKey");
2697 //not going to set modified by for all groups
2698 setAllGroupsNotDefault.setParameter("defaultGroup", false);
2699 setAllGroupsNotDefault.setParameter("deleted", false);
2700 setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey());
2702 logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default");
2703 } catch(Exception e){
2704 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on setAllGroupsNotDefault.executeUpdate()");
2705 throw new PersistenceException("Could not set all other groups default to false");
2714 public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDBException {
2715 logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup("+group+", "+moveToGroup+","+username+") called");
2717 throw new IllegalArgumentException("PDPGroup group cannot be null");
2719 if(isNullOrEmpty(username,group.getId())){
2720 throw new IllegalArgumentException("group.getId() and and username must not be null or empty");
2723 if(group.isDefaultGroup()){
2724 PolicyLogger.error("The default group "+group.getId()+" was attempted to be deleted. It cannot be.");
2725 throw new PolicyDBException("You cannot delete the default group.");
2727 synchronized(emLock){
2728 checkBeforeOperationRun();
2729 Query deleteGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
2730 deleteGroupQuery.setParameter("groupId", group.getId());
2731 deleteGroupQuery.setParameter("deleted", false);
2732 List<?> deleteGroupQueryList;
2734 deleteGroupQueryList = deleteGroupQuery.getResultList();
2735 } catch(Exception e){
2736 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()");
2737 throw new PersistenceException("Query failed trying to check if group exists");
2739 if(deleteGroupQueryList.size() < 1){
2740 logger.warn("The group could not be found with id " + group.getId());
2742 } else if(deleteGroupQueryList.size() > 1){
2743 PolicyLogger.error("Somehow, more than one group with the id "+group.getId()+" were found in the database that are not deleted");
2744 throw new PersistenceException("Somehow, more than one group with the id "+group.getId()+" were found in the database that are not deleted");
2747 Query pdpsInGroupQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted");
2748 pdpsInGroupQuery.setParameter("group", ((GroupEntity)deleteGroupQueryList.get(0)));
2749 pdpsInGroupQuery.setParameter("deleted", false);
2750 List<?> pdpsInGroupList;
2752 pdpsInGroupList = pdpsInGroupQuery.getResultList();
2753 } catch(Exception e){
2754 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()");
2755 throw new PersistenceException("Query failed trying to get PDPs in group");
2757 if(pdpsInGroupList.size() > 0){
2758 if(moveToGroup != null){
2759 Query checkMoveToGroupQuery = em.createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted");
2760 checkMoveToGroupQuery.setParameter("groupId", moveToGroup.getId());
2761 checkMoveToGroupQuery.setParameter("deleted", false);
2762 List<?> checkMoveToGroupList;
2764 checkMoveToGroupList = checkMoveToGroupQuery.getResultList();
2765 } catch(Exception e){
2766 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList()");
2767 throw new PersistenceException("Query failed trying to check if group exists");
2769 if(checkMoveToGroupList.size() < 1){
2770 PolicyLogger.error("The group could not be found with id " + moveToGroup.getId());
2771 throw new PersistenceException("The group could not be found with id " + moveToGroup.getId());
2772 } else if(checkMoveToGroupList.size() > 1){
2773 PolicyLogger.error("Somehow, more than one group with the id "+moveToGroup.getId()+" were found in the database that are not deleted");
2774 throw new PersistenceException("Somehow, more than one group with the id "+moveToGroup.getId()+" were found in the database that are not deleted");
2776 GroupEntity newGroup = (GroupEntity)checkMoveToGroupList.get(0);
2777 for(Object pdpObject : pdpsInGroupList){
2778 PdpEntity pdp = (PdpEntity)pdpObject;
2779 pdp.setGroup(newGroup);
2780 if(!stringEquals(pdp.getModifiedBy(),username)){
2781 pdp.setModifiedBy(username);
2786 this.newGroupId = newGroup.getGroupId();
2787 } catch(PersistenceException e){
2788 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PersistenceException trying to set pdp group to null on em.flush()");
2789 throw new PersistenceException("Query failed trying to set pdp group to ");
2794 PolicyLogger.error("Group "+group.getId()+" is trying to be delted with PDPs. No group was provided to move them to");
2795 throw new PolicyDBException("Group has PDPs. Must provide a group for them to move to");
2800 GroupEntity groupToDelete = (GroupEntity)deleteGroupQueryList.get(0);
2801 groupToDelete.setDeleted(true);
2802 if(!stringEquals(groupToDelete.getModifiedBy(), username)){
2803 groupToDelete.setModifiedBy(username);
2806 this.groupId = groupToDelete.getGroupKey();
2811 public StdPDPGroup addPolicyToGroup(String groupID, String policyID, String username) throws PolicyDBException {
2812 logger.info("PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup("+groupID+", "+policyID+","+username+") called");
2813 if(isNullOrEmpty(groupID, policyID, username)){
2814 throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty");
2816 synchronized(emLock){
2817 checkBeforeOperationRun();
2818 //check if group exists
2819 Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
2820 groupQuery.setParameter("groupId", groupID);
2821 groupQuery.setParameter("deleted", false);
2822 List<?> groupQueryList;
2824 groupQueryList = groupQuery.getResultList();
2825 }catch(Exception e){
2826 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if group exists groupQuery.getResultList()");
2827 throw new PersistenceException("Query failed trying to check if group "+groupID+" exists");
2829 if(groupQueryList.size() < 1){
2830 PolicyLogger.error("Group policy is being added to does not exist with id "+groupID);
2831 throw new PersistenceException("Group policy is being added to does not exist with id "+groupID);
2832 } else if(groupQueryList.size() > 1){
2833 PolicyLogger.error("Somehow, more than one group with the id "+groupID+" were found in the database that are not deleted");
2834 throw new PersistenceException("Somehow, more than one group with the id "+groupID+" were found in the database that are not deleted");
2837 //we need to convert the form of the policy id that is used groups into the form that is used
2838 //for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml)
2839 String[] policyNameScopeAndVersion = getNameScopeAndVersionFromPdpPolicy(policyID);
2840 Query policyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName AND p.scope=:scope AND p.deleted=:deleted");
2841 policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]);
2842 policyQuery.setParameter("scope", policyNameScopeAndVersion[1]);
2843 policyQuery.setParameter("deleted", false);
2844 List<?> policyQueryList;
2846 policyQueryList = policyQuery.getResultList();
2847 } catch(Exception e){
2849 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if policy exists policyQuery.getResultList()");
2850 throw new PersistenceException("Query failed trying to check if policy "+policyNameScopeAndVersion[0]+" exists");
2852 if(policyQueryList.size() < 1){
2853 PolicyLogger.error("Policy being added to the group does not exist with policy id "+policyNameScopeAndVersion[0]);
2854 throw new PersistenceException("Policy being added to the group does not exist with policy id "+policyNameScopeAndVersion[0]);
2855 } else if(policyQueryList.size() > 1){
2856 PolicyLogger.error("Somehow, more than one policy with the id "+policyNameScopeAndVersion[0]+" were found in the database that are not deleted");
2857 throw new PersistenceException("Somehow, more than one group with the id "+policyNameScopeAndVersion[0]+" were found in the database that are not deleted");
2859 logger.info("PolicyDBDao: Getting group and policy from database");
2860 GroupEntity group = (GroupEntity)groupQueryList.get(0);
2861 PolicyEntity policy = (PolicyEntity)policyQueryList.get(0);
2862 Iterator<PolicyEntity> policyIt = group.getPolicies().iterator();
2863 String policyName = getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0];
2865 logger.info("PolicyDBDao: policyName retrieved is " + policyName);
2867 while(policyIt.hasNext()){
2868 PolicyEntity pol = policyIt.next();
2869 if(policy.getScope().equals(pol.getScope()) &&
2870 getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0].equals(policyName)) {
2874 }catch(Exception e){
2876 PolicyLogger.error("Could not delete old versions for policy "+policy.getPolicyName()+", ID: "+policy.getPolicyId());
2878 group.addPolicyToGroup(policy);
2881 // After adding policy to the db group we need to make sure the filesytem group is in sync with the db group
2883 StdPDPGroup pdpGroup = (StdPDPGroup) papEngine.getGroup(group.getGroupId());
2884 return synchronizeGroupPoliciesInFileSystem(pdpGroup, group);
2885 } catch (PAPException e) {
2887 PolicyLogger.error("PolicyDBDao: Could not synchronize the filesystem group with the database group. " + e.getMessage());
2894 //this means delete pdp not just remove from group
2896 public void removePdpFromGroup(String pdpID, String username) {
2897 logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup("+pdpID+","+username+") called");
2898 if(isNullOrEmpty(pdpID,username)){
2899 throw new IllegalArgumentException("pdpID and username must not be null or empty");
2901 synchronized(emLock){
2902 checkBeforeOperationRun();
2903 Query pdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted");
2904 pdpQuery.setParameter("pdpId", pdpID);
2905 pdpQuery.setParameter("deleted", false);
2908 pdpList = pdpQuery.getResultList();
2909 } catch(Exception e){
2910 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if pdp exists pdpQuery.getResultList()");
2911 throw new PersistenceException("Query failed trying to check if pdp "+pdpID+" exists");
2913 if(pdpList.size() > 1){
2914 PolicyLogger.error("Somehow, more than one pdp with the id "+pdpID+" were found in the database that are not deleted");
2915 throw new PersistenceException("Somehow, more than one pdp with the id "+pdpID+" were found in the database that are not deleted");
2916 } else if(pdpList.size() < 1){
2917 PolicyLogger.error("Pdp being removed does not exist with id "+pdpID);
2920 PdpEntity pdp = (PdpEntity)pdpList.get(0);
2922 if(!stringEquals(pdp.getModifiedBy(),username)){
2923 pdp.setModifiedBy(username);
2925 pdp.setDeleted(true);
2928 this.pdpId = pdp.getPdpKey();
2933 private PolicyDBDao(){
2937 public static PolicyDBDaoTestClass getPolicyDBDaoTestClass(){
2938 return new PolicyDBDao().new PolicyDBDaoTestClass();
2941 final class PolicyDBDaoTestClass {
2942 String getConfigFile(String filename, String scope, PolicyRestAdapter policy){
2943 return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy);
2945 String computeScope(String fullPath, String pathToExclude){
2946 return PolicyDBDao.computeScope(fullPath, pathToExclude);
2948 String encryptPassword(String password) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
2949 return PolicyDBDao.encryptPassword(password);
2951 String decryptPassword(String password) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
2952 return PolicyDBDao.decryptPassword(password);
2954 String getDescriptionFromXacml(String xacmlData){
2955 return PolicyDBDao.getDescriptionFromXacml(xacmlData);
2957 String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException{
2958 return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName);