001/*
002 * (C) Copyright 2009 Nuxeo SA (http://nuxeo.com/) and others.
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 * Contributors:
017 *     Florent Guillaume
018 */
019
020package org.nuxeo.runtime.datasource;
021
022import java.util.HashMap;
023import java.util.Hashtable;
024import java.util.Map;
025import java.util.Map.Entry;
026
027import javax.naming.Context;
028import javax.naming.Name;
029import javax.naming.NamingException;
030import javax.naming.Reference;
031import javax.naming.StringRefAddr;
032import javax.naming.spi.ObjectFactory;
033import javax.sql.DataSource;
034import javax.sql.XADataSource;
035
036import org.apache.commons.logging.LogFactory;
037import org.apache.tomcat.jdbc.naming.GenericNamingResourcesFactory;
038import org.nuxeo.common.xmap.annotation.XNode;
039import org.nuxeo.common.xmap.annotation.XNodeMap;
040import org.nuxeo.common.xmap.annotation.XObject;
041import org.nuxeo.runtime.api.Framework;
042import org.w3c.dom.Element;
043import org.w3c.dom.NamedNodeMap;
044import org.w3c.dom.Node;
045
046/**
047 * The descriptor for a Nuxeo-defined datasource.
048 * <p>
049 * The attributes of a {@code <datasource>} element are:
050 * <ul>
051 * <li><b>name</b>: the JNDI name (for instance {@code jdbc/foo})</li>
052 * <li><b>driverClassName</b>: the JDBC driver class name (only for a non-XA datasource)</li>
053 * <li><b>xaDataSource</b>: the XA datasource class name (only for a XA datasource)</li>
054 * </ul>
055 * <p>
056 * To configure the characteristics of the pool:
057 * <ul>
058 * <li><b>maxActive</b>: the maximum number of active connections</li>
059 * <li><b>minIdle</b>: the minimum number of idle connections</li>
060 * <li><b>maxIdle</b>: the maximum number of idle connections</li>
061 * <li><b>maxWait</b>: the maximum number of milliseconds to wait for a connection to be available, or -1 (the default)
062 * to wait indefinitely</li>
063 * <li>... see {@link org.apache.commons.dbcp.BasicDataSource BasicDataSource} setters for more</li>
064 * </ul>
065 * <p>
066 * To configure the datasource connections, individual {@code <property>} sub-elements are used.
067 * <p>
068 * For a non-XA datasource, you must specify at least a <b>url</b>:
069 *
070 * <pre>
071 *   &lt;property name=&quot;url&quot;&gt;jdbc:derby:foo/bar&lt;/property&gt;
072 *   &lt;property name=&quot;username&quot;&gt;nuxeo&lt;/property&gt;
073 *   &lt;property name=&quot;password&quot;&gt;nuxeo&lt;/property&gt;
074 * </pre>
075 *
076 * For a XA datasource, see the documentation for your JDBC driver.
077 */
078@XObject("datasource")
079public class DataSourceDescriptor {
080
081    /*
082     * It is not possible to expand the variables in the setters because in tests, values are not available in context.
083     * A clean up needs to be done to have the values during startup.
084     */
085
086    @XNode("@name")
087    protected String name;
088
089    public String getName() {
090        return Framework.expandVars(name);
091    }
092
093    @XNode("@xaDataSource")
094    protected String xaDataSource;
095
096    public String getXaDataSource() {
097        return Framework.expandVars(xaDataSource);
098    }
099
100    @XNode("@dataSource")
101    protected String dataSource;
102
103    public String getDataSource() {
104        return Framework.expandVars(dataSource);
105    }
106
107    @XNode("@driverClassName")
108    protected String driverClasssName;
109
110    public String getDriverClasssName() {
111        return Framework.expandVars(driverClasssName);
112    }
113
114    @XNode("")
115    public Element element;
116
117    @XNodeMap(value = "property", key = "@name", type = HashMap.class, componentType = String.class)
118    public Map<String, String> properties;
119
120    protected Reference poolReference;
121
122    protected Reference xaReference;
123
124    public static class PoolFactory implements ObjectFactory {
125
126        @Override
127        public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> env) {
128            return Framework.getService(PooledDataSourceRegistry.class).getOrCreatePool(obj, name, nameCtx, env);
129        }
130
131    }
132
133    public void bindSelf(Context naming) throws NamingException {
134        if (xaDataSource != null) {
135            String xaName = DataSourceHelper.relativize(getName() + "-xa");
136            poolReference = new Reference(XADataSource.class.getName(), PoolFactory.class.getName(), null);
137            poolReference.add(new StringRefAddr("dataSourceJNDI", xaName));
138            xaReference = new Reference(Framework.expandVars(xaDataSource),
139                    GenericNamingResourcesFactory.class.getName(), null);
140            for (Entry<String, String> e : properties.entrySet()) {
141                String key = e.getKey();
142                String value = Framework.expandVars(e.getValue());
143                StringRefAddr addr = new StringRefAddr(key, value);
144                xaReference.add(addr);
145            }
146            naming.bind(DataSourceHelper.getDataSourceJNDIName(xaName), xaReference);
147        } else if (dataSource != null) {
148            poolReference = new Reference(DataSource.class.getName(), PoolFactory.class.getName(), null);
149            final String name = Framework.expandVars(dataSource);
150            poolReference.add(new StringRefAddr("dataSourceJNDI", DataSourceHelper.getDataSourceJNDIName(name)));
151        } else if (driverClasssName != null) {
152            poolReference = new Reference(DataSource.class.getName(), PoolFactory.class.getName(), null);
153        } else {
154            throw new RuntimeException("Datasource " + getName()
155                    + " should have xaDataSource or driverClassName attribute");
156        }
157
158        for (Entry<String, String> e : properties.entrySet()) {
159            String key = e.getKey();
160            String value = Framework.expandVars(e.getValue());
161            StringRefAddr addr = new StringRefAddr(key, value);
162            poolReference.add(addr);
163        }
164
165        NamedNodeMap attrs = element.getAttributes();
166        for (int i = 0; i < attrs.getLength(); i++) {
167            Node attr = attrs.item(i);
168            String attrName = attr.getNodeName();
169            String value = Framework.expandVars(attr.getNodeValue());
170            StringRefAddr addr = new StringRefAddr(attrName, value);
171            poolReference.add(addr);
172        }
173
174        LogFactory.getLog(DataSourceDescriptor.class).info("binding " + getName());
175        String jndiName = DataSourceHelper.getDataSourceJNDIName(getName());
176        naming.bind(jndiName, poolReference);
177        // create pooled
178        naming.lookup(jndiName);
179    }
180
181    public void unbindSelf(Context naming) throws NamingException {
182        try {
183            final PooledDataSourceRegistry registry = Framework.getLocalService(PooledDataSourceRegistry.class);
184            if (registry != null) {
185                registry.clearPool(getName());
186            }
187        } finally {
188            try {
189                if (xaReference != null) {
190                    naming.unbind(DataSourceHelper.getDataSourceJNDIName(getName() + "-xa"));
191                }
192            } finally {
193                naming.unbind(DataSourceHelper.getDataSourceJNDIName(getName()));
194            }
195        }
196    }
197
198}