001    /*
002     * Copyright 2001,2004 The Apache Software Foundation.
003     * 
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     * 
008     *      http://www.apache.org/licenses/LICENSE-2.0
009     * 
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.apache.commons.scaffold.sql;
018    
019    
020    import java.sql.SQLException;
021    
022    import javax.servlet.http.HttpServlet;
023    import javax.sql.DataSource;
024    
025    
026    /**
027     * Connection adaptor for a connection pool that is exposed
028     * through the servlet context, like the Struts generic
029     * connection pool.
030     * <p>
031     * The ConnectionServlet will automatically set a reference
032     * to itself if an instance of this class is specified
033     * as the ConnectionAdaptor.
034     *
035     * @author Ted Husted
036     * @version $Revision: 155464 $ $Date: 2005-02-26 13:26:54 +0000 (Sat, 26 Feb 2005) $
037     */
038    public class ServletAdaptor extends ConnectionAdaptor {
039    
040    
041        /**
042         * Field to store a link to a servlet in the application.
043         */
044        private static HttpServlet servlet = null;
045    
046    
047        /**
048         * Set a reference to a servlet in the application
049         * to allow access to the servlet context.
050         */
051        public void setServlet(HttpServlet servlet) {
052            ServletAdaptor.servlet = servlet;
053        }
054    
055    
056       /**
057        * Return datasource from the servlet context using
058        * key as the attribute name.
059        *
060        * @param key The attribute name for the resource.
061        * If null is passed, null is returned.
062        * @returns null or the datasource object related to "key"
063        */
064        protected DataSource getDataSource(String key)
065                throws SQLException {
066    
067            if (null==key) return null;
068    
069            return (DataSource)
070                servlet.getServletContext().getAttribute(key);
071    
072        }
073    
074    
075         // Required
076        public ServletAdaptor() {
077    
078            if (null==pool) pool = this;
079    
080        }
081    
082    } // end ServletAdaptor
083