11package aces .webctrl .postgresql .core ;
22import java .nio .file .*;
3+ import java .sql .*;
34import javax .servlet .*;
5+ import java .util .*;
46import java .util .concurrent .*;
57import com .controlj .green .addonsupport .*;
8+ import com .controlj .green .addonsupport .access .*;
69import com .controlj .green .common .CJProduct ;
710public class Initializer implements ServletContextListener {
811 /** Name of the addon used for auto udpates */
@@ -45,6 +48,8 @@ public class Initializer implements ServletContextListener {
4548 private volatile static long nextSave = 0 ;
4649 /** Stores log messages before sending them to the database. */
4750 public final static ConcurrentLinkedQueue <LogMessage > logCache = new ConcurrentLinkedQueue <LogMessage >();
51+ /** Root system connection to the database. */
52+ private volatile static SystemConnection con = null ;
4853 /**
4954 * Entry point of this add-on.
5055 */
@@ -119,13 +124,13 @@ public void run(){
119124 @ Override public void contextDestroyed (ServletContextEvent sce ){
120125 stop = true ;
121126 if (mainThread ==null ){
122- Config . save ();
127+ handleDestruction ();
123128 }else {
124129 mainThread .interrupt ();
125130 synchronized (syncNotifier ){
126131 syncNotifier .notifyAll ();
127132 }
128- Config . save ();
133+ handleDestruction ();
129134 //Wait for the primary processing thread to terminate.
130135 while (true ){
131136 try {
@@ -137,6 +142,23 @@ public void run(){
137142 log ("Execution terminated." );
138143 new Sync (Event .SHUTDOWN );
139144 }
145+ private static void handleDestruction (){
146+ Config .save ();
147+ // We deregister the PostgreSQL driver so that Tomcat does not complain
148+ final ClassLoader cl = Thread .currentThread ().getContextClassLoader ();
149+ final Enumeration <Driver > drivers = DriverManager .getDrivers ();
150+ Driver driver ;
151+ while (drivers .hasMoreElements ()) {
152+ driver = drivers .nextElement ();
153+ if (driver .getClass ().getClassLoader ()==cl ) {
154+ try {
155+ DriverManager .deregisterDriver (driver );
156+ }catch (Throwable t ){
157+ log (t );
158+ }
159+ }
160+ }
161+ }
140162 /**
141163 * Tells the processing thread to invoke a synchronization event ASAP.
142164 */
@@ -146,6 +168,15 @@ public static void syncNow(){
146168 syncNotifier .notifyAll ();
147169 }
148170 }
171+ /**
172+ * @return the root system connection used by this application.
173+ */
174+ public static SystemConnection getConnection (){
175+ if (con ==null ){
176+ con = DirectAccess .getDirectAccess ().getRootSystemConnection ();
177+ }
178+ return con ;
179+ }
149180 /**
150181 * @return the name of this application.
151182 */
0 commit comments