XMPPServer.java 57.7 KB
Newer Older
1 2
/**
 *
3
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
4
 *
5 6 7 8 9 10 11 12 13 14 15
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
16 17
 */

18
package org.jivesoftware.openfire;
19

20
import java.io.BufferedReader;
21 22 23 24
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
25
import java.io.InputStreamReader;
26 27 28 29
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.KeyStore;
30
import java.sql.Connection;
31 32 33 34 35 36 37 38
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
39
import java.util.TimerTask;
40 41
import java.util.concurrent.CopyOnWriteArrayList;

42 43 44
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.jivesoftware.database.DbConnectionManager;
45
import org.jivesoftware.openfire.admin.AdminManager;
46 47
import org.jivesoftware.openfire.audit.AuditManager;
import org.jivesoftware.openfire.audit.spi.AuditManagerImpl;
48
import org.jivesoftware.openfire.clearspace.ClearspaceManager;
49
import org.jivesoftware.openfire.cluster.ClusterManager;
50
import org.jivesoftware.openfire.cluster.NodeID;
51 52 53 54 55
import org.jivesoftware.openfire.commands.AdHocCommandHandler;
import org.jivesoftware.openfire.component.InternalComponentManager;
import org.jivesoftware.openfire.container.AdminConsolePlugin;
import org.jivesoftware.openfire.container.Module;
import org.jivesoftware.openfire.container.PluginManager;
56 57 58 59 60 61 62
import org.jivesoftware.openfire.disco.IQDiscoInfoHandler;
import org.jivesoftware.openfire.disco.IQDiscoItemsHandler;
import org.jivesoftware.openfire.disco.ServerFeaturesProvider;
import org.jivesoftware.openfire.disco.ServerIdentitiesProvider;
import org.jivesoftware.openfire.disco.ServerItemsProvider;
import org.jivesoftware.openfire.disco.UserIdentitiesProvider;
import org.jivesoftware.openfire.disco.UserItemsProvider;
63 64 65
import org.jivesoftware.openfire.filetransfer.DefaultFileTransferManager;
import org.jivesoftware.openfire.filetransfer.FileTransferManager;
import org.jivesoftware.openfire.filetransfer.proxy.FileTransferProxy;
csh's avatar
csh committed
66
import org.jivesoftware.openfire.handler.*;
67
import org.jivesoftware.openfire.lockout.LockOutManager;
68
import org.jivesoftware.openfire.mediaproxy.MediaProxyService;
69
import org.jivesoftware.openfire.muc.MultiUserChatManager;
70 71 72
import org.jivesoftware.openfire.net.MulticastDNSService;
import org.jivesoftware.openfire.net.SSLConfig;
import org.jivesoftware.openfire.net.ServerTrafficCounter;
73 74
import org.jivesoftware.openfire.pep.IQPEPHandler;
import org.jivesoftware.openfire.pep.IQPEPOwnerHandler;
75 76
import org.jivesoftware.openfire.pubsub.PubSubModule;
import org.jivesoftware.openfire.roster.RosterManager;
77
import org.jivesoftware.openfire.session.RemoteSessionLocator;
78 79 80 81 82 83 84
import org.jivesoftware.openfire.spi.ConnectionManagerImpl;
import org.jivesoftware.openfire.spi.PacketDelivererImpl;
import org.jivesoftware.openfire.spi.PacketRouterImpl;
import org.jivesoftware.openfire.spi.PacketTransporterImpl;
import org.jivesoftware.openfire.spi.PresenceManagerImpl;
import org.jivesoftware.openfire.spi.RoutingTableImpl;
import org.jivesoftware.openfire.spi.XMPPServerInfoImpl;
85 86 87 88
import org.jivesoftware.openfire.transport.TransportHandler;
import org.jivesoftware.openfire.update.UpdateManager;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.vcard.VCardManager;
89 90 91 92 93 94
import org.jivesoftware.util.CertificateManager;
import org.jivesoftware.util.InitializationException;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.TaskEngine;
import org.jivesoftware.util.Version;
95
import org.jivesoftware.util.cache.CacheFactory;
96 97
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
98 99 100 101 102
import org.xmpp.packet.JID;

/**
 * The main XMPP server that will load, initialize and start all the server's
 * modules. The server is unique in the JVM and could be obtained by using the
103 104
 * {@link #getInstance()} method.
 * <p>
105 106
 * The loaded modules will be initialized and may access through the server other
 * modules. This means that the only way for a module to locate another module is
107 108 109
 * through the server. The server maintains a list of loaded modules.
 * </p>
 * <p>
110
 * After starting up all the modules the server will load any available plugin.
111 112 113
 * For more information see: {@link org.jivesoftware.openfire.container.PluginManager}.
 * </p>
 * <p>A configuration file keeps the server configuration. This information is required for the
114
 * server to work correctly. The server assumes that the configuration file is named
115
 * <b>openfire.xml</b> and is located in the <b>conf</b> folder. The folder that keeps
116
 * the configuration file must be located under the home folder. The server will try different
117
 * methods to locate the home folder.</p>
118
 * <ol>
119
 * <li><b>system property</b> - The server will use the value defined in the <i>openfireHome</i>
120 121 122
 * system property.</li>
 * <li><b>working folder</b> -  The server will check if there is a <i>conf</i> folder in the
 * working directory. This is the case when running in standalone mode.</li>
123
 * <li><b>openfire_init.xml file</b> - Attempt to load the value from openfire_init.xml which
124
 * must be in the classpath</li>
125 126 127 128 129 130
 * </ol>
 *
 * @author Gaston Dombiak
 */
public class XMPPServer {

131 132
	private static final Logger Log = LoggerFactory.getLogger(XMPPServer.class);

133 134 135
    private static XMPPServer instance;

    private String name;
136
    private String host;
137 138 139
    private Version version;
    private Date startDate;
    private boolean initialized = false;
140
    private boolean started = false;
141
    private NodeID nodeID;
142
    private static final NodeID DEFAULT_NODE_ID = NodeID.getInstance(new byte[0]);
143

144 145
    public static final String EXIT = "exit";

146 147 148
    /**
     * All modules loaded by this server
     */
149
    private Map<Class, Module> modules = new LinkedHashMap<Class, Module>();
150

151 152 153 154 155
    /**
     * Listeners that will be notified when the server has started or is about to be stopped.
     */
    private List<XMPPServerListener> listeners = new CopyOnWriteArrayList<XMPPServerListener>();

156 157 158 159
    /**
     * Location of the home directory. All configuration files should be
     * located here.
     */
160
    private File openfireHome;
161 162 163 164
    private ClassLoader loader;

    private PluginManager pluginManager;
    private InternalComponentManager componentManager;
165
    private RemoteSessionLocator remoteSessionLocator;
166 167 168 169 170 171 172

    /**
     * True if in setup mode
     */
    private boolean setupMode = true;

    private static final String STARTER_CLASSNAME =
173
            "org.jivesoftware.openfire.starter.ServerStarter";
174 175
    private static final String WRAPPER_CLASSNAME =
            "org.tanukisoftware.wrapper.WrapperManager";
176
    private boolean shuttingDown;
Gaston Dombiak's avatar
Gaston Dombiak committed
177
    private XMPPServerInfoImpl xmppServerInfo;
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

    /**
     * Returns a singleton instance of XMPPServer.
     *
     * @return an instance.
     */
    public static XMPPServer getInstance() {
        return instance;
    }

    /**
     * Creates a server and starts it.
     */
    public XMPPServer() {
        // We may only have one instance of the server running on the JVM
        if (instance != null) {
            throw new IllegalStateException("A server is already running");
        }
        instance = this;
        start();
    }

    /**
     * Returns a snapshot of the server's status.
     *
     * @return the server information current at the time of the method call.
     */
    public XMPPServerInfo getServerInfo() {
        if (!initialized) {
            throw new IllegalStateException("Not initialized yet");
        }
Gaston Dombiak's avatar
Gaston Dombiak committed
209
        return xmppServerInfo;
210 211 212 213 214 215 216 217 218 219 220 221
    }

    /**
     * Returns true if the given address is local to the server (managed by this
     * server domain). Return false even if the jid's domain matches a local component's
     * service JID.
     *
     * @param jid the JID to check.
     * @return true if the address is a local address to this server.
     */
    public boolean isLocal(JID jid) {
        boolean local = false;
222
        if (jid != null && name != null && name.equals(jid.getDomain())) {
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
            local = true;
        }
        return local;
    }

    /**
     * Returns true if the given address does not match the local server hostname and does not
     * match a component service JID.
     *
     * @param jid the JID to check.
     * @return true if the given address does not match the local server hostname and does not
     *         match a component service JID.
     */
    public boolean isRemote(JID jid) {
        if (jid != null) {
238
            if (!name.equals(jid.getDomain()) && !componentManager.hasComponent(jid)) {
239 240 241 242 243 244
                return true;
            }
        }
        return false;
    }

Gaston Dombiak's avatar
Gaston Dombiak committed
245 246 247 248 249 250 251
    /**
     * Returns an ID that uniquely identifies this server in a cluster. When not running in cluster mode
     * the returned value is always the same. However, when in cluster mode the value should be set
     * when joining the cluster and must be unique even upon restarts of this node.
     *
     * @return an ID that uniquely identifies this server in a cluster.
     */
252
    public NodeID getNodeID() {
253
        return nodeID == null ? DEFAULT_NODE_ID : nodeID;
Gaston Dombiak's avatar
Gaston Dombiak committed
254 255 256 257 258 259 260 261 262
    }

    /**
     * Sets an ID that uniquely identifies this server in a cluster. When not running in cluster mode
     * the returned value is always the same. However, when in cluster mode the value should be set
     * when joining the cluster and must be unique even upon restarts of this node.
     *
     * @param nodeID an ID that uniquely identifies this server in a cluster or null if not in a cluster.
     */
263
    public void setNodeID(NodeID nodeID) {
Gaston Dombiak's avatar
Gaston Dombiak committed
264 265 266
        this.nodeID = nodeID;
    }

267 268 269 270 271 272 273
    /**
     * Returns true if the given address matches a component service JID.
     *
     * @param jid the JID to check.
     * @return true if the given address matches a component service JID.
     */
    public boolean matchesComponent(JID jid) {
274
        return jid != null && !name.equals(jid.getDomain()) && componentManager.hasComponent(jid);
275 276 277 278 279 280 281 282 283 284 285 286 287
    }

    /**
     * Creates an XMPPAddress local to this server.
     *
     * @param username the user name portion of the id or null to indicate none is needed.
     * @param resource the resource portion of the id or null to indicate none is needed.
     * @return an XMPPAddress for the server.
     */
    public JID createJID(String username, String resource) {
        return new JID(username, name, resource);
    }

288 289 290 291 292 293 294 295 296 297 298 299 300
    /**
     * Creates an XMPPAddress local to this server. The construction of the new JID
     * can be optimized by skipping stringprep operations.
     *
     * @param username the user name portion of the id or null to indicate none is needed.
     * @param resource the resource portion of the id or null to indicate none is needed.
     * @param skipStringprep true if stringprep should not be applied.
     * @return an XMPPAddress for the server.
     */
    public JID createJID(String username, String resource, boolean skipStringprep) {
        return new JID(username, name, resource, skipStringprep);
    }

301 302 303 304 305 306 307
    /**
     * Returns a collection with the JIDs of the server's admins. The collection may include
     * JIDs of local users and users of remote servers.
     *
     * @return a collection with the JIDs of the server's admins.
     */
    public Collection<JID> getAdmins() {
308
        return AdminManager.getInstance().getAdminAccounts();
309 310
    }

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    /**
     * Adds a new server listener that will be notified when the server has been started
     * or is about to be stopped.
     *
     * @param listener the new server listener to add.
     */
    public void addServerListener(XMPPServerListener listener) {
        listeners.add(listener);
    }

    /**
     * Removes a server listener that was being notified when the server was being started
     * or was about to be stopped.
     *
     * @param listener the server listener to remove.
     */
    public void removeServerListener(XMPPServerListener listener) {
        listeners.remove(listener);
    }

331
    private void initialize() throws FileNotFoundException {
332
        locateOpenfire();
333

334 335
        startDate = new Date();

336 337 338 339 340
        try {
            host = InetAddress.getLocalHost().getHostName();
        }
        catch (UnknownHostException ex) {
            Log.warn("Unable to determine local hostname.", ex);
341 342 343
        }
        if (host == null) {
            host = "127.0.0.1";        	
344 345
        }

346
        version = new Version(3, 9, 3, Version.ReleaseStatus.Alpha, -1);
347 348 349 350 351
        if ("true".equals(JiveGlobals.getXMLProperty("setup"))) {
            setupMode = false;
        }

        if (isStandAlone()) {
352
        	Log.info("Registering shutdown hook (standalone mode)");
353
            Runtime.getRuntime().addShutdownHook(new ShutdownHookThread());
354
            TaskEngine.getInstance().schedule(new Terminator(), 1000, 1000);
355 356 357 358
        }

        loader = Thread.currentThread().getContextClassLoader();

359 360 361 362
        try {
            CacheFactory.initialize();
        } catch (InitializationException e) {
            e.printStackTrace();
363
            Log.error(e.getMessage(), e);
364 365
        }

366 367 368 369 370
        JiveGlobals.migrateProperty("xmpp.domain");
        name = JiveGlobals.getProperty("xmpp.domain", host).toLowerCase();

        org.jivesoftware.util.Log.setDebugEnabled(JiveGlobals.getXMLProperty("log.debug.enabled", false));
        
371 372 373 374
        // Update server info
        xmppServerInfo = new XMPPServerInfoImpl(name, host, version, startDate);


375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        initialized = true;
    }

    /**
     * Finish the setup process. Because this method is meant to be called from inside
     * the Admin console plugin, it spawns its own thread to do the work so that the
     * class loader is correct.
     */
    public void finishSetup() {
        if (!setupMode) {
            return;
        }
        // Make sure that setup finished correctly.
        if ("true".equals(JiveGlobals.getXMLProperty("setup"))) {
            // Set the new server domain assigned during the setup process
390
            name = JiveGlobals.getProperty("xmpp.domain").toLowerCase();
Jay Kline's avatar
Jay Kline committed
391
            xmppServerInfo.setXMPPDomain(name);
392

393 394 395 396 397 398 399 400 401
            // Update certificates (if required)
            try {
                // Check if keystore already has certificates for current domain
                KeyStore ksKeys = SSLConfig.getKeyStore();
                boolean dsaFound = CertificateManager.isDSACertificate(ksKeys, name);
                boolean rsaFound = CertificateManager.isRSACertificate(ksKeys, name);

                // No certificates were found so create new self-signed certificates
                if (!dsaFound) {
Matt Tucker's avatar
Matt Tucker committed
402 403
                    CertificateManager.createDSACert(ksKeys, SSLConfig.getKeyPassword(),
                            name + "_dsa", "cn=" + name, "cn=" + name, "*." + name);
404 405
                }
                if (!rsaFound) {
Matt Tucker's avatar
Matt Tucker committed
406 407
                    CertificateManager.createRSACert(ksKeys, SSLConfig.getKeyPassword(),
                            name + "_rsa", "cn=" + name, "cn=" + name, "*." + name);
408 409 410 411 412 413 414 415 416 417
                }
                // Save new certificates into the key store
                if (!dsaFound || !rsaFound) {
                    SSLConfig.saveStores();
                }

            } catch (Exception e) {
                Log.error("Error generating self-signed certificates", e);
            }

418 419 420
            // Initialize list of admins now (before we restart Jetty)
            AdminManager.getInstance().getAdminAccounts();

421
            Thread finishSetup = new Thread() {
422 423
                @Override
				public void run() {
424 425
                    try {
                        if (isStandAlone()) {
426 427 428 429 430 431 432
                            // Always restart the HTTP server manager. This covers the case
                            // of changing the ports, as well as generating self-signed certificates.
                        
                            // Wait a short period before shutting down the admin console.
                            // Otherwise, the page that requested the setup finish won't
                            // render properly!
                            Thread.sleep(1000);
Matt Tucker's avatar
Matt Tucker committed
433 434 435
                            ((AdminConsolePlugin) pluginManager.getPlugin("admin")).restart();
//                            ((AdminConsolePlugin) pluginManager.getPlugin("admin")).shutdown();
//                            ((AdminConsolePlugin) pluginManager.getPlugin("admin")).startup();
436 437 438 439 440 441 442 443 444 445 446 447 448
                        }

                        verifyDataSource();
                        // First load all the modules so that modules may access other modules while
                        // being initialized
                        loadModules();
                        // Initize all the modules
                        initModules();
                        // Start all the modules
                        startModules();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
449
                        Log.error(e.getMessage(), e);
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
                        shutdownServer();
                    }
                }
            };
            // Use the correct class loader.
            finishSetup.setContextClassLoader(loader);
            finishSetup.start();
            // We can now safely indicate that setup has finished
            setupMode = false;
        }
    }

    public void start() {
        try {
            initialize();

466
            // Create PluginManager now (but don't start it) so that modules may use it
467
            File pluginDir = new File(openfireHome, "plugins");
468 469
            pluginManager = new PluginManager(pluginDir);

470 471 472 473 474 475 476 477 478 479 480
            // If the server has already been setup then we can start all the server's modules
            if (!setupMode) {
                verifyDataSource();
                // First load all the modules so that modules may access other modules while
                // being initialized
                loadModules();
                // Initize all the modules
                initModules();
                // Start all the modules
                startModules();
            }
481 482 483
            // Initialize statistics
            ServerTrafficCounter.initStatistics();

484 485 486 487
            // Load plugins (when in setup mode only the admin console will be loaded)
            pluginManager.start();

            // Log that the server has been started
Gaston Dombiak's avatar
Gaston Dombiak committed
488 489
            String startupBanner = LocaleUtils.getLocalizedString("short.title") + " " + version.getVersionString() +
                    " [" + JiveGlobals.formatDateTime(new Date()) + "]";
490 491 492
            Log.info(startupBanner);
            System.out.println(startupBanner);

493 494
            started = true;
            
495 496 497 498
            // Notify server listeners that the server has been started
            for (XMPPServerListener listener : listeners) {
                listener.serverStarted();
            }
499 500 501
        }
        catch (Exception e) {
            e.printStackTrace();
502
            Log.error(e.getMessage(), e);
503 504 505 506 507 508 509 510 511 512 513 514 515 516
            System.out.println(LocaleUtils.getLocalizedString("startup.error"));
            shutdownServer();
        }
    }

    private void loadModules() {
        // Load boot modules
        loadModule(RoutingTableImpl.class.getName());
        loadModule(AuditManagerImpl.class.getName());
        loadModule(RosterManager.class.getName());
        loadModule(PrivateStorage.class.getName());
        // Load core modules
        loadModule(PresenceManagerImpl.class.getName());
        loadModule(SessionManager.class.getName());
517
        loadModule(PacketRouterImpl.class.getName());
518 519 520
        loadModule(IQRouter.class.getName());
        loadModule(MessageRouter.class.getName());
        loadModule(PresenceRouter.class.getName());
521
        loadModule(MulticastRouter.class.getName());
522 523 524 525 526
        loadModule(PacketTransporterImpl.class.getName());
        loadModule(PacketDelivererImpl.class.getName());
        loadModule(TransportHandler.class.getName());
        loadModule(OfflineMessageStrategy.class.getName());
        loadModule(OfflineMessageStore.class.getName());
527
        loadModule(VCardManager.class.getName());
528 529 530 531
        // Load standard modules
        loadModule(IQBindHandler.class.getName());
        loadModule(IQSessionEstablishmentHandler.class.getName());
        loadModule(IQAuthHandler.class.getName());
532
        loadModule(IQPingHandler.class.getName());
533 534 535 536
        loadModule(IQPrivateHandler.class.getName());
        loadModule(IQRegisterHandler.class.getName());
        loadModule(IQRosterHandler.class.getName());
        loadModule(IQTimeHandler.class.getName());
csh's avatar
csh committed
537
        loadModule(IQEntityTimeHandler.class.getName());
538 539 540 541 542 543
        loadModule(IQvCardHandler.class.getName());
        loadModule(IQVersionHandler.class.getName());
        loadModule(IQLastActivityHandler.class.getName());
        loadModule(PresenceSubscribeHandler.class.getName());
        loadModule(PresenceUpdateHandler.class.getName());
        loadModule(IQOfflineMessagesHandler.class.getName());
544 545
        loadModule(IQPEPHandler.class.getName());
        loadModule(IQPEPOwnerHandler.class.getName());
546 547 548
        loadModule(MulticastDNSService.class.getName());
        loadModule(IQSharedGroupHandler.class.getName());
        loadModule(AdHocCommandHandler.class.getName());
549
        loadModule(IQPrivacyHandler.class.getName());
550
        loadModule(DefaultFileTransferManager.class.getName());
551
        loadModule(FileTransferProxy.class.getName());
552
        loadModule(MediaProxyService.class.getName());
553
        loadModule(PubSubModule.class.getName());
554 555
        loadModule(IQDiscoInfoHandler.class.getName());
        loadModule(IQDiscoItemsHandler.class.getName());
556
        loadModule(UpdateManager.class.getName());
557
        loadModule(FlashCrossDomainHandler.class.getName());
558
        loadModule(InternalComponentManager.class.getName());
559
        loadModule(MultiUserChatManager.class.getName());
560
        loadModule(ClearspaceManager.class.getName());
561 562
        loadModule(IQMessageCarbonsHandler.class.getName());

563 564 565
        // Load this module always last since we don't want to start listening for clients
        // before the rest of the modules have been started
        loadModule(ConnectionManagerImpl.class.getName());
566 567
        // Keep a reference to the internal component manager
        componentManager = getComponentManager();
568 569 570 571 572 573 574 575 576 577
    }

    /**
     * Loads a module.
     *
     * @param module the name of the class that implements the Module interface.
     */
    private void loadModule(String module) {
        try {
            Class modClass = loader.loadClass(module);
578
            Module mod = (Module) modClass.newInstance();
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
            this.modules.put(modClass, mod);
        }
        catch (Exception e) {
            e.printStackTrace();
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
    }

    private void initModules() {
        for (Module module : modules.values()) {
            boolean isInitialized = false;
            try {
                module.initialize(this);
                isInitialized = true;
            }
            catch (Exception e) {
                e.printStackTrace();
                // Remove the failed initialized module
                this.modules.remove(module.getClass());
                if (isInitialized) {
                    module.stop();
                    module.destroy();
                }
                Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            }
        }
    }

    /**
     * <p>Following the loading and initialization of all the modules
     * this method is called to iterate through the known modules and
     * start them.</p>
     */
    private void startModules() {
        for (Module module : modules.values()) {
            boolean started = false;
            try {
                module.start();
            }
            catch (Exception e) {
                if (started && module != null) {
                    module.stop();
                    module.destroy();
                }
                Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            }
        }
    }

    /**
     * Restarts the server and all it's modules only if the server is restartable. Otherwise do
     * nothing.
     */
    public void restart() {
        if (isStandAlone() && isRestartable()) {
            try {
                Class wrapperClass = Class.forName(WRAPPER_CLASSNAME);
636 637
                Method restartMethod = wrapperClass.getMethod("restart", (Class []) null);
                restartMethod.invoke(null, (Object []) null);
638 639 640 641 642 643 644
            }
            catch (Exception e) {
                Log.error("Could not restart container", e);
            }
        }
    }

645
    /**
646 647 648 649
     * Restarts the HTTP server only when running in stand alone mode. The restart
     * process will be done in another thread that will wait 1 second before doing
     * the actual restart. The delay will give time to the page that requested the
     * restart to fully render its content.
650 651 652
     */
    public void restartHTTPServer() {
        Thread restartThread = new Thread() {
653 654
            @Override
			public void run() {
655 656 657 658 659 660 661 662
                if (isStandAlone()) {
                    // Restart the HTTP server manager. This covers the case
                    // of changing the ports, as well as generating self-signed certificates.

                    // Wait a short period before shutting down the admin console.
                    // Otherwise, this page won't render properly!
                    try {
                        Thread.sleep(1000);
663 664
                        ((AdminConsolePlugin) pluginManager.getPlugin("admin")).shutdown();
                        ((AdminConsolePlugin) pluginManager.getPlugin("admin")).startup();
665 666 667 668 669 670 671 672 673 674
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        restartThread.setContextClassLoader(loader);
        restartThread.start();
    }

675 676 677 678 679
    /**
     * Stops the server only if running in standalone mode. Do nothing if the server is running
     * inside of another server.
     */
    public void stop() {
680
    	Log.info("Initiating shutdown ...");
681 682 683 684 685 686
        // Only do a system exit if we're running standalone
        if (isStandAlone()) {
            // if we're in a wrapper, we have to tell the wrapper to shut us down
            if (isRestartable()) {
                try {
                    Class wrapperClass = Class.forName(WRAPPER_CLASSNAME);
687 688
                    Method stopMethod = wrapperClass.getMethod("stop", Integer.TYPE);
                    stopMethod.invoke(null, 0);
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
                }
                catch (Exception e) {
                    Log.error("Could not stop container", e);
                }
            }
            else {
                shutdownServer();
                Thread shutdownThread = new ShutdownThread();
                shutdownThread.setDaemon(true);
                shutdownThread.start();
            }
        }
        else {
            // Close listening socket no matter what the condition is in order to be able
            // to be restartable inside a container.
            shutdownServer();
        }
    }

    public boolean isSetupMode() {
        return setupMode;
    }

    public boolean isRestartable() {
713
        boolean restartable;
714 715 716 717 718 719 720 721 722 723 724
        try {
            restartable = Class.forName(WRAPPER_CLASSNAME) != null;
        }
        catch (ClassNotFoundException e) {
            restartable = false;
        }
        return restartable;
    }

    /**
     * Returns if the server is running in standalone mode. We consider that it's running in
725
     * standalone if the "org.jivesoftware.openfire.starter.ServerStarter" class is present in the
726 727 728 729 730
     * system.
     *
     * @return true if the server is running in standalone mode.
     */
    public boolean isStandAlone() {
731
        boolean standalone;
732 733 734 735 736 737 738 739 740 741 742 743 744
        try {
            standalone = Class.forName(STARTER_CLASSNAME) != null;
        }
        catch (ClassNotFoundException e) {
            standalone = false;
        }
        return standalone;
    }

    /**
     * Verify that the database is accessible.
     */
    private void verifyDataSource() {
745 746 747
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
748
        try {
749 750 751
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement("SELECT count(*) FROM ofID");
            rs = pstmt.executeQuery();
752 753 754 755 756 757 758 759 760 761
            rs.next();
        }
        catch (Exception e) {
            System.err.println("Database setup or configuration error: " +
                    "Please verify your database settings and check the " +
                    "logs/error.log file for detailed error messages.");
            Log.error("Database could not be accessed", e);
            throw new IllegalArgumentException(e);
        }
        finally {
762
            DbConnectionManager.closeConnection(rs, pstmt, con);
763 764 765 766
        }
    }

    /**
767 768
     * Verifies that the given home guess is a real Openfire home directory.
     * We do the verification by checking for the Openfire config file in
769 770
     * the config dir of jiveHome.
     *
771
     * @param homeGuess a guess at the path to the home directory.
772 773 774 775
     * @param jiveConfigName the name of the config file to check.
     * @return a file pointing to the home directory or null if the
     *         home directory guess was wrong.
     * @throws java.io.FileNotFoundException if there was a problem with the home
776
     *                                       directory provided
777 778
     */
    private File verifyHome(String homeGuess, String jiveConfigName) throws FileNotFoundException {
779 780
        File openfireHome = new File(homeGuess);
        File configFile = new File(openfireHome, jiveConfigName);
781
        if (!configFile.exists()) {
782 783
            throw new FileNotFoundException();
        }
784 785
        else {
            try {
786
                return new File(openfireHome.getCanonicalPath());
787 788 789 790
            }
            catch (Exception ex) {
                throw new FileNotFoundException();
            }
791 792 793 794 795 796 797 798
        }
    }

    /**
     * <p>Retrieve the jive home for the container.</p>
     *
     * @throws FileNotFoundException If jiveHome could not be located
     */
799 800 801 802 803
    private void locateOpenfire() throws FileNotFoundException {
        String jiveConfigName = "conf" + File.separator + "openfire.xml";
        // First, try to load it openfireHome as a system property.
        if (openfireHome == null) {
            String homeProperty = System.getProperty("openfireHome");
804 805
            try {
                if (homeProperty != null) {
806
                    openfireHome = verifyHome(homeProperty, jiveConfigName);
807 808 809 810 811 812 813 814 815 816
                }
            }
            catch (FileNotFoundException fe) {
                // Ignore.
            }
        }

        // If we still don't have home, let's assume this is standalone
        // and just look for home in a standard sub-dir location and verify
        // by looking for the config file
817
        if (openfireHome == null) {
818
            try {
819
                openfireHome = verifyHome("..", jiveConfigName).getCanonicalFile();
820 821 822 823 824 825 826 827 828 829
            }
            catch (FileNotFoundException fe) {
                // Ignore.
            }
            catch (IOException ie) {
                // Ignore.
            }
        }

        // If home is still null, no outside process has set it and
830
        // we have to attempt to load the value from openfire_init.xml,
831
        // which must be in the classpath.
832
        if (openfireHome == null) {
833 834
            InputStream in = null;
            try {
835
                in = getClass().getResourceAsStream("/openfire_init.xml");
836 837 838 839 840 841
                if (in != null) {
                    SAXReader reader = new SAXReader();
                    Document doc = reader.read(in);
                    String path = doc.getRootElement().getText();
                    try {
                        if (path != null) {
842
                            openfireHome = verifyHome(path, jiveConfigName);
843 844 845 846 847 848 849 850
                        }
                    }
                    catch (FileNotFoundException fe) {
                        fe.printStackTrace();
                    }
                }
            }
            catch (Exception e) {
851
                System.err.println("Error loading openfire_init.xml to find home.");
852 853 854
                e.printStackTrace();
            }
            finally {
855 856 857 858 859
                try {
                    if (in != null) {
                        in.close();
                    }
                }
860 861 862 863 864 865 866
                catch (Exception e) {
                    System.err.println("Could not close open connection");
                    e.printStackTrace();
                }
            }
        }

867
        if (openfireHome == null) {
868 869 870 871 872
            System.err.println("Could not locate home");
            throw new FileNotFoundException();
        }
        else {
            // Set the home directory for the config file
873
            JiveGlobals.setHomeDirectory(openfireHome.toString());
874 875 876 877 878
            // Set the name of the config file
            JiveGlobals.setConfigName(jiveConfigName);
        }
    }

879 880 881 882 883 884 885
    /**
     * This timer task is used to monitor the System input stream
     * for a "terminate" command from the launcher (or the console). 
     * This allows for a graceful shutdown when Openfire is started 
     * via the launcher, especially in Windows.
     */
    private class Terminator extends TimerTask {
886
    	private BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
887 888 889 890 891 892 893 894 895 896 897 898 899
    	public void run() {
        	try { 
        		if (stdin.ready()) {
            		if (EXIT.equalsIgnoreCase(stdin.readLine())) {
            			System.exit(0); // invokes shutdown hook(s)
            		}
        		}
        	} catch (IOException ioe) {
        		Log.error("Error reading console input", ioe);
        	}
    	}
    }
    
900 901 902 903 904 905 906 907
    /**
     * <p>A thread to ensure the server shuts down no matter what.</p>
     * <p>Spawned when stop() is called in standalone mode, we wait a few
     * seconds then call system exit().</p>
     *
     * @author Iain Shigeoka
     */
    private class ShutdownHookThread extends Thread {
908

909 910 911
        /**
         * <p>Logs the server shutdown.</p>
         */
912 913
        @Override
		public void run() {
914 915 916 917 918 919 920 921 922 923 924 925 926 927
            shutdownServer();
            Log.info("Server halted");
            System.err.println("Server halted");
        }
    }

    /**
     * <p>A thread to ensure the server shuts down no matter what.</p>
     * <p>Spawned when stop() is called in standalone mode, we wait a few
     * seconds then call system exit().</p>
     *
     * @author Iain Shigeoka
     */
    private class ShutdownThread extends Thread {
928

929 930 931
        /**
         * <p>Shuts down the JVM after a 5 second delay.</p>
         */
932 933
        @Override
		public void run() {
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
            try {
                Thread.sleep(5000);
                // No matter what, we make sure it's dead
                System.exit(0);
            }
            catch (InterruptedException e) {
                // Ignore.
            }

        }
    }

    /**
     * Makes a best effort attempt to shutdown the server
     */
    private void shutdownServer() {
950
        shuttingDown = true;
951
        ClusterManager.shutdown();
952 953
        // Notify server listeners that the server is about to be stopped
        for (XMPPServerListener listener : listeners) {
954 955 956 957 958
        	try {
        		listener.serverStopping();
        	} catch (Exception ex) {
        		Log.error("Exception during listener shutdown", ex);
        	}
959
        }
960 961 962 963
        // If we don't have modules then the server has already been shutdown
        if (modules.isEmpty()) {
            return;
        }
964
    	Log.info("Shutting down " + modules.size() + " modules ...");
965 966
        // Get all modules and stop and destroy them
        for (Module module : modules.values()) {
967 968 969 970 971 972
        	try {
	            module.stop();
	            module.destroy();
        	} catch (Exception ex) {
        		Log.error("Exception during module shutdown", ex);
        	}
973 974
        }
        // Stop all plugins
975
    	Log.info("Shutting down plugins ...");
976
        if (pluginManager != null) {
977 978 979 980 981
        	try {
        		pluginManager.shutdown();
        	} catch (Exception ex) {
        		Log.error("Exception during plugin shutdown", ex);
        	}
982
        }
983
        modules.clear();
984
        // Stop the Db connection manager.
985 986 987 988 989
        try {	
        	DbConnectionManager.destroyConnectionProvider();
        } catch (Exception ex) {
    		Log.error("Exception during DB shutdown", ex);
        }
990 991 992 993

        // Shutdown the task engine.
        TaskEngine.getInstance().shutdown();

994
        // hack to allow safe stopping
995
        Log.info("Openfire stopped");
996
    }
997
    
998 999 1000 1001 1002 1003 1004 1005 1006
    /**
     * Returns true if the server is being shutdown.
     *
     * @return true if the server is being shutdown.
     */
    public boolean isShuttingDown() {
        return shuttingDown;
    }

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    /**
     * Returns the <code>ConnectionManager</code> registered with this server. The
     * <code>ConnectionManager</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>ConnectionManager</code> registered with this server.
     */
    public ConnectionManager getConnectionManager() {
        return (ConnectionManager) modules.get(ConnectionManagerImpl.class);
    }

    /**
     * Returns the <code>RoutingTable</code> registered with this server. The
     * <code>RoutingTable</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>RoutingTable</code> registered with this server.
     */
    public RoutingTable getRoutingTable() {
        return (RoutingTable) modules.get(RoutingTableImpl.class);
    }

    /**
     * Returns the <code>PacketDeliverer</code> registered with this server. The
     * <code>PacketDeliverer</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>PacketDeliverer</code> registered with this server.
     */
    public PacketDeliverer getPacketDeliverer() {
        return (PacketDeliverer) modules.get(PacketDelivererImpl.class);
    }

    /**
     * Returns the <code>RosterManager</code> registered with this server. The
     * <code>RosterManager</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>RosterManager</code> registered with this server.
     */
    public RosterManager getRosterManager() {
        return (RosterManager) modules.get(RosterManager.class);
    }

    /**
     * Returns the <code>PresenceManager</code> registered with this server. The
     * <code>PresenceManager</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>PresenceManager</code> registered with this server.
     */
    public PresenceManager getPresenceManager() {
        return (PresenceManager) modules.get(PresenceManagerImpl.class);
    }

    /**
     * Returns the <code>OfflineMessageStore</code> registered with this server. The
     * <code>OfflineMessageStore</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>OfflineMessageStore</code> registered with this server.
     */
    public OfflineMessageStore getOfflineMessageStore() {
        return (OfflineMessageStore) modules.get(OfflineMessageStore.class);
    }

    /**
     * Returns the <code>OfflineMessageStrategy</code> registered with this server. The
     * <code>OfflineMessageStrategy</code> was registered with the server as a module while starting
     * up the server.
     *
     * @return the <code>OfflineMessageStrategy</code> registered with this server.
     */
    public OfflineMessageStrategy getOfflineMessageStrategy() {
1081
        return (OfflineMessageStrategy) modules.get(OfflineMessageStrategy.class);
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
    }

    /**
     * Returns the <code>PacketRouter</code> registered with this server. The
     * <code>PacketRouter</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>PacketRouter</code> registered with this server.
     */
    public PacketRouter getPacketRouter() {
1092
        return (PacketRouter) modules.get(PacketRouterImpl.class);
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    }

    /**
     * Returns the <code>IQRegisterHandler</code> registered with this server. The
     * <code>IQRegisterHandler</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>IQRegisterHandler</code> registered with this server.
     */
    public IQRegisterHandler getIQRegisterHandler() {
1103
        return (IQRegisterHandler) modules.get(IQRegisterHandler.class);
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
    }

    /**
     * Returns the <code>IQAuthHandler</code> registered with this server. The
     * <code>IQAuthHandler</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>IQAuthHandler</code> registered with this server.
     */
    public IQAuthHandler getIQAuthHandler() {
1114
        return (IQAuthHandler) modules.get(IQAuthHandler.class);
1115
    }
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
    
    /**
     * Returns the <code>IQPEPHandler</code> registered with this server. The
     * <code>IQPEPHandler</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>IQPEPHandler</code> registered with this server.
     */
    public IQPEPHandler getIQPEPHandler() {
        return (IQPEPHandler) modules.get(IQPEPHandler.class);
    }
1127 1128 1129 1130 1131 1132 1133 1134 1135

    /**
     * Returns the <code>PluginManager</code> instance registered with this server.
     *
     * @return the PluginManager instance.
     */
    public PluginManager getPluginManager() {
        return pluginManager;
    }
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

    /**
     * Returns the <code>PubSubModule</code> registered with this server. The
     * <code>PubSubModule</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>PubSubModule</code> registered with this server.
     */
    public PubSubModule getPubSubModule() {
        return (PubSubModule) modules.get(PubSubModule.class);
    }
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156

    /**
     * Returns a list with all the modules registered with the server that inherit from IQHandler.
     *
     * @return a list with all the modules registered with the server that inherit from IQHandler.
     */
    public List<IQHandler> getIQHandlers() {
        List<IQHandler> answer = new ArrayList<IQHandler>();
        for (Module module : modules.values()) {
            if (module instanceof IQHandler) {
1157
                answer.add((IQHandler) module);
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
            }
        }
        return answer;
    }

    /**
     * Returns the <code>SessionManager</code> registered with this server. The
     * <code>SessionManager</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>SessionManager</code> registered with this server.
     */
    public SessionManager getSessionManager() {
        return (SessionManager) modules.get(SessionManager.class);
    }

    /**
     * Returns the <code>TransportHandler</code> registered with this server. The
     * <code>TransportHandler</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>TransportHandler</code> registered with this server.
     */
    public TransportHandler getTransportHandler() {
        return (TransportHandler) modules.get(TransportHandler.class);
    }

    /**
     * Returns the <code>PresenceUpdateHandler</code> registered with this server. The
     * <code>PresenceUpdateHandler</code> was registered with the server as a module while starting
     * up the server.
     *
     * @return the <code>PresenceUpdateHandler</code> registered with this server.
     */
    public PresenceUpdateHandler getPresenceUpdateHandler() {
        return (PresenceUpdateHandler) modules.get(PresenceUpdateHandler.class);
    }

    /**
     * Returns the <code>PresenceSubscribeHandler</code> registered with this server. The
     * <code>PresenceSubscribeHandler</code> was registered with the server as a module while
     * starting up the server.
     *
     * @return the <code>PresenceSubscribeHandler</code> registered with this server.
     */
    public PresenceSubscribeHandler getPresenceSubscribeHandler() {
        return (PresenceSubscribeHandler) modules.get(PresenceSubscribeHandler.class);
    }

    /**
     * Returns the <code>IQRouter</code> registered with this server. The
     * <code>IQRouter</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>IQRouter</code> registered with this server.
     */
    public IQRouter getIQRouter() {
        return (IQRouter) modules.get(IQRouter.class);
    }

    /**
     * Returns the <code>MessageRouter</code> registered with this server. The
     * <code>MessageRouter</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>MessageRouter</code> registered with this server.
     */
    public MessageRouter getMessageRouter() {
        return (MessageRouter) modules.get(MessageRouter.class);
    }

    /**
     * Returns the <code>PresenceRouter</code> registered with this server. The
     * <code>PresenceRouter</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>PresenceRouter</code> registered with this server.
     */
    public PresenceRouter getPresenceRouter() {
        return (PresenceRouter) modules.get(PresenceRouter.class);
    }

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
    /**
     * Returns the <code>MulticastRouter</code> registered with this server. The
     * <code>MulticastRouter</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>MulticastRouter</code> registered with this server.
     */
    public MulticastRouter getMulticastRouter() {
        return (MulticastRouter) modules.get(MulticastRouter.class);
    }

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
    /**
     * Returns the <code>UserManager</code> registered with this server. The
     * <code>UserManager</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>UserManager</code> registered with this server.
     */
    public UserManager getUserManager() {
        return UserManager.getInstance();
    }

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    /**
     * Returns the <code>LockOutManager</code> registered with this server.  The
     * <code>LockOutManager</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>LockOutManager</code> registered with this server.
     */
    public LockOutManager getLockOutManager() {
        return LockOutManager.getInstance();
    }

1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
    /**
     * Returns the <code>UpdateManager</code> registered with this server. The
     * <code>UpdateManager</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>UpdateManager</code> registered with this server.
     */
    public UpdateManager getUpdateManager() {
        return (UpdateManager) modules.get(UpdateManager.class);
    }

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    /**
     * Returns the <code>AuditManager</code> registered with this server. The
     * <code>AuditManager</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>AuditManager</code> registered with this server.
     */
    public AuditManager getAuditManager() {
        return (AuditManager) modules.get(AuditManagerImpl.class);
    }

    /**
     * Returns a list with all the modules that provide "discoverable" features.
     *
     * @return a list with all the modules that provide "discoverable" features.
     */
    public List<ServerFeaturesProvider> getServerFeaturesProviders() {
        List<ServerFeaturesProvider> answer = new ArrayList<ServerFeaturesProvider>();
        for (Module module : modules.values()) {
            if (module instanceof ServerFeaturesProvider) {
                answer.add((ServerFeaturesProvider) module);
            }
        }
        return answer;
    }
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
 
    /**
     * Returns a list with all the modules that provide "discoverable" identities.
     *
     * @return a list with all the modules that provide "discoverable" identities.
     */
    public List<ServerIdentitiesProvider> getServerIdentitiesProviders() {
        List<ServerIdentitiesProvider> answer = new ArrayList<ServerIdentitiesProvider>();
        for (Module module : modules.values()) {
            if (module instanceof ServerIdentitiesProvider) {
                answer.add((ServerIdentitiesProvider) module);
            }
        }
        return answer;
    }
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340

    /**
     * Returns a list with all the modules that provide "discoverable" items associated with
     * the server.
     *
     * @return a list with all the modules that provide "discoverable" items associated with
     *         the server.
     */
    public List<ServerItemsProvider> getServerItemsProviders() {
        List<ServerItemsProvider> answer = new ArrayList<ServerItemsProvider>();
        for (Module module : modules.values()) {
            if (module instanceof ServerItemsProvider) {
                answer.add((ServerItemsProvider) module);
            }
        }
        return answer;
    }
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
    
    /**
     * Returns a list with all the modules that provide "discoverable" user identities.
     *
     * @return a list with all the modules that provide "discoverable" user identities.
     */
    public List<UserIdentitiesProvider> getUserIdentitiesProviders() {
        List<UserIdentitiesProvider> answer = new ArrayList<UserIdentitiesProvider>();
        for (Module module : modules.values()) {
            if (module instanceof UserIdentitiesProvider) {
                answer.add((UserIdentitiesProvider) module);
            }
        }
        return answer;
    }

    /**
     * Returns a list with all the modules that provide "discoverable" items associated with
     * users.
     *
     * @return a list with all the modules that provide "discoverable" items associated with
     *         users.
     */
    public List<UserItemsProvider> getUserItemsProviders() {
        List<UserItemsProvider> answer = new ArrayList<UserItemsProvider>();
        for (Module module : modules.values()) {
            if (module instanceof UserItemsProvider) {
                answer.add((UserItemsProvider) module);
            }
        }
        return answer;
    }
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407

    /**
     * Returns the <code>IQDiscoInfoHandler</code> registered with this server. The
     * <code>IQDiscoInfoHandler</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>IQDiscoInfoHandler</code> registered with this server.
     */
    public IQDiscoInfoHandler getIQDiscoInfoHandler() {
        return (IQDiscoInfoHandler) modules.get(IQDiscoInfoHandler.class);
    }

    /**
     * Returns the <code>IQDiscoItemsHandler</code> registered with this server. The
     * <code>IQDiscoItemsHandler</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>IQDiscoItemsHandler</code> registered with this server.
     */
    public IQDiscoItemsHandler getIQDiscoItemsHandler() {
        return (IQDiscoItemsHandler) modules.get(IQDiscoItemsHandler.class);
    }

    /**
     * Returns the <code>PrivateStorage</code> registered with this server. The
     * <code>PrivateStorage</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>PrivateStorage</code> registered with this server.
     */
    public PrivateStorage getPrivateStorage() {
        return (PrivateStorage) modules.get(PrivateStorage.class);
    }

    /**
1408 1409
     * Returns the <code>MultiUserChatManager</code> registered with this server. The
     * <code>MultiUserChatManager</code> was registered with the server as a module while starting up
1410 1411
     * the server.
     *
1412
     * @return the <code>MultiUserChatManager</code> registered with this server.
1413
     */
1414 1415
    public MultiUserChatManager getMultiUserChatManager() {
        return (MultiUserChatManager) modules.get(MultiUserChatManager.class);
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    }

    /**
     * Returns the <code>AdHocCommandHandler</code> registered with this server. The
     * <code>AdHocCommandHandler</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>AdHocCommandHandler</code> registered with this server.
     */
    public AdHocCommandHandler getAdHocCommandHandler() {
        return (AdHocCommandHandler) modules.get(AdHocCommandHandler.class);
    }
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438

    /**
     * Returns the <code>FileTransferProxy</code> registered with this server. The
     * <code>FileTransferProxy</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>FileTransferProxy</code> registered with this server.
     */
    public FileTransferProxy getFileTransferProxy() {
        return (FileTransferProxy) modules.get(FileTransferProxy.class);
    }
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449

    /**
     * Returns the <code>FileTransferManager</code> registered with this server. The
     * <code>FileTransferManager</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>FileTransferProxy</code> registered with this server.
     */
    public FileTransferManager getFileTransferManager() {
        return (FileTransferManager) modules.get(DefaultFileTransferManager.class);
    }
1450

1451 1452 1453 1454 1455
    /**
     * Returns the <code>MediaProxyService</code> registered with this server. The
     * <code>MediaProxyService</code> was registered with the server as a module while starting up
     * the server.
     *
1456
     * @return the <code>MediaProxyService</code> registered with this server.
1457 1458 1459 1460 1461
     */
    public MediaProxyService getMediaProxyService() {
        return (MediaProxyService) modules.get(MediaProxyService.class);
    }

1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
    /**
     * Returns the <code>FlashCrossDomainHandler</code> registered with this server. The
     * <code>FlashCrossDomainHandler</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>FlashCrossDomainHandler</code> registered with this server.
     */
    public FlashCrossDomainHandler getFlashCrossDomainHandler() {
        return (FlashCrossDomainHandler) modules.get(FlashCrossDomainHandler.class);
    }

1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
    /**
     * Returns the <code>VCardManager</code> registered with this server. The
     * <code>VCardManager</code> was registered with the server as a module while starting up
     * the server.
     * @return the <code>VCardManager</code> registered with this server.
     */
    public VCardManager getVCardManager() {
        return VCardManager.getInstance();
    }

1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
    /**
     * Returns the <code>InternalComponentManager</code> registered with this server. The
     * <code>InternalComponentManager</code> was registered with the server as a module while starting up
     * the server.
     *
     * @return the <code>InternalComponentManager</code> registered with this server.
     */
    private InternalComponentManager getComponentManager() {
        return (InternalComponentManager) modules.get(InternalComponentManager.class);
    }

1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
    /**
     * Returns the locator to use to find sessions hosted in other cluster nodes. When not running
     * in a cluster a <tt>null</tt> value is returned.
     *
     * @return the locator to use to find sessions hosted in other cluster nodes.
     */
    public RemoteSessionLocator getRemoteSessionLocator() {
        return remoteSessionLocator;
    }

    /**
     * Sets the locator to use to find sessions hosted in other cluster nodes. When not running
     * in a cluster set a <tt>null</tt> value.
     *
     * @param remoteSessionLocator the locator to use to find sessions hosted in other cluster nodes.
     */
    public void setRemoteSessionLocator(RemoteSessionLocator remoteSessionLocator) {
        this.remoteSessionLocator = remoteSessionLocator;
    }
1513 1514 1515 1516 1517 1518 1519 1520 1521

    /**
     * Returns whether or not the server has been started.
     * 
     * @return whether or not the server has been started.
     */
    public boolean isStarted() {
        return started;
    }
1522
}