View Javadoc

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