⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 torqueinstance.java

📁 torque服务器源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package org.apache.torque;/* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright *    notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright *    notice, this list of conditions and the following disclaimer in *    the documentation and/or other materials provided with the *    distribution. * * 3. The end-user documentation included with the redistribution, *    if any, must include the following acknowledgment: *       "This product includes software developed by the *        Apache Software Foundation (http://www.apache.org/)." *    Alternately, this acknowledgment may appear in the software itself, *    if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and *    "Apache Turbine" must not be used to endorse or promote products *    derived from this software without prior written permission. For *    written permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", *    "Apache Turbine", nor may "Apache" appear in their name, without *    prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation.  For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */import java.io.IOException;import java.sql.Connection;import java.sql.SQLException;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.commons.configuration.Configuration;import org.apache.commons.configuration.PropertiesConfiguration;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.torque.adapter.DB;import org.apache.torque.adapter.DBFactory;import org.apache.torque.dsfactory.DataSourceFactory;import org.apache.torque.manager.AbstractBaseManager;import org.apache.torque.map.DatabaseMap;import org.apache.torque.map.TableMap;import org.apache.torque.oid.IDBroker;import org.apache.torque.oid.IDGeneratorFactory;import org.apache.torque.util.BasePeer;/** * The core of Torque's implementation.  Both the classic {@link * org.apache.torque.Torque} static wrapper and the {@link * org.apache.torque.avalon.TorqueComponent} <a * href="http://avalon.apache.org/">Avalon</a> implementation leverage * this class. * * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a> * @author <a href="mailto:magnus@handtolvur.is">Magn鷖 摅r Torfason</a> * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> * @author <a href="mailto:Rafal.Krzewski@e-point.pl">Rafal Krzewski</a> * @author <a href="mailto:mpoeschl@marmot.at">Martin Poeschl</a> * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a> * @author <a href="mailto:kschrader@karmalab.org">Kurt Schrader</a> * @version $Id: TorqueInstance.java,v 1.5 2003/08/05 18:09:35 mpoeschl Exp $ */public class TorqueInstance{    /** Logging */    private static Log log = LogFactory.getLog(TorqueInstance.class);    /** A constant for <code>default</code>. */    private static final String DEFAULT_NAME = "default";    /** The db name that is specified as the default in the property file */    private String defaultDBName;    /** The global cache of database maps */    private Map dbMaps;    /** The cache of DataSourceFactory's */    private Map dsFactoryMap;    /** The cache of DB adapter keys */    private Map adapterMap;    /** A repository of Manager instances. */    private Map managers;    /** Torque-specific configuration. */    private Configuration conf;    /** flag to set to true once this class has been initialized */    private boolean isInit = false;    /**     * Store mapbuilder classnames for peers that have been referenced prior     * to Torque being initialized.  This can happen if torque om/peer objects     * are serialized then unserialized prior to Torque being reinitialized.     * This condition exists in a normal catalina restart.     */    private List mapBuilders = null;    /**     * Creates a new instance with default configuration.     *     * @see #resetConfiguration()     */    public TorqueInstance()    {        resetConfiguration();    }    /**     * Initializes this instance of Torque.     *     * @see org.apache.stratum.lifecycle.Initializable     * @throws TorqueException Any exceptions caught during processing will be     *         rethrown wrapped into a TorqueException.     */    private synchronized void initialize() throws TorqueException    {        log.debug("initialize()");        if (isInit)        {            log.debug("Multiple initializations of Torque attempted");            return;        }        if (conf == null)        {            throw new TorqueException("Torque cannot be initialized without "                    + "a valid configuration. Please check the log files "                    + "for further details.");        }        // Now that we have dealt with processing the log4j properties        // that may be contained in the configuration we will make the        // configuration consist only of the remain torque specific        // properties that are contained in the configuration. First        // look for properties that are in the "torque" namespace.        Configuration subConf = conf.subset("torque");        if (!subConf.isEmpty())        {            setConfiguration(subConf);        }        dbMaps = new HashMap();        initAdapters(conf);        initDataSourceFactories(conf);        for (Iterator i = mapBuilders.iterator(); i.hasNext();)        {            //this will add any maps in this builder to the proper database map            BasePeer.getMapBuilder((String) i.next());        }        // any further mapBuilders will be called/built on demand        mapBuilders = null;        // setup manager mappings        initManagerMappings(conf);        isInit = true;    }    /**     *     * @param conf the Configuration representing the properties file     * @throws TorqueException Any exceptions caught during processing will be     *         rethrown wrapped into a TorqueException.     */    private final void initAdapters(Configuration conf)            throws TorqueException    {        log.debug("initAdapters(" + conf + ")");        adapterMap = new HashMap();        Configuration c = conf.subset("database");        if (c != null)        {            boolean foundAdapters = false;            try            {                for (Iterator it = c.getKeys(); it.hasNext(); )                {                    String key = (String) it.next();                    if (key.endsWith("adapter"))                    {                        String adapter = c.getString(key);                        String handle = key.substring(0, key.indexOf('.'));                        DB db = DBFactory.create(adapter);                        // register the adapter for this name                        adapterMap.put(handle, db);                        log.debug("Adding " + adapter + " -> " + handle + " as Adapter");                        foundAdapters = true;                    }                }                if (!foundAdapters)                {                    log.warn("Databases defined but no adapter "                             + "configurations found!");                }            }            catch (Exception e)            {                log.error("Error reading configuration seeking database "                          + "adapters", e);                throw new TorqueException(e);            }        }        else        {            log.warn("No Database definitions found!");        }    }    /**     *     * @param conf the Configuration representing the properties file     * @throws TorqueException Any exceptions caught during processing will be     *         rethrown wrapped into a TorqueException.     */    private void initDataSourceFactories(Configuration conf)            throws TorqueException    {        log.debug("initDataSourceFactories(" + conf + ")");        dsFactoryMap = new HashMap();        Configuration c = conf.subset("dsfactory");        if (c != null)        {            boolean foundFactories = false;            try            {                for (Iterator it = c.getKeys(); it.hasNext();)                {                    String key = (String) it.next();                    if (key.endsWith("factory"))                    {                        String classname = c.getString(key);                        String handle = key.substring(0, key.indexOf('.'));                        log.debug("handle: " + handle                                + " DataSourceFactory: " + classname);                        Class dsfClass = Class.forName(classname);                        DataSourceFactory dsf =                                (DataSourceFactory) dsfClass.newInstance();                        dsf.initialize(c.subset(handle));                        dsFactoryMap.put(handle, dsf);                        foundFactories = true;                    }                }                if (!foundFactories)                {                    log.warn("Data Sources configured but no factories found!");                }            }            catch (Exception e)            {                log.error("Error reading adapter configuration", e);                throw new TorqueException(e);            }        }        // As there might be a default database configured        // to map "default" onto an existing datasource, we        // must check, whether there _is_ really an entry for        // the "default" in the dsFactoryMap or not. If it is        // not, then add a dummy entry for the "default"        //        // Without this, you can't actually access the "default"        // data-source, even if you have an entry like        //        // database.default = bookstore        //        // in your Torque.properties        //        String defaultDB = getDefaultDB();        if (dsFactoryMap.get(DEFAULT_NAME) == null                && !defaultDB.equals(DEFAULT_NAME))        {            log.debug("Adding a dummy entry for "                    + DEFAULT_NAME + ", mapped onto " + defaultDB);            dsFactoryMap.put(DEFAULT_NAME, dsFactoryMap.get(defaultDB));        }    }    /**     * Initialization of Torque with a properties file.     *     * @param configFile The absolute path to the configuration file.     * @throws TorqueException Any exceptions caught during processing will be     *         rethrown wrapped into a TorqueException.     */    public void init(String configFile)            throws TorqueException    {        log.debug("init(" + configFile + ")");        try        {            Configuration conf = (Configuration)                    new PropertiesConfiguration(configFile);            log.debug("Config Object is " + conf);            init(conf);        }        catch (IOException e)        {            throw new TorqueException(e);        }    }    /**     * Initialization of Torque with a properties file.     *     * @param conf The Torque configuration.     * @throws TorqueException Any exceptions caught during processing will be     *         rethrown wrapped into a TorqueException.     */    public void init(Configuration conf)            throws TorqueException    {        log.debug("init(" + conf + ")");        setConfiguration(conf);        initialize();    }    /**     * Creates a mapping between classes and their manager classes.     *     * The mapping is built according to settings present in     * properties file.  The entries should have the     * following form:     *     * <pre>     * torque.managed_class.com.mycompany.Myclass.manager= \     *          com.mycompany.MyManagerImpl     * services.managed_class.com.mycompany.Myotherclass.manager= \     *          com.mycompany.MyOtherManagerImpl     * </pre>     *     * <br>     *     * Generic ServiceBroker provides no Services.     *     * @param conf the Configuration representing the properties file     * @throws TorqueException Any exceptions caught during processing will be     *         rethrown wrapped into a TorqueException.     */    protected void initManagerMappings(Configuration conf)            throws TorqueException    {        int pref = Torque.MANAGER_PREFIX.length();        int suff = Torque.MANAGER_SUFFIX.length();        for (Iterator it = conf.getKeys(); it.hasNext();)        {            String key = (String) it.next();            if (key.startsWith(Torque.MANAGER_PREFIX)                    && key.endsWith(Torque.MANAGER_SUFFIX))            {                String managedClassKey = key.substring(pref,                        key.length() - suff);                if (!managers.containsKey(managedClassKey))                {                    String managerClass = conf.getString(key);                    log.info("Added Manager for Class: " + managedClassKey                            + " -> " + managerClass);                    try                    {                        initManager(managedClassKey, managerClass);                    }                    catch (TorqueException e)                    {                        // the exception thrown here seems to disappear.                        // At least when initialized by Turbine, should find                        // out why, but for now make sure it is noticed.                        log.error("", e);                        e.printStackTrace();                        throw e;                    }                }            }        }    }    /**     * Initialize a manager     *     * @param name name of the manager

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -