View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.db;
15  
16  
17  import javax.naming.Context;
18  import javax.naming.InitialContext;
19  import javax.sql.DataSource;
20  
21  import org.xml.sax.Attributes;
22  
23  import ch.qos.logback.core.joran.action.Action;
24  import ch.qos.logback.core.joran.spi.InterpretationContext;
25  import ch.qos.logback.core.joran.util.PropertySetter;
26  import ch.qos.logback.core.util.OptionHelper;
27  
28  /**
29   * 
30   * @author Ceki Gulcu
31   *
32   */
33  public class BindDataSourceToJNDIAction extends Action {
34    
35    static final String DATA_SOURCE_CLASS = "dataSourceClass";
36    static final String URL = "url";
37    static final String USER = "user";
38    static final String PASSWORD = "password";
39  
40    /**
41     * Instantiates an a data source and bind it to JNDI
42     * Most of the required parameters are placed in the ec.substitutionProperties
43     */
44    public void begin(
45        InterpretationContext ec, String localName, Attributes attributes) {
46      String dsClassName = ec.getProperty(DATA_SOURCE_CLASS);
47  
48      if (OptionHelper.isEmpty(dsClassName)) {
49        addWarn("dsClassName is a required parameter");
50        ec.addError("dsClassName is a required parameter");
51  
52        return;
53      }
54  
55      String urlStr = ec.getProperty(URL);
56      String userStr = ec.getProperty(USER);
57      String passwordStr = ec.getProperty(PASSWORD);
58  
59      try {
60        DataSource ds =
61          (DataSource) OptionHelper.instantiateByClassName(dsClassName, DataSource.class, context);
62  
63        PropertySetter setter = new PropertySetter(ds);
64        setter.setContext(context);
65  
66        if (!OptionHelper.isEmpty(urlStr)) {
67          setter.setProperty("url", urlStr);
68        }
69  
70        if (!OptionHelper.isEmpty(userStr)) {
71          setter.setProperty("user", userStr);
72        }
73  
74        if (!OptionHelper.isEmpty(passwordStr)) {
75          setter.setProperty("password", passwordStr);
76        }
77  
78        Context ctx = new InitialContext();
79        ctx.rebind("dataSource", ds);
80      } catch (Exception oops) {
81        addError(
82          "Could not bind  datasource. Reported error follows.", oops);
83        ec.addError("Could not not bind  datasource of type [" + dsClassName + "].");
84      }
85    }
86  
87    public void end(InterpretationContext ec, String name) {
88    }
89  }