KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > core > CoreServlet


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.core;
21
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.net.HttpURLConnection JavaDoc;
25 import java.security.Provider JavaDoc;
26 import java.security.Security JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Enumeration JavaDoc;
29 import java.util.EventListener JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.StringTokenizer JavaDoc;
32
33 import javax.security.auth.login.Configuration JavaDoc;
34 import javax.servlet.ServletException JavaDoc;
35 import javax.servlet.UnavailableException JavaDoc;
36 import javax.servlet.http.HttpServletRequest JavaDoc;
37 import javax.servlet.http.HttpServletResponse JavaDoc;
38 import javax.swing.event.EventListenerList JavaDoc;
39
40 import org.apache.commons.digester.Digester;
41 import org.apache.commons.logging.Log;
42 import org.apache.commons.logging.LogFactory;
43 import org.apache.struts.Globals;
44 import org.apache.struts.action.ActionServlet;
45 import org.apache.struts.action.RequestProcessor;
46 import org.apache.struts.config.ModuleConfig;
47 import org.apache.struts.util.MessageResourcesFactory;
48
49 import com.maverick.ssl.SSLTransportFactory;
50 import com.sslexplorer.agent.AgentRequestHandler;
51 import com.sslexplorer.boot.BootProgressMonitor;
52 import com.sslexplorer.boot.ContextHolder;
53 import com.sslexplorer.boot.ContextListener;
54 import com.sslexplorer.boot.PropertyClassManager;
55 import com.sslexplorer.boot.PropertyDefinitionCategory;
56 import com.sslexplorer.boot.SSLTransportJCE;
57 import com.sslexplorer.extensions.ApplicationParameters;
58 import com.sslexplorer.extensions.ExtensionException;
59 import com.sslexplorer.extensions.forms.ConfigureExtensionsForm;
60 import com.sslexplorer.extensions.store.ExtensionStore;
61 import com.sslexplorer.jdbc.JDBCUserDatabase;
62 import com.sslexplorer.jdbc.hsqldb.EmbeddedHSQLDBServer;
63 import com.sslexplorer.keystore.wizards.KeyStoreImportTypeManager;
64 import com.sslexplorer.keystore.wizards.types.ReplyFromCAImportType;
65 import com.sslexplorer.keystore.wizards.types.RootServerCertificateImportType;
66 import com.sslexplorer.keystore.wizards.types.ServerAuthenticationKeyImportType;
67 import com.sslexplorer.keystore.wizards.types.TrustedServerCertificateImportType;
68 import com.sslexplorer.keystore.wizards.types._3SPPurchaseImportType;
69 import com.sslexplorer.language.Language;
70 import com.sslexplorer.language.LanguagePackDefinition;
71 import com.sslexplorer.language.LanguagePackManager;
72 import com.sslexplorer.navigation.NavigationBar;
73 import com.sslexplorer.navigation.NavigationManager;
74 import com.sslexplorer.notification.Notifier;
75 import com.sslexplorer.notification.agent.AgentMessageSink;
76 import com.sslexplorer.notification.smtp.SMTPMessageSink;
77 import com.sslexplorer.policyframework.PolicyDatabaseFactory;
78 import com.sslexplorer.policyframework.ResourceStack;
79 import com.sslexplorer.properties.ProfilesFactory;
80 import com.sslexplorer.properties.Property;
81 import com.sslexplorer.properties.impl.policyattributes.PolicyAttributes;
82 import com.sslexplorer.properties.impl.profile.ProfileProperties;
83 import com.sslexplorer.properties.impl.realms.RealmProperties;
84 import com.sslexplorer.properties.impl.resource.ResourceProperties;
85 import com.sslexplorer.properties.impl.systemconfig.SystemConfigKey;
86 import com.sslexplorer.properties.impl.systemconfig.SystemConfiguration;
87 import com.sslexplorer.properties.impl.userattributes.UserAttributes;
88 import com.sslexplorer.requesthandler.test.TestRequestHandler;
89 import com.sslexplorer.rss.FeedManager;
90 import com.sslexplorer.security.AuthenticationModuleManager;
91 import com.sslexplorer.security.Constants;
92 import com.sslexplorer.security.EmbeddedClientAuthenticationModule;
93 import com.sslexplorer.security.HTTPAuthenticationModule;
94 import com.sslexplorer.security.LogonControllerFactory;
95 import com.sslexplorer.security.PasswordAuthenticationModule;
96 import com.sslexplorer.security.PersonalQuestionsAuthenticationModule;
97 import com.sslexplorer.security.SystemDatabaseFactory;
98 import com.sslexplorer.security.UserDatabase;
99 import com.sslexplorer.security.UserDatabaseDefinition;
100 import com.sslexplorer.security.WebDAVAuthenticationModule;
101 import com.sslexplorer.table.TableItemActionMenuTree;
102 import com.sslexplorer.tasks.timer.StoppableTimer;
103 import com.sslexplorer.unixauth.UNIXUserDatabase;
104
105 /**
106  * Main controlling servlet. This extends struts own
107  * {@link org.apache.struts.action.ActionServlet}. Pretty much all SSL-Explorer
108  * actions will come through here.
109  * <p>
110  * Many features in SSL-Explorer require access to this servlet as it manages
111  * pages scripts, the logon controller, the policy database, the plugin manager,
112  * the system database and the events system.
113  * <p>
114  * Only a single instance of this servlet will ever exist, a reference to which
115  * is available through the static {@link #getServlet()} method.
116  *
117  * @author Brett Smith <brett@3sp.com>
118  */

119 public class CoreServlet extends ActionServlet implements ContextListener {
120
121     /**
122      *
123      */

124     private static final long serialVersionUID = 2175322073390766579L;
125
126     final static Log log = LogFactory.getLog(CoreServlet.class);
127
128     private static CoreServlet instance;
129
130     private CoreMessageResources applicationStoreResources;
131
132     private EventListenerList JavaDoc coreListeners;
133
134     private boolean logonControllerLocked;
135
136     private StringBuffer JavaDoc tileConfigFiles = new StringBuffer JavaDoc();
137
138     private List JavaDoc<CoreScript> pageScripts;
139
140     private Notifier notifier;
141
142     private EmbeddedHSQLDBServer dbServer;
143
144     private boolean shuttingDown;
145
146     private boolean devConfig;
147
148     private Digester digester;
149     
150     private ModuleConfig moduleConfig;
151     
152     private boolean pastInitialisation;
153     
154     private BootProgressMonitor bootProgressMonitor;
155
156     /**
157      * Constructor
158      */

159     public CoreServlet() {
160         super();
161         instance = this;
162         pageScripts = new ArrayList JavaDoc<CoreScript>();
163         coreListeners = new EventListenerList JavaDoc();
164         NavigationManager.addMenuTree(new CoreMenuTree());
165         NavigationManager.addMenuTree(new PageTaskMenuTree());
166         NavigationManager.addMenuTree(new ToolBarMenuTree());
167         NavigationManager.addMenuTree(new NavigationBar());
168         NavigationManager.addMenuTree(new TableItemActionMenuTree());
169         Configuration.setConfiguration(new CoreJAASConfiguration());
170         addTileConfigurationFile("/WEB-INF/tiles-defs.xml");
171
172         // Make sure that Http redirects are followed in places where we use URL
173
// to connect to our website
174
HttpURLConnection.setFollowRedirects(true);
175
176     }
177
178     /**
179      * Add a database
180      *
181      * @param databaseName database
182      * @param file
183      * @throws Exception
184      */

185     public void addDatabase(String JavaDoc databaseName, File JavaDoc file) throws Exception JavaDoc {
186         if (log.isInfoEnabled())
187             log.info("Adding database " + databaseName + " to folder " + file.getPath());
188         dbServer.addDatabase(databaseName, file);
189     }
190
191     /**
192      * Add a {@link CoreScript} that will be made available on every page. Note,
193      * for the scripts to appear the theme must include the
194      * <strong>explorer:pageScripts</strong> tag.
195      *
196      * @param script script to add to all pages
197      */

198     public void addPageScript(CoreScript script) {
199         pageScripts.add(script);
200     }
201
202     /**
203      * Remove a {@link CoreScript} from those made available on every page.
204      *
205      * @param script script to remove from all pages
206      */

207     public void removePageScript(CoreScript script) {
208         pageScripts.remove(script);
209     }
210
211     /**
212      * Return a list of all the currently registered page scripts.
213      *
214      * @return list of page scripts
215      */

216     public List JavaDoc getPageScripts() {
217         return pageScripts;
218     }
219
220     /**
221      * Return a command separated list of tiles configuration files that are
222      * currently in use.
223      *
224      * @return list of tiles configuration files
225      */

226     public String JavaDoc getTilesConfigurationFiles() {
227         return tileConfigFiles.toString();
228     }
229
230     /**
231      * Add a {@link CoreListener} to the list of object that will be sent
232      * {@link CoreEvent}s.
233      *
234      * @param listener listener to add
235      */

236     public void addCoreListener(CoreListener listener) {
237         coreListeners.add(CoreListener.class, listener);
238     }
239
240     /**
241      * Remove a {@link CoreListener} from the list of object that will be sent
242      * {@link CoreEvent}s.
243      *
244      * @param listener listener to remove
245      */

246     public void removeCoreListener(CoreListener listener) {
247         coreListeners.remove(CoreListener.class, listener);
248     }
249
250     /**
251      * Fire a {@link CoreEvent} at all {@link CoreListener}s that have
252      * registered an interest in events.
253      *
254      * @param evt event to fire to all listener
255      */

256     public void fireCoreEvent(CoreEvent evt) {
257         EventListener JavaDoc[] l = coreListeners.getListeners(CoreListener.class);
258         for (int i = l.length - 1; i >= 0; i--) {
259             /*
260              * We dont want badly behaved listeners to throw uncaught
261              * execeptions and upset other listeners
262              */

263             try {
264                 ((CoreListener) l[i]).coreEvent(evt);
265             } catch (Throwable JavaDoc t) {
266                 log.error("Event failed.", t);
267             }
268         }
269     }
270
271     /*
272      * (non-Javadoc)
273      *
274      * @see org.apache.struts.action.ActionServlet#initOther()
275      */

276     protected void initOther() throws ServletException JavaDoc {
277         super.initOther();
278
279         // Some sanity checks
280
checkDevEnvironment();
281
282         // Intiailise notifier
283
initNotifier();
284
285         // Listen for core events
286
addCoreListener(new DefaultCoreListener());
287
288         // Initialise plugin manager
289
if (log.isInfoEnabled())
290             log.info("Creating extension manager.");
291
292         /*
293          * Load the application store resources - these may be changed by the
294          * application store when new descriptors are loaded
295          */

296
297         MessageResourcesFactory messageResourcesFactory = new CoreMessageResourcesFactory(getClass().getClassLoader());
298         applicationStoreResources = (CoreMessageResources) messageResourcesFactory.createResources("com.sslexplorer.applications.store.ApplicationResources");
299         applicationStoreResources.setReturnNull(false);
300
301         // finally setup the scheduler
302
this.getServletContext().setAttribute(StoppableTimer.NAME, new StoppableTimer());
303     }
304
305
306     /**
307      * Get the {@link CoreMessageResources} that contains all installed
308      * extension message resource.
309      *
310      * @return extension store message resources
311      */

312     public CoreMessageResources getExtensionStoreResources() {
313         return applicationStoreResources;
314     }
315
316     /**
317      * @param path
318      */

319     public void addTileConfigurationFile(String JavaDoc path) {
320         if (log.isInfoEnabled())
321             log.info("Adding tile configuration file " + path);
322         if (tileConfigFiles.length() > 0)
323             tileConfigFiles.append(',');
324         tileConfigFiles.append(path);
325     }
326
327     /**
328      * @param path
329      */

330     public void removeTileConfigurationFile(String JavaDoc path) {
331         if (log.isInfoEnabled())
332             log.info("Removing tile configuration file " + path);
333         // TODO Why on earth are we using a string to store the list of tile
334
// moduleConfig files?
335
StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
336         StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(tileConfigFiles.toString(), ",");
337         while (t.hasMoreTokens()) {
338             String JavaDoc p = t.nextToken();
339             if (!p.equals(path)) {
340                 if (buf.length() > 0) {
341                     buf.append(",");
342                 }
343                 buf.append(p);
344             }
345         }
346         tileConfigFiles = buf;
347         if (log.isInfoEnabled())
348             log.info("New tile configuration path is " + tileConfigFiles.toString());
349     }
350     
351     protected void activateCore() throws ServletException JavaDoc {
352
353         // Add the default language definition
354
LanguagePackDefinition pdef = new LanguagePackDefinition(null, "core");
355         pdef.addLanguage(new Language(null, "en", "English"));
356         LanguagePackManager.getInstance().addLanguagePackDefinition(pdef);
357
358         // now the databases are registered we need a userdatabase setup so the
359
// process can proceed.
360
bootProgressMonitor.updateMessage("Initialising user database");
361         bootProgressMonitor.updateProgress(50);
362         UserDatabaseManager.getInstance().initialize(ContextHolder.getContext().isSetupMode());
363
364         // Use the default system database if no other has been registered
365
try {
366             bootProgressMonitor.updateMessage("Initialising system database");
367             bootProgressMonitor.updateProgress(55);
368             SystemDatabaseFactory.getInstance().open(this);
369         } catch (Exception JavaDoc e) {
370             log.error("Failed to initialise system database.", e);
371             throw new ServletException JavaDoc("Failed to initialise system database.", e);
372         }
373
374         // Policy database
375
try {
376             bootProgressMonitor.updateMessage("Initialising policy database");
377             bootProgressMonitor.updateProgress(60);
378             PolicyDatabaseFactory.getInstance().open(this);
379             PolicyDatabaseFactory.getInstance().initAccessRights();
380         } catch (Exception JavaDoc e) {
381             log.error("Failed to initialise policy database.", e);
382             throw new ServletException JavaDoc("Failed to initialise policy database.", e);
383         }
384
385         // Start the plugins
386
bootProgressMonitor.updateMessage("Activating extensions");
387         bootProgressMonitor.updateProgress(65);
388         if ("true".equalsIgnoreCase(System.getProperty("sslexplorer.disableExtensions"))) {
389             log.warn("Extension manager disabled, extension store wont be activated.");
390         } else {
391             try {
392                 ExtensionStore.getInstance().activate();
393             } catch (ExtensionException ee) {
394                 throw new ServletException JavaDoc("Failed to activate extension store.", ee);
395             }
396         }
397
398         // Register CONNECT handler
399
bootProgressMonitor.updateMessage("Registering request handlers");
400         bootProgressMonitor.updateProgress(75);
401         if (!ContextHolder.getContext().isSetupMode()) {
402             if (System.getProperty("sslexplorer.testing", "false").equals("true")) {
403                 ContextHolder.getContext().registerRequestHandler(new TestRequestHandler());
404             }
405             ContextHolder.getContext().registerRequestHandler(new AgentRequestHandler());
406         }
407
408         /*
409          * If running in setup mode, we don't want to change any properties
410          * until the wizard has finished
411          */

412         if (ContextHolder.getContext().isSetupMode())
413             PropertyClassManager.getInstance().setAutoCommit(false);
414
415         /*
416          * Disable any property categories for user databases configuration
417          * if not in setup mode
418          */

419         if (!ContextHolder.getContext().isSetupMode()) {
420             bootProgressMonitor.updateMessage("Removing hidden categories");
421             bootProgressMonitor.updateProgress(80);
422             UserDatabase defaultUserDatabase = UserDatabaseManager.getInstance().getDefaultUserDatabase();
423             if (defaultUserDatabase == null) {
424                 // throw new ServletException("There is no default userdatabase,
425
// check log for details.");
426
} else {
427                 log.info("The default user database is " + defaultUserDatabase.getDatabaseDescription());
428                 for (UserDatabaseDefinition def : UserDatabaseManager.getInstance().getUserDatabaseDefinitions()) {
429                     if (def.getInstallationCategory() > 0) {
430                         PropertyDefinitionCategory cat = PropertyClassManager.getInstance()
431                                         .getPropertyClass(RealmProperties.NAME)
432                                         .getPropertyDefinitionCategory(def.getInstallationCategory());
433                         log.info("Disabling user database configuration category " + def.getInstallationCategory() + " (" + cat.hashCode() + ")");
434                         if (cat == null) {
435                             log.error("No such category " + def.getInstallationCategory());
436                         } else {
437                             cat.setEnabled(false);
438                         }
439                     }
440                 }
441             }
442         }
443
444         // Start the notifier
445
try {
446             notifier.start();
447         } catch (Exception JavaDoc e) {
448             log.error("Failed to start notifier.", e);
449         }
450         
451         // Starting Updating RSS feeds
452

453         if (!Property.getPropertyBoolean(new SystemConfigKey("ui.rssFeeds"))) {
454             if (log.isInfoEnabled())
455                 log.info("RSS feeds disabled, not checking");
456         }
457         else {
458
459             FeedManager.getInstance().startUpdating();
460         }
461     }
462
463     protected void initNotifier() throws ServletException JavaDoc {
464
465         File JavaDoc queueDir = new File JavaDoc(ContextHolder.getContext().getConfDirectory(), "queue");
466         if (!queueDir.exists()) {
467             if (!queueDir.mkdirs()) {
468                 throw new ServletException JavaDoc("Could not create message queue directory " + queueDir.getAbsolutePath());
469             }
470         }
471         if (!queueDir.isDirectory()) {
472             throw new ServletException JavaDoc("Message queue directory appears to not be a directory.");
473         }
474         if (!queueDir.canWrite() || !queueDir.canRead()) {
475             throw new ServletException JavaDoc("Message queue directory " + queueDir.getAbsolutePath() + " has incorret permissions.");
476         }
477         try {
478             notifier = new Notifier(queueDir);
479         } catch (IOException JavaDoc e2) {
480             log.error("Notifier failed to initialise.", e2);
481             throw new ServletException JavaDoc(e2);
482         }
483         try {
484             notifier.addSink(new SMTPMessageSink(), Property.getPropertyBoolean(new SystemConfigKey("smtp.startOnStartup")));
485         } catch (Exception JavaDoc e) {
486             e.printStackTrace();
487             throw new ServletException JavaDoc("Failed to add SMTP message sink.", e);
488         }
489         notifier.addSink(new AgentMessageSink(), true);
490     }
491
492     /*
493      * (non-Javadoc)
494      *
495      * @see org.apache.struts.action.ActionServlet#initModuleMessageResources(org.apache.struts.config.ModuleConfig)
496      */

497     protected void initModuleMessageResources(final ModuleConfig config) throws ServletException JavaDoc {
498         super.initModuleMessageResources(config);
499         if (log.isInfoEnabled())
500             log.info("Initialising extension message resources");
501         getServletContext().setAttribute("applicationStore" + config.getPrefix(), applicationStoreResources);
502     }
503
504     /**
505      * There will only ever been one instance of the servlet, this method allows
506      * static access to it.
507      *
508      * @return the core servlet instance
509      */

510     public static CoreServlet getServlet() {
511         return instance;
512     }
513
514     /**
515      * Get the notifier instance that may be used to send notification messages
516      * to users, adminstrators etc.
517      *
518      * @return notifier
519      */

520     public Notifier getNotifier() {
521         return notifier;
522     }
523
524     /*
525      * (non-Javadoc)
526      *
527      * @see javax.servlet.GenericServlet#init()
528      */

529     public void init() throws ServletException JavaDoc {
530         pastInitialisation = false;
531          
532
533         try {
534
535             ContextHolder.getContext().addContextListener(this);
536             
537             if(System.getProperty("sslexplorer.disableNewSSLEngine", "false").equals("false"))
538                 SSLTransportFactory.setTransportImpl(SSLTransportJCE.class);
539             
540             // Init bouncy castle
541
Class JavaDoc c = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
542             Security.insertProviderAt((Provider JavaDoc) c.newInstance(), 0);
543
544             // Start the database
545
// TODO this should be configurable
546
dbServer = new EmbeddedHSQLDBServer("true".equalsIgnoreCase(System.getProperty("sslexplorer.hsqldb.tcpipServer",
547                 "false")));
548
549             // Load the property classes
550
PropertyClassManager.getInstance().registerPropertyClass(new ProfileProperties());
551             PropertyClassManager.getInstance().registerPropertyClass(new SystemConfiguration());
552             PropertyClassManager.getInstance().registerPropertyClass(new UserAttributes());
553             PropertyClassManager.getInstance().registerPropertyClass(new PolicyAttributes());
554             PropertyClassManager.getInstance().registerPropertyClass(new RealmProperties());
555             PropertyClassManager.getInstance().registerPropertyClass(new ApplicationParameters());
556             PropertyClassManager.getInstance().registerPropertyClass(new ResourceProperties());
557             
558             // Load the property database and categories
559
// Use the default system database if no other has been registered
560
try {
561                 ProfilesFactory.getInstance().open(this);
562             } catch (Exception JavaDoc e) {
563                 log.error("Failed to initialise property database.", e);
564                 throw new ServletException JavaDoc("Failed to initialise system database.", e);
565             }
566             
567             bootProgressMonitor = ContextHolder.getContext().getBootProgressMonitor();
568             
569             // Initialise extensions
570
bootProgressMonitor.updateMessage("Initialising extensions");
571             bootProgressMonitor.updateProgress(10);
572             initExtensionStore();
573
574             // Initialise core
575
bootProgressMonitor.updateMessage("Initialising core");
576             bootProgressMonitor.updateProgress(20);
577             initInternal();
578             initOther();
579             initServlet();
580
581             getServletContext().setAttribute(Globals.ACTION_SERVLET_KEY, this);
582             initModuleConfigFactory();
583             // Initialize modules as needed
584
ModuleConfig moduleConfig = initModuleConfig("", config);
585             initCore();
586
587             // Start extensions
588
bootProgressMonitor.updateMessage("Starting extensions");
589             bootProgressMonitor.updateProgress(30);
590             startExtensions();
591             
592             // Update module configuration
593
bootProgressMonitor.updateMessage("Updating configuration");
594             bootProgressMonitor.updateProgress(40);
595             initModuleMessageResources(moduleConfig);
596             initModuleDataSources(moduleConfig);
597             initModulePlugIns(moduleConfig);
598             
599             // Start extensions
600
bootProgressMonitor.updateMessage("Activating core");
601             bootProgressMonitor.updateProgress(45);
602             activateCore();
603
604             // do not freeze, we want to be able to dynamically change struts
605
// configuration
606
// moduleConfig.freeze();
607

608             bootProgressMonitor.updateMessage("Finalising configuration");
609             bootProgressMonitor.updateProgress(85);
610             Enumeration JavaDoc names = getServletConfig().getInitParameterNames();
611             while (names.hasMoreElements()) {
612                 String JavaDoc name = (String JavaDoc) names.nextElement();
613                 if (!name.startsWith("moduleConfig/")) {
614                     continue;
615                 }
616                 String JavaDoc prefix = name.substring(6);
617                 moduleConfig = initModuleConfig(prefix, getServletConfig().getInitParameter(name));
618                 initModuleMessageResources(moduleConfig);
619                 initModuleDataSources(moduleConfig);
620                 initModulePlugIns(moduleConfig);
621                 // do not freeze, we want to be able to dynamically change
622
// struts configuration
623
// moduleConfig.freeze();
624
}
625
626             this.initModulePrefixes(this.getServletContext());
627             this.destroyConfigDigester();
628
629             fireCoreEvent(new CoreEvent(this, CoreEventConstants.SERVER_STARTED, null, null));
630
631         } catch (UnavailableException JavaDoc ex) {
632             throw ex;
633         } catch (Throwable JavaDoc t) {
634
635             // The follow error message is not retrieved from internal message
636
// resources as they may not have been able to have been
637
// initialized
638
log.error("Failed to initialise SSL-Explorer core.", t);
639             throw new UnavailableException JavaDoc(t.getMessage());
640         }
641         finally {
642             pastInitialisation = true;
643         }
644     }
645
646     /*
647      * (non-Javadoc)
648      *
649      * @see org.apache.struts.action.ActionServlet#initModuleConfig(java.lang.String,
650      * java.lang.String)
651      */

652     protected ModuleConfig initModuleConfig(String JavaDoc prefix, String JavaDoc paths) throws ServletException JavaDoc {
653         moduleConfig = super.initModuleConfig(prefix, paths);
654         digester = initConfigDigester();
655         moduleConfig.getControllerConfig().setProcessorClass("com.sslexplorer.core.CoreRequestProcessor");
656         return moduleConfig;
657     }
658     
659     protected void initCore() throws ServletException JavaDoc {
660
661 // // Process each specified resource path
662
// while (paths.length() > 0) {
663
// digester.push(moduleConfig);
664
// String path = null;
665
// int comma = paths.indexOf(',');
666
// if (comma >= 0) {
667
// path = paths.substring(0, comma).trim();
668
// paths = paths.substring(comma + 1);
669
// } else {
670
// path = paths.trim();
671
// paths = "";
672
// }
673
//
674
// if (path.length() < 1) {
675
// break;
676
// }
677
//
678
// this.parseModuleConfigFile(digester, path);
679
// }
680

681         // Add the additional default struts configs
682

683         digester.push(moduleConfig);
684         this.parseModuleConfigFile(digester, "/WEB-INF/wizard-struts-config.xml");
685         digester.push(moduleConfig);
686         this.parseModuleConfigFile(digester, "/WEB-INF/ajax-struts-config.xml");
687
688         /**
689          * Install Maverick SSL support
690          */

691         try {
692             if (log.isInfoEnabled())
693                 log.info("Installing Maverick SSL");
694             com.maverick.ssl.https.HttpsURLStreamHandlerFactory.addHTTPSSupport();
695         } catch (IOException JavaDoc ex1) {
696             throw new ServletException JavaDoc("Failed to install Maverick SSL support");
697         }
698         boolean strictHostVerification = false;
699         System.setProperty("com.maverick.ssl.allowUntrustedCertificates", String.valueOf(!strictHostVerification));
700         System.setProperty("com.maverick.ssl.allowInvalidCertificates", String.valueOf(!strictHostVerification));
701
702         if (log.isInfoEnabled())
703             log.info("Adding default authentication modules.");
704         // Add the default authentication modules
705
AuthenticationModuleManager.getInstance().registerModule("Password",
706             PasswordAuthenticationModule.class,
707             "properties",
708             true,
709             true,
710             false);
711         AuthenticationModuleManager.getInstance().registerModule("HTTP",
712             HTTPAuthenticationModule.class,
713             "properties",
714             true,
715             true,
716             false);
717         AuthenticationModuleManager.getInstance().registerModule("PersonalQuestions",
718             PersonalQuestionsAuthenticationModule.class,
719             "properties",
720             false,
721             true,
722             false);
723         AuthenticationModuleManager.getInstance().registerModule("WebDAV",
724             WebDAVAuthenticationModule.class,
725             "properties",
726             true,
727             false,
728             true);
729         AuthenticationModuleManager.getInstance().registerModule("EmbeddedClient",
730             EmbeddedClientAuthenticationModule.class,
731             "properties",
732             true,
733             false,
734             true);
735
736         // Add the default page scripts
737
addPageScript(new CoreScript(CoreScript.PAGE_HEADER, "JavaScript", "/js/cookieDetect.jsp", null, "text/javascript"));
738         addPageScript(new CoreScript(CoreScript.PAGE_HEADER, "JavaScript", "/js/prototype.js", null, "text/javascript"));
739         addPageScript(new CoreScript(CoreScript.PAGE_HEADER, "JavaScript", "/js/extensions.js", null, "text/javascript"));
740         addPageScript(new CoreScript(CoreScript.PAGE_HEADER, "JavaScript", "/js/scriptaculous.js", null, "text/javascript"));
741         addPageScript(new CoreScript(CoreScript.PAGE_HEADER, "JavaScript", "/js/overlibmws.js", null, "text/javascript"));
742         addPageScript(new CoreScript(CoreScript.PAGE_HEADER, "JavaScript", "/js/ajaxtags.js", null, "text/javascript"));
743         addPageScript(new CoreScript(CoreScript.PAGE_HEADER, "JavaScript", "/js/cookies.js", null, "text/javascript"));
744         addPageScript(new CoreScript(CoreScript.PAGE_HEADER, "JavaScript", "/js/table.js", null, "text/javascript"));
745         addPageScript(new CoreScript(CoreScript.PAGE_HEADER, "JavaScript", "/js/datetimepicker.js", null, "text/javascript"));
746         addPageScript(new CoreScript(CoreScript.PAGE_HEADER, "JavaScript", "/js/modalbox.js", null, "text/javascript"));
747         addPageScript(new CoreScript(CoreScript.AFTER_BODY_START, "JavaScript", "/js/set.js", null, "text/javascript"));
748         addPageScript(new CoreScript(CoreScript.AFTER_BODY_START, "JavaScript", "/js/resources.js", null, "text/javascript"));
749         addPageScript(new CoreScript(CoreScript.AFTER_BODY_START, "JavaScript", "/js/items.js", null, "text/javascript"));
750         addPageScript(new CoreScript(CoreScript.AFTER_BODY_START, "JavaScript", "/js/input.js", null, "text/javascript"));
751         addPageScript(new CoreScript(CoreScript.AFTER_BODY_START, "JavaScript", "/js/windowManager.js", null, "text/javascript"));
752         addPageScript(new CoreScript(CoreScript.BEFORE_BODY_END, "JavaScript", "/js/wz_tooltip.js", null, "text/javascript"));
753
754         // Add the default panels
755
PanelManager.getInstance().addPanel(new DefaultPanel("menu",
756                         Panel.SIDEBAR,
757                         50,
758                         null,
759                         "menu",
760                         "navigation",
761                         false,
762                         true,
763                         false,
764                         false));
765         PanelManager.getInstance().addPanel(new DefaultPanel("editingResourceInfo",
766                         Panel.SIDEBAR,
767                         100,
768                         "/WEB-INF/jsp/tiles/editingResourceInfo.jspf",
769                         null,
770                         "navigation",
771                         false,
772                         true,
773                         false,
774                         false) {
775             public boolean isAvailable(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc layout) {
776                 return super.isAvailable(request, response, layout) && !ResourceStack.isEmpty(request.getSession())
777                     && request.getSession().getAttribute(Constants.WIZARD_SEQUENCE) == null;
778             }
779
780         });
781         PanelManager.getInstance().addPanel(new DefaultPanel("wizardSequenceInfo",
782                         Panel.SIDEBAR,
783                         100,
784                         "/WEB-INF/jsp/tiles/wizardSequenceInfo.jspf",
785                         null,
786                         "navigation",
787                         false,
788                         true,
789                         false,
790                         false) {
791             public boolean isAvailable(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc layout) {
792                 return super.isAvailable(request, response, layout) && ResourceStack.isEmpty(request.getSession())
793                     && request.getSession().getAttribute(Constants.WIZARD_SEQUENCE) != null;
794             }
795         });
796 // PanelManager.getInstance().addPanel(new DefaultPanel("about",
797
// Panel.SIDEBAR,
798
// 1000,
799
// "/WEB-INF/jsp/tiles/about.jspf",
800
// null,
801
// "navigation",
802
// false,
803
// false,
804
// false,
805
// false) {
806
//
807
// public boolean isAvailable(HttpServletRequest request, HttpServletResponse response, String layout) {
808
// return LogonControllerFactory.getInstance().getSessionInfo(request) != null && layout.equals(MAIN_LAYOUT) && !ContextHolder.getContext().isSetupMode()
809
// && super.isAvailable(request, response, layout);
810
// }
811
//
812
// });
813
PanelManager.getInstance().addPanel(new DefaultPanel("pageInfo",
814                         Panel.CONTENT,
815                         25,
816                         "/WEB-INF/jsp/tiles/pageInfo.jspf",
817                         null,
818                         "navigation") {
819
820             public boolean isAvailable(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc layout) {
821                 return ( LogonControllerFactory.getInstance().getSessionInfo(request) != null || ContextHolder.getContext().isSetupMode() ) &&
822                     request.getSession().getAttribute(Constants.SESSION_LOCKED) == null;
823             }
824
825         });
826         PanelManager.getInstance().addPanel(new DefaultPanel("content", Panel.CONTENT, 50, null, "content", "navigation", false));
827         PanelManager.getInstance().addPanel(new DefaultPanel("panelOptions",
828                         Panel.MESSAGES,
829                         10,
830                         "/WEB-INF/jsp/tiles/panelOptions.jspf",
831                         null,
832                         "navigation",
833                         true,
834                         true,
835                         true,
836                         true) {
837             
838             public String JavaDoc getDefaultFrameState() {
839                 return FRAME_CLOSED;
840             }
841
842         });
843         PanelManager.getInstance().addPanel(new DefaultPanel("pageTasks",
844                         Panel.MESSAGES,
845                         50,
846                         "/WEB-INF/jsp/tiles/pageTasks.jspf",
847                         "pageTasks",
848                         "navigation",
849                         false,
850                         false,
851                         true,
852                         true));
853         PanelManager.getInstance().addPanel(new DefaultPanel("toolBar",
854             Panel.CONTENT,
855             35,
856             "/WEB-INF/jsp/tiles/toolBar.jspf",
857             null,
858             "navigation") {
859             public boolean isAvailable(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc layout) {
860                 return ( LogonControllerFactory.getInstance().getSessionInfo(request) != null || ContextHolder.getContext().isSetupMode() ) &&
861                 request.getSession().getAttribute(Constants.TOOL_BAR_ITEMS) != null;
862             }
863         });
864         PanelManager.getInstance().addPanel(new DefaultPanel("errorMessages",
865                         Panel.MESSAGES,
866                         60,
867                         "/WEB-INF/jsp/tiles/errorMessages.jspf",
868                         null,
869                         "navigation",
870                         true,
871                         false,
872                         true,
873                         true));
874         PanelManager.getInstance().addPanel(new DefaultPanel("warnings",
875                         Panel.MESSAGES,
876                         70,
877                         "/WEB-INF/jsp/tiles/warnings.jspf",
878                         null,
879                         "navigation",
880                         true,
881                         true,
882                         true,
883                         true));
884         PanelManager.getInstance().addPanel(new DefaultPanel("infoMessages",
885                         Panel.MESSAGES,
886                         80,
887                         "/WEB-INF/jsp/tiles/infoMessages.jspf",
888                         null,
889                         "navigation",
890                         true,
891                         true,
892                         true,
893                         true));
894         PanelManager.getInstance().addPanel(new ClipboardPanel());
895         PanelManager.getInstance().addPanel(new DefaultPanel("rssFeeds",
896                         Panel.MESSAGES,
897                         120,
898                         "/WEB-INF/jsp/tiles/rssFeeds.jspf",
899                         null,
900                         "navigation",
901                         true,
902                         true,
903                         true,
904                         true) {
905         });
906         PanelManager.getInstance().addPanel(new DefaultPanel("userSessions",
907                         Panel.STATUS_TAB,
908                         10,
909                         "/WEB-INF/jsp/content/setup/userSessions.jspf",
910                         null,
911                         "setup",
912                         false));
913         PanelManager.getInstance().addPanel(new DefaultPanel("systemInfo",
914                         Panel.STATUS_TAB,
915                         20,
916                         "/WEB-INF/jsp/content/setup/systemInfo.jspf",
917                         null,
918                         "setup",
919                         false));
920
921         // Add the default key store import types
922
KeyStoreImportTypeManager.getInstance().registerType(new _3SPPurchaseImportType());
923         KeyStoreImportTypeManager.getInstance().registerType(new RootServerCertificateImportType());
924         KeyStoreImportTypeManager.getInstance().registerType(new ReplyFromCAImportType());
925         KeyStoreImportTypeManager.getInstance().registerType(new ServerAuthenticationKeyImportType());
926         KeyStoreImportTypeManager.getInstance().registerType(new TrustedServerCertificateImportType());
927
928         // Add the default user databases
929
UserDatabaseManager.getInstance().registerDatabase(new UserDatabaseDefinition(JDBCUserDatabase.class,
930                         "builtIn",
931                         "properties",
932                         -1));
933
934         // Only register UNIXAuth if /etc/passwd iailable
935
if (new File JavaDoc("/etc/passwd").canRead()) {
936             UserDatabaseManager.getInstance().registerDatabase(new UserDatabaseDefinition(UNIXUserDatabase.class,
937                             "unixAuth",
938                             "properties",
939                             -1));
940         }
941         
942         /* Add the 'site' VFS directory as a resource base. This must be
943          * done because we need access to the resources without authentication
944          */

945         File JavaDoc siteDir = new File JavaDoc(ContextHolder.getContext().getConfDirectory(), "site");
946         try {
947             if (!siteDir.exists()) {
948                 siteDir.mkdirs();
949             }
950             ContextHolder.getContext().addResourceBase(siteDir.toURL());
951         } catch (Exception JavaDoc e) {
952             log.error("Failed to add " + siteDir.getPath()
953                 + " as a resource base. Site specific resources such as icons may not work.");
954         }
955         
956         // Add the extension store panels.
957
// categories are Installed, Updateable, Beta, Remote Access, AccessControl, Resources, UserInterface, Misc, Articles
958
PanelManager.getInstance().addPanel(new DefaultPanel("installed",
959             ConfigureExtensionsForm.EXTENSIONS_TAB_ID,
960             10,
961             "/WEB-INF/jsp/content/extensions/installedExtensionStoreContent.jspf",
962             null,
963             "extensions",
964             false));
965         PanelManager.getInstance().addPanel(new DefaultPanel("updateable",
966             ConfigureExtensionsForm.EXTENSIONS_TAB_ID,
967             20,
968             "/WEB-INF/jsp/content/extensions/updateableExtensionStoreContent.jspf",
969             null,
970             "extensions",
971             false));
972         PanelManager.getInstance().addPanel(new DefaultPanel("beta",
973             ConfigureExtensionsForm.EXTENSIONS_TAB_ID,
974             30,
975             "/WEB-INF/jsp/content/extensions/betaExtensionStoreContent.jspf",
976             null,
977             "extensions",
978             false));
979         PanelManager.getInstance().addPanel(new DefaultPanel("remoteAccess",
980             ConfigureExtensionsForm.EXTENSIONS_TAB_ID,
981             40,
982             "/WEB-INF/jsp/content/extensions/remoteAccessExtensionStoreContent.jspf",
983             null,
984             "extensions",
985             false));
986         PanelManager.getInstance().addPanel(new DefaultPanel("accessControl",
987             ConfigureExtensionsForm.EXTENSIONS_TAB_ID,
988             50,
989             "/WEB-INF/jsp/content/extensions/accessControlExtensionStoreContent.jspf",
990             null,
991             "extensions",
992             false));
993         PanelManager.getInstance().addPanel(new DefaultPanel("resources",
994             ConfigureExtensionsForm.EXTENSIONS_TAB_ID,
995             60,
996             "/WEB-INF/jsp/content/extensions/resourcesExtensionStoreContent.jspf",
997             null,
998             "extensions",
999             false));
1000        PanelManager.getInstance().addPanel(new DefaultPanel("userInterface",
1001            ConfigureExtensionsForm.EXTENSIONS_TAB_ID,
1002            70,
1003            "/WEB-INF/jsp/content/extensions/userInterfaceExtensionStoreContent.jspf",
1004            null,
1005            "extensions",
1006            false));
1007        PanelManager.getInstance().addPanel(new DefaultPanel("misc",
1008            ConfigureExtensionsForm.EXTENSIONS_TAB_ID,
1009            80,
1010            "/WEB-INF/jsp/content/extensions/miscExtensionStoreContent.jspf",
1011            null,
1012            "extensions",
1013            false));
1014        PanelManager.getInstance().addPanel(new DefaultPanel("articles",
1015            ConfigureExtensionsForm.EXTENSIONS_TAB_ID,
1016            90,
1017            "/WEB-INF/jsp/content/extensions/articlesExtensionStoreContent.jspf",
1018            null,
1019            "extensions",
1020            false));
1021
1022        
1023    }
1024
1025    /**
1026     * @param path
1027     * @throws ServletException
1028     */

1029    public void addStrutsConfig(String JavaDoc path) throws ServletException JavaDoc {
1030        digester.push(moduleConfig);
1031        if (log.isInfoEnabled())
1032            log.info("Processing plugin struts configuration file " + path + " to moulde config '" + moduleConfig.getPrefix() + "'");
1033        try {
1034            /* If we have already past initialisation stage, then this
1035             * call is a plugin being started at runtime
1036             */

1037            if(pastInitialisation) {
1038                initModuleConfig("", path);
1039                initModuleMessageResources(moduleConfig);
1040                initModuleDataSources(moduleConfig);
1041                initModulePlugIns(moduleConfig);
1042            }
1043            else {
1044                this.parseModuleConfigFile(digester, path);
1045            }
1046        } catch (UnavailableException JavaDoc ue) {
1047            if(log.isInfoEnabled()) {
1048                log.error("Failed to add struts config.", ue);
1049            }
1050        }
1051    }
1052    
1053    /**
1054     * @throws ServletException
1055     */

1056    public void initExtensionStore() throws ServletException JavaDoc {
1057
1058        // Initialise extension store
1059
ExtensionStore store = ExtensionStore.getInstance();
1060
1061        // Initialise store
1062
try {
1063            store.init(ContextHolder.getContext().getApplicationDirectory());
1064        } catch (Exception JavaDoc e) {
1065            log.error("Failed to initialise extension store.", e);
1066            throw new ServletException JavaDoc(e);
1067        }
1068    }
1069
1070    /**
1071     * @throws ServletException
1072     */

1073    public void startExtensions() throws ServletException JavaDoc {
1074
1075        
1076        // Intialise plugins
1077
if ("true".equalsIgnoreCase(System.getProperty("sslexplorer.disableExtensions"))) {
1078            log.warn("Extension manager disabled, extensions wont be started");
1079        } else {
1080            try {
1081                ExtensionStore.getInstance().start();
1082            } catch (ExtensionException ee) {
1083                log.error("Failed to start extension store.", ee);
1084                throw new ServletException JavaDoc("Failed to start extension store.", ee);
1085            }
1086        }
1087    }
1088
1089    /**
1090     *
1091     */

1092    public void stopped() {
1093        if (shuttingDown) {
1094            throw new RuntimeException JavaDoc("Already shutting down.");
1095        }
1096        shuttingDown = true;
1097        fireCoreEvent(new CoreEvent(this, CoreEventConstants.SERVER_STOPPING, null, null));
1098        if (notifier != null && notifier.isStarted()) {
1099            notifier.stop();
1100        }
1101        
1102        // Stop updating rss feeds
1103
FeedManager.getInstance().stopUpdating();
1104
1105        // Close down all user databases
1106
UserDatabaseManager.getInstance().closeAll();
1107
1108        // Stop all extensions
1109
try {
1110            ExtensionStore.getInstance().stop();
1111        } catch (ExtensionException e) {
1112            log.error("Failed to stop extensions.", e);
1113        }
1114
1115        // Stop the database server
1116
if (dbServer != null) {
1117            dbServer.stop();
1118        }
1119
1120        // Fire our last event. Listeners should do as little as possible at
1121
// this stage
1122
fireCoreEvent(new CoreEvent(this, CoreEventConstants.SERVER_STOPPED, null, null));
1123        
1124        shuttingDown = false;
1125    }
1126
1127    /**
1128     * Get if the system is currently shutting down. This will become true as
1129     * soon as {@link #stopped()} has been invoked.
1130     *
1131     * @return shutting down
1132     */

1133    public boolean isShuttingDown() {
1134        return shuttingDown;
1135    }
1136
1137    void checkDevEnvironment() throws ServletException JavaDoc {
1138        devConfig = "true".equalsIgnoreCase(System.getProperty("sslexplorer.useDevConfig", "false"));
1139        File JavaDoc defaultDevConfDir = new File JavaDoc(System.getProperty("user.dir"), "conf");
1140        try {
1141            if (devConfig && ContextHolder.getContext()
1142                            .getConfDirectory()
1143                            .getCanonicalFile()
1144                            .equals(defaultDevConfDir.getCanonicalFile())) {
1145                throw new ServletException JavaDoc("When running in developmenet mode, you may NOT use " + defaultDevConfDir.getAbsolutePath()
1146                    + " as your 'conf' directory. Please specifiy "
1147                    + "a different directory using the --conf=<dir> argument when starting the server.");
1148            }
1149        } catch (IOException JavaDoc ioe) {
1150            throw new ServletException JavaDoc("Failed to determine if incorrect conf directory is being used", ioe);
1151        }
1152    }
1153
1154    public RequestProcessor getRequestProcessor(HttpServletRequest JavaDoc request) throws ServletException JavaDoc {
1155        return getRequestProcessor(getModuleConfig(request));
1156        
1157    }
1158}
Popular Tags