View Javadoc

1   /*
2    * Copyright 2000-2004 The Apache Software Foundation.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.apache.jetspeed.components.datasource;
17  
18  import java.sql.Connection;
19  import java.sql.SQLException;
20  import java.sql.Statement;
21  
22  import org.apache.commons.logging.Log;
23  import org.apache.commons.logging.LogFactory;
24  import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
25  
26  /***
27   * The SchemaAwareDataSourceProxy optionally injects a schema selection into an
28   * existing database connection. It proxies a DataSource and executes an
29   * injected sql statement on every getConnection() call.
30   * 
31   * Inspired by http://forum.springframework.org/showthread.php?t=10728, runtime
32   * schema switching was stripped.
33   * 
34   * @author <a href="mailto:joachim@wemove.com">Joachim Müller</a>
35   * @version $Id: SchemaAwareDataSourceProxy.java 601297 2007-12-05 11:20:04Z ate $
36   */
37  public class SchemaAwareDataSourceProxy extends TransactionAwareDataSourceProxy
38  {
39      private static final Log log = LogFactory.getLog(SchemaAwareDataSourceProxy.class);
40  
41      private String schemaSql = null;
42  
43      public void setSchemaSql(String schemaSql)
44      {
45          this.schemaSql = schemaSql;
46      }
47  
48      public Connection getConnection() throws SQLException
49      {
50          Connection con = super.getConnection();
51  
52          if (schemaSql != null)
53          {
54              if (log.isDebugEnabled())
55              {
56                  log.debug("Setting schema by executing sql '" + schemaSql + "' on connection " + con);
57              }
58  
59              Statement stmt = con.createStatement();
60              try
61              {
62                  // database specific SQL.
63                  stmt.execute(schemaSql);
64              }
65              catch (Exception e)
66              {
67                  log.error("Error executing table schema setting sql: '" + schemaSql + "'.", e);
68              }
69              finally
70              {
71                  stmt.close();
72              }
73          }
74  
75          return con;
76      }
77  }