[POLICY-6] add missing license information
[policy/drools-pdp.git] / policy-persistence / src / main / java / org / openecomp / policy / drools / persistence / PersistenceFeature.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * policy-persistence
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.drools.persistence;
22
23 import java.io.IOException;
24 import java.sql.Connection;
25 import java.sql.DriverManager;
26 import java.sql.PreparedStatement;
27 import java.sql.SQLException;
28 import java.util.Date;
29 import java.util.HashMap;
30 import java.util.Map;
31 import java.util.Properties;
32
33 import javax.persistence.EntityManagerFactory;
34 import javax.persistence.Persistence;
35
36 import org.eclipse.persistence.config.PersistenceUnitProperties;
37 import org.kie.api.KieServices;
38 import org.kie.api.runtime.Environment;
39 import org.kie.api.runtime.EnvironmentName;
40 import org.kie.api.runtime.KieSession;
41 import org.kie.api.runtime.KieSessionConfiguration;
42 import org.openecomp.policy.common.ia.IntegrityAudit;
43 import org.openecomp.policy.common.ia.IntegrityAuditProperties;
44 import org.openecomp.policy.common.im.StateManagement;
45 import org.openecomp.policy.common.logging.eelf.MessageCodes;
46 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
47 import org.openecomp.policy.common.logging.flexlogger.Logger;
48 import org.openecomp.policy.common.logging.flexlogger.PropertyUtil;
49 import org.openecomp.policy.drools.core.DroolsPDPIntegrityMonitor;
50 import org.openecomp.policy.drools.core.PolicySessionFeatureAPI;
51 import org.openecomp.policy.drools.core.IntegrityMonitorProperties;
52 import org.openecomp.policy.drools.core.PolicyContainer;
53 import org.openecomp.policy.drools.core.PolicySession;
54 import org.openecomp.policy.drools.features.PolicyEngineFeatureAPI;
55 import org.openecomp.policy.drools.im.PMStandbyStateChangeNotifier;
56 import org.openecomp.policy.drools.system.PolicyEngine;
57
58 import bitronix.tm.Configuration;
59 import bitronix.tm.TransactionManagerServices;
60 import bitronix.tm.resource.jdbc.PoolingDataSource;
61
62 /**
63  * If this feature is supported, there is a single instance of it.
64  * It adds persistence to Drools sessions, but it is also intertwined with
65  * active/standby state management and IntegrityMonitor. For now, they are
66  * all treated as a single feature, but it would be nice to separate them.
67  *
68  * The bulk of the code here was once in other classes, such as
69  * 'PolicyContainer' and 'Main'. It was moved here as part of making this
70  * a separate optional feature.
71  */
72 public class PersistenceFeature implements PolicySessionFeatureAPI, PolicyEngineFeatureAPI
73 {
74   // get an instance of logger
75   private static Logger logger =
76         FlexLogger.getLogger(PersistenceFeature.class);
77
78   // 'KieServices' singleton
79   static private KieServices kieServices = KieServices.Factory.get();
80
81   private static DroolsPdp myPdp;
82   private static Object myPdpSync = new Object();
83   private static DroolsPdpsElectionHandler electionHandler;
84
85   // indicates whether persistence has been disabled
86   private static boolean persistenceDisabled = false;
87
88   /*
89    * Used by JUnit testing to verify whether or not audit is running.
90    */
91   private static IntegrityAudit integrityAudit = null;
92
93   /**
94    * Lookup the adjunct for this feature that is associated with the
95    * specified PolicyContainer. If not found, create one.
96    *
97    * @param policyContainer the container whose adjunct we are looking up,
98    *    and possibly creating
99    * @return the associated 'ContainerAdjunct' instance, which may be new
100    */
101   private ContainerAdjunct getContainerAdjunct(PolicyContainer policyContainer)
102   {
103         Object rval = policyContainer.getAdjunct(this);
104         if (rval == null || ! (rval instanceof ContainerAdjunct))
105           {
106                 // adjunct does not exist, or has the wrong type (should never happen)
107                 rval = new ContainerAdjunct(policyContainer);
108                 policyContainer.setAdjunct(this, rval);
109           }
110         return((ContainerAdjunct)rval);
111   }
112
113   /**************************/
114   /* 'FeatureAPI' interface */
115   /**************************/
116
117   /**
118    * {@inheritDoc}
119    */
120   @Override
121         public int getSequenceNumber()
122   {
123         return(1);
124   }
125
126   /**
127    * {@inheritDoc}
128    */
129   @Override
130         public void globalInit(String args[], String configDir)
131   {
132         // Initialization code associated with 'PolicyContainer'
133         DroolsPDPIntegrityMonitor droolsPdpIntegrityMonitor = null;
134         try
135           {
136                 droolsPdpIntegrityMonitor = DroolsPDPIntegrityMonitor.init(configDir);
137           }
138         catch (Exception e)
139           {
140                 logger.error(MessageCodes.EXCEPTION_ERROR, e,
141                                          "main", "DroolsPDPIntegrityMonitor.init()");
142           }
143
144         initializePersistence(configDir, droolsPdpIntegrityMonitor);
145
146         // 1. Start Integrity Monitor (unless it was specifically disabled in the CORE layer
147                 
148                 
149         if (persistenceDisabled) {
150           System.out.println("WARNING: Starting Engine with Persistance disabled");
151           logger.warn("Starting Engine with Persistance disabled");
152         } else {
153           DroolsPDPIntegrityMonitor im = null;
154           //At this point the DroolsPDPIntegrityMonitor instance must exist
155           try {
156                 im = DroolsPDPIntegrityMonitor.getInstance();
157           } catch (Exception e1) {
158                 String msg = "policy-core startup failed to get DroolsPDPIntegrityMonitor instance:  \n" + e1;
159                 System.out.println(msg);
160                 e1.printStackTrace();
161           }
162           //Now get the StateManagement instance so we can register our observer
163           StateManagement sm = im.getStateManager();
164                         
165           //Create an instance of the Observer
166           PMStandbyStateChangeNotifier pmNotifier = new PMStandbyStateChangeNotifier();
167                         
168           //Register the PMStandbyStateChangeNotifier Observer
169           sm.addObserver(pmNotifier);
170         }
171   }
172
173   /**
174    * This is a hook to create a new persistent KieSession.
175    *
176    * {@inheritDoc}
177    */
178   @Override
179         public KieSession activatePolicySession
180         (PolicyContainer policyContainer, String name, String kieBaseName)
181   {
182         return(getContainerAdjunct(policyContainer)
183                    .newPersistentKieSession(name, kieBaseName));
184   }
185
186   /**
187    * {@inheritDoc}
188    */
189   @Override
190         public void disposeKieSession(PolicySession policySession)
191   {
192         // TODO: There should be one data source per session
193         getContainerAdjunct(policySession.getPolicyContainer())
194           .disposeKieSession();
195   }
196
197   /**
198    * {@inheritDoc}
199    */
200   @Override
201         public void destroyKieSession(PolicySession policySession)
202   {
203         // TODO: There should be one data source per session
204         getContainerAdjunct(policySession.getPolicyContainer())
205           .destroyKieSession();
206   }
207
208   /**
209    * {@inheritDoc}
210    */
211   @Override
212         public boolean isPersistenceEnabled()
213   {
214         return(!persistenceDisabled);
215   }
216         
217   /**
218    * {@inheritDoc}
219    */
220   @Override
221         public boolean afterStart(PolicyEngine engine) 
222   {
223         // ASSERTION: engine == PolicyEngine.manager
224     PolicyEngine.manager.lock();
225     return false;
226   }
227         
228    /**
229         * {@inheritDoc}
230         */
231    @Override
232         public boolean beforeStart(PolicyEngine engine) {return false;}
233         
234    /**
235         * {@inheritDoc}
236         */
237    @Override
238         public boolean beforeShutdown(PolicyEngine engine) {return false;}
239
240    /**
241         * {@inheritDoc}
242         */
243    @Override
244         public boolean afterShutdown(PolicyEngine engine) {return false;}
245    
246    /**
247         * {@inheritDoc}
248         */
249    @Override
250     public boolean beforeConfigure(PolicyEngine engine, Properties properties) {return false;}
251
252    /**
253         * {@inheritDoc}
254         */
255    @Override
256     public boolean afterConfigure(PolicyEngine engine) {return false;}
257
258    /**
259         * {@inheritDoc}
260         */
261    @Override
262         public boolean beforeActivate(PolicyEngine engine)
263   {
264         if (persistenceDisabled)
265           {
266                 return(false);
267           }
268
269         // The following code will remove "old" Drools 'sessioninfo' records, so
270         // they aren't used to restore data to Drools sessions. This also has the
271         // useful side-effect of removing abandoned records as well.
272
273         // Fetch the timeout value, in seconds. If it is not specified or is
274         // less than or equal to 0, no records are removed.
275
276         String timeoutString = null;
277         int timeout = 0;
278         try
279           {
280                 timeoutString = DroolsPersistenceProperties.getProperty
281                   ("persistence.sessioninfo.timeout");
282                 if (timeoutString != null)
283                   {
284                         // timeout parameter is specified
285                         timeout = Integer.valueOf(timeoutString);
286                   }
287           }
288         catch (NumberFormatException e)
289           {
290                 logger.error("Invalid value for Drools persistence property "
291                                          + "persistence.sessioninfo.timeout: "
292                                          + timeoutString);
293           }
294         if (timeout <= 0)
295           {
296                 // parameter is not specified, is <= 0, or is an invalid number
297                 return(false);
298           }
299
300         // if we reach this point, we are ready to remove old records from
301         // the database
302
303         Connection connection = null;
304         PreparedStatement statement = null;
305         try
306           {
307                 // fetch database parameters from properties
308
309                 String url = DroolsPersistenceProperties.getProperty
310                   (DroolsPersistenceProperties.DB_URL);
311                 String user = DroolsPersistenceProperties.getProperty
312                   (DroolsPersistenceProperties.DB_USER);
313                 String password = DroolsPersistenceProperties.getProperty
314                   (DroolsPersistenceProperties.DB_PWD);
315
316                 if (url != null && user != null && password != null)
317                   {
318                         // get DB connection
319                         connection = DriverManager.getConnection(url, user, password);
320
321                         // create statement to delete old records
322                         statement = connection.prepareStatement
323                           ("DELETE FROM sessioninfo WHERE "
324                            + "timestampdiff(second,lastmodificationdate,now()) > ?");
325                         statement.setInt(1,timeout);
326
327                         // execute statement
328                         int count = statement.executeUpdate();
329                         logger.info("Cleaning up sessioninfo table -- "
330                                                 + count + " records removed");
331                   }
332           }
333         catch (SQLException e)
334           {
335                 logger.error("Clean up of sessioninfo table failed", e);
336           }
337         finally
338           {
339                 // cleanup
340                 if (statement != null)
341                   {
342                         try
343                           {
344                                 statement.close();
345                           }
346                         catch (SQLException e)
347                           {
348                                 logger.error("SQL connection close failed", e);
349                           }
350                   }
351                 if (connection != null)
352                   {
353                         try
354                           {
355                                 connection.close();
356                           }
357                         catch (SQLException e)
358                           {
359                                 logger.error("SQL connection close failed", e);
360                           }
361                   }
362           }
363         return(false);
364   }
365
366    /**
367         * {@inheritDoc}
368         */
369    @Override
370    public boolean afterActivate(PolicyEngine engine) {return false;}
371
372    /**
373         * {@inheritDoc}
374         */
375    @Override
376     public boolean beforeDeactivate(PolicyEngine engine) {return false;}
377
378    /**
379         * {@inheritDoc}
380         */
381    @Override
382     public boolean afterDeactivate(PolicyEngine engine) {return false;}
383
384    /**
385         * {@inheritDoc}
386         */
387    @Override
388     public boolean beforeStop(PolicyEngine engine) {return false;}
389
390    /**
391         * {@inheritDoc}
392         */
393    @Override
394     public boolean afterStop(PolicyEngine engine) {return false;}
395
396    /**
397         * {@inheritDoc}
398         */
399    @Override
400     public boolean beforeLock(PolicyEngine engine) {return false;}
401
402    /**
403         * {@inheritDoc}
404         */
405    @Override
406     public boolean afterLock(PolicyEngine engine) {return false;}
407
408    /**
409         * {@inheritDoc}
410         */
411    @Override
412     public boolean beforeUnlock(PolicyEngine engine) {return false;}
413
414    /**
415         * {@inheritDoc}
416         */
417    @Override
418     public boolean afterUnlock(PolicyEngine engine) {return false;}
419
420   /**************************/
421
422   /**
423    * @return 'true' if Drools persistence is disabled, and 'false' if not
424    */
425   static public boolean getPersistenceDisabled()
426   {
427         return(persistenceDisabled);
428   }
429
430   /**
431    * Read in the persistence properties, determine whether persistence is
432    * enabled or disabled, and initialize persistence if enabled.
433    */
434   private static void initializePersistence(String configDir, DroolsPDPIntegrityMonitor droolsPdpIntegrityMonitor)
435   {
436           
437                 try {
438                         Properties pDrools = PropertyUtil.getProperties(configDir
439                                         + "/droolsPersistence.properties");
440                         DroolsPersistenceProperties.initProperties(pDrools);
441                         Properties pXacml = PropertyUtil.getProperties(configDir
442                                         + "/xacmlPersistence.properties");
443                         XacmlPersistenceProperties.initProperties(pXacml);
444                         if ("true".equals(pDrools.getProperty("persistenceDisabled"))) {
445                                 // 'persistenceDisabled' only relates to the 'drools'
446                                 // database. The fact that integrityMonitor/xacml depends upon
447                                 // persistence is an implementation detail there (which can't
448                                 // currently be disabled), and doesn't directly affect
449                                 // 'policy-core'.
450                                 persistenceDisabled = true;
451                         } 
452                 } catch (IOException e1) {
453                         logger.error(MessageCodes.MISS_PROPERTY_ERROR, e1,
454                                         "initializePersistence");
455                 }
456                   
457             /*
458              * Might as well handle the Integrity Monitor properties here, too.
459              */
460             try {
461                   Properties pIm =
462                     PropertyUtil.getProperties(configDir + "/IntegrityMonitor.properties");
463                   IntegrityMonitorProperties.initProperties(pIm);
464                   logger.info("initializePersistence: resourceName=" + IntegrityMonitorProperties.getProperty(IntegrityMonitorProperties.PDP_INSTANCE_ID));
465             } catch (IOException e1) {
466                   logger.error(MessageCodes.MISS_PROPERTY_ERROR, e1, "initializePersistence");
467             }
468           
469
470                 if (persistenceDisabled) {
471                         // The persistence design is tied to 'DroolsPdpsElectionHandler',
472                         // so we should bypass that as well. This also means that we
473                         // won't get active/standby notifications, so we need to go
474                         // into the 'active' state in order to have any 'PolicySession'
475                         // instances.
476                         return;
477                 }
478
479             DroolsPdpsConnector conn = getDroolsPdpsConnector("ncompPU");
480                 String uniquePdpId = IntegrityMonitorProperties.getProperty(IntegrityMonitorProperties.PDP_INSTANCE_ID);
481                 if(uniquePdpId == null){
482                         throw new NullPointerException();
483                 }
484                 
485                 /*
486                  * In a JUnit test environment, one or more PDPs may already have been
487                  * inserted in the DB, so we need to check for this.
488                  */
489                 DroolsPdp existingPdp = conn.getPdp(uniquePdpId);
490                 if (existingPdp != null) {
491                         System.out.println("Found existing PDP record, pdpId="
492                                         + existingPdp.getPdpId() + ", isDesignated="
493                                         + existingPdp.isDesignated() + ", updatedDate="
494                                         + existingPdp.getUpdatedDate());
495                         myPdp = existingPdp;
496                 }
497                 
498             /*
499              * Kick off integrity audit for Drools DB.
500              */
501             startIntegrityAudit(configDir);
502                                 
503                 synchronized(myPdpSync){
504                         if(myPdp == null){
505
506                                 myPdp = new DroolsPdpImpl(uniquePdpId,false,4,new Date());      
507                         }
508                         if(myPdp != null){
509                                 String site_name = "";
510                                 site_name = IntegrityMonitorProperties.getProperty(IntegrityMonitorProperties.SITE_NAME);
511                                 if (site_name == null) {
512                                         site_name = "";
513                                 }else{
514                                         site_name = site_name.trim();
515                                 }
516                                 myPdp.setSiteName(site_name);
517                         }
518                         if(electionHandler == null){
519                 electionHandler = new DroolsPdpsElectionHandler(conn,myPdp,droolsPdpIntegrityMonitor);
520                         }
521                 }
522                 Configuration bitronixConfiguration = TransactionManagerServices.getConfiguration();
523                 bitronixConfiguration.setJournal(null);
524                 bitronixConfiguration.setServerId(uniquePdpId);
525                 System.out.println("\n\nThis controller is a standby, waiting to be chosen as primary...\n\n");
526                 logger.info("\n\nThis controller is a standby, waiting to be chosen as primary...\n\n");
527   }
528
529         private static void startIntegrityAudit(String configDir) {
530
531                 logger.info("startIntegrityAudit: Entering, configDir='" + configDir
532                                 + "'");
533
534                 /*
535                  * Initialize Integrity Audit properties. file.
536                  */
537                 try {
538
539                         String resourceName = IntegrityMonitorProperties
540                                         .getProperty(IntegrityMonitorProperties.PDP_INSTANCE_ID);
541
542                         /*
543                          * Load properties for auditing of Drools DB.
544                          */
545                         Properties droolsPia = PropertyUtil.getProperties(configDir
546                                         + "/IntegrityMonitor.properties");
547
548                         /*
549                          * Supplement properties specific to the IntegrityMonitor (e.g.
550                          * site_name, node_type, resource.name) with properties specific to
551                          * persisting Drools DB entities (see
552                          * ../policy-core/src/main/resources/persistence.xml)
553                          * 
554                          * Note: integrity_audit_period_seconds is defined in
555                          * IntegrityMonitor.properties, rather than creating a whole new
556                          * "IntegrityAudit.properties" file for just one property.
557                          */
558                         droolsPia
559                                         .setProperty(
560                                                         IntegrityAuditProperties.DB_DRIVER,
561                                                         DroolsPersistenceProperties
562                                                                         .getProperty(DroolsPersistenceProperties.DB_DRIVER));
563                         droolsPia.setProperty(IntegrityAuditProperties.DB_PWD,
564                                         DroolsPersistenceProperties
565                                                         .getProperty(DroolsPersistenceProperties.DB_PWD));
566                         droolsPia.setProperty(IntegrityAuditProperties.DB_URL,
567                                         DroolsPersistenceProperties
568                                                         .getProperty(DroolsPersistenceProperties.DB_URL));
569                         droolsPia.setProperty(IntegrityAuditProperties.DB_USER,
570                                         DroolsPersistenceProperties
571                                                         .getProperty(DroolsPersistenceProperties.DB_USER));
572
573                         /*
574                          * Start audit for Drools DB.
575                          */
576                         integrityAudit = new IntegrityAudit(
577                                         resourceName, "auditDroolsPU", droolsPia);
578                         integrityAudit.startAuditThread();
579
580                 } catch (IOException e1) {
581                         logger.error(
582                                         MessageCodes.MISS_PROPERTY_ERROR,
583                                         e1,
584                                         "initializePersistence: IntegrityAuditProperties: "
585                                                         + e1.getMessage());
586                 } catch (Exception e2) {
587                         logger.error(
588                                         MessageCodes.EXCEPTION_ERROR,
589                                         e2,
590                                         "initializePersistence: IntegrityAuditProperties: "
591                                                         + e2.getMessage());
592                 }
593
594                 logger.debug("startIntegrityAudit: Exiting");
595
596         }
597   
598         /*
599          * Moved code to instantiate a JpaDroolsPdpsConnector object from main() to
600          * this method, so it can also be accessed from StandbyStateChangeNotifier
601          * class.
602          */
603         public static DroolsPdpsConnector getDroolsPdpsConnector(String pu) {
604
605                 Map<String, Object> propMap = new HashMap<String, Object>();
606                 propMap.put("javax.persistence.jdbc.driver", DroolsPersistenceProperties
607                                 .getProperty(DroolsPersistenceProperties.DB_DRIVER));
608                 propMap.put("javax.persistence.jdbc.url",
609                                 DroolsPersistenceProperties.getProperty(DroolsPersistenceProperties.DB_URL));
610                 propMap.put("javax.persistence.jdbc.user", DroolsPersistenceProperties
611                                 .getProperty(DroolsPersistenceProperties.DB_USER));
612                 propMap.put("javax.persistence.jdbc.password",
613                                 DroolsPersistenceProperties.getProperty(DroolsPersistenceProperties.DB_PWD));
614
615                 EntityManagerFactory emf = Persistence.createEntityManagerFactory(
616                                 pu, propMap);
617                 DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emf);
618
619                 return conn;
620         }
621
622         /*
623          * IntegrityAudit instance is needed by JUnit testing to ascertain whether
624          * or not audit is running.
625          */
626         public static IntegrityAudit getIntegrityAudit() {
627
628                 return integrityAudit;
629
630         }
631
632   /* ============================================================ */
633
634   /**
635    * Each instance of this class is a logical extension of a 'PolicyContainer'
636    * instance. It's reference is stored in the 'adjuncts' table within the
637    * 'PolicyContainer', and will be garbage-collected with the container.
638    */
639   class ContainerAdjunct
640   {
641         // this is the 'PolicyContainer' instance that this adjunct is extending
642         private PolicyContainer policyContainer;
643         private PoolingDataSource ds = null;
644
645         /**
646          * Constructor - initialize a new 'ContainerAdjunct'
647          *
648          * @param policyContainer the 'PolicyContainer' instance this adjunct
649          *              is extending
650          */
651         ContainerAdjunct(PolicyContainer policyContainer)
652         {
653           this.policyContainer = policyContainer;
654         }
655
656         /**
657          * Create a new persistent KieSession. If there is already a corresponding
658          * entry in the database, it is used to initialize the KieSession. If not,
659          * a completely new session is created.
660          *
661          * @param name the name of the KieSession (which is also the name of
662          *      the associated PolicySession)
663          * @param kieBaseName the name of the 'KieBase' instance containing
664          *      this session
665          * @return a new KieSession with persistence enabled (if persistence is
666          *      disabled, 'null' is returned
667          */
668         private KieSession newPersistentKieSession(String name, String kieBaseName)
669         {
670           if (persistenceDisabled)
671                 {
672                   return(null);
673                 }
674           long desiredSessionId = -1;
675           synchronized (myPdpSync) {
676                 
677         
678         
679                 for(DroolsSession droolsSession : electionHandler.getSessions()){
680                   if(droolsSession.getSessionName().equals(name)){
681                         desiredSessionId = droolsSession.getSessionId();
682                   }
683                 }
684           }
685           System.out.println("\n\nThis controller is primary... coming up with session "+desiredSessionId+"\n\n");
686           logger.info("\n\nThis controller is primary... coming up with session "+desiredSessionId+"\n\n");
687           Map<String, Object> props = new HashMap<String, Object>();
688           props.put("URL", DroolsPersistenceProperties.getProperty(DroolsPersistenceProperties.DB_URL));
689           props.put("user", DroolsPersistenceProperties.getProperty(DroolsPersistenceProperties.DB_USER));
690           props.put("password", DroolsPersistenceProperties.getProperty(DroolsPersistenceProperties.DB_PWD));
691           props.put("dataSource",DroolsPersistenceProperties.getProperty(DroolsPersistenceProperties.DB_DATA_SOURCE));
692           logger.info("getPolicySession:session does not exist -- attempt to create one with name " + name);
693           // session does not exist -- attempt to create one
694           System.getProperties().put("java.naming.factory.initial","bitronix.tm.jndi.BitronixInitialContextFactory");
695           Environment env = kieServices.newEnvironment();
696           //kContainer.newKieBase(null);
697           ds = new PoolingDataSource();                 
698           ds.setUniqueName("jdbc/BitronixJTADataSource"+name);
699           ds.setClassName( (String)props.remove("dataSource"));
700           //ds.setClassName( "org.h2.Driver" );
701           ds.setMaxPoolSize( 3 );
702           ds.setIsolationLevel("SERIALIZABLE");
703           ds.setAllowLocalTransactions( true );
704           //ds.getDriverProperties().put( "user", "sa" );
705           //ds.getDriverProperties().put( "password", "" );
706           //ds.getDriverProperties().put( "URL", "jdbc:h2:tcp://localhost/drools" );
707           ds.getDriverProperties().putAll(props);
708           ds.init();    
709           Properties emfProperties = new Properties();
710           emfProperties.setProperty(PersistenceUnitProperties.JTA_DATASOURCE, "jdbc/BitronixJTADataSource"+name);
711           env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, Persistence.createEntityManagerFactory("ncompsessionsPU",emfProperties));
712           env.set(EnvironmentName.TRANSACTION_MANAGER,TransactionManagerServices.getTransactionManager());
713           KieSessionConfiguration kConf = KieServices.Factory.get().newKieSessionConfiguration();
714           KieSession kieSession;
715           try{
716                 kieSession = kieServices.getStoreServices().loadKieSession(desiredSessionId, policyContainer.getKieContainer().getKieBase(kieBaseName), kConf, env);
717                 System.out.println("LOADING We can load session "+desiredSessionId+", going to create a new one");
718                 logger.info("LOADING We can load session "+desiredSessionId+", going to create a new one");
719           }catch(Exception e){
720                 System.out.println("LOADING We cannot load session "+desiredSessionId+", going to create a new one");
721
722                 logger.info("LOADING We cannot load session "+desiredSessionId+", going to create a new one");
723                 kieSession = kieServices.getStoreServices().newKieSession(policyContainer.getKieContainer().getKieBase(kieBaseName), null, env);
724                 System.out.println("LOADING CREATED "+kieSession.getIdentifier());
725                 logger.info("LOADING CREATED "+kieSession.getIdentifier());
726           }
727           synchronized (myPdpSync) {
728                 myPdp.setSessionId(name,kieSession.getIdentifier());
729                 electionHandler.updateMyPdp();
730           }
731           return(kieSession);
732         }
733
734         private void disposeKieSession()
735         {
736         if (ds != null)
737           {
738                 ds.close();
739                 ds = null;
740           }
741         }
742
743         private void destroyKieSession()
744         {
745           // does the same thing as 'dispose'
746           disposeKieSession();
747         }
748   }
749 }