JDBCDataConnection.java
上传用户:zhengdagz
上传日期:2014-03-06
资源大小:1956k
文件大小:11k
源码类别:

xml/soap/webservice

开发平台:

Java

  1. /*
  2.  * $Id: JDBCDataConnection.java,v 1.7 2005/10/10 17:01:16 rbair Exp $
  3.  *
  4.  * Copyright 2005 Sun Microsystems, Inc., 4150 Network Circle,
  5.  * Santa Clara, California 95054, U.S.A. All rights reserved.
  6.  *
  7.  * This library is free software; you can redistribute it and/or
  8.  * modify it under the terms of the GNU Lesser General Public
  9.  * License as published by the Free Software Foundation; either
  10.  * version 2.1 of the License, or (at your option) any later version.
  11.  * 
  12.  * This library is distributed in the hope that it will be useful,
  13.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15.  * Lesser General Public License for more details.
  16.  * 
  17.  * You should have received a copy of the GNU Lesser General Public
  18.  * License along with this library; if not, write to the Free Software
  19.  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  20.  */
  21. package org.jdesktop.dataset.provider.sql;
  22. import java.sql.Connection;
  23. import java.sql.DriverManager;
  24. import java.sql.PreparedStatement;
  25. import java.sql.ResultSet;
  26. import java.util.Properties;
  27. import javax.naming.InitialContext;
  28. import org.jdesktop.dataset.DataConnection;
  29. /**
  30.  * An implementation of the DataConnection for interacting with
  31.  * a local database. This implementation is "local", meaning that it is
  32.  * written and optimized for low latency database access, such as for an in
  33.  * memory database, or one on a local network.
  34.  * <p/>
  35.  * @author rbair
  36.  */
  37. public class JDBCDataConnection extends DataConnection {
  38.     /**
  39.      * The connection to the database
  40.      */
  41.     private Connection conn;
  42.     /**
  43.      * This is a mutex used to control access to the conn object.
  44.      * Note that I create a new String object explicitly. This is done
  45.      * so that a single mutex is unique for each JDBCDataConnection
  46.      * instance.
  47.      */
  48.     private final Object connMutex = new String("Connection_Mutex");
  49.     /**
  50.      * If used, defines the JNDI context from which to get a connection to
  51.      * the data base
  52.      */
  53.     private String jndiContext;
  54.     /**
  55.      * When using the DriverManager to connect to the database, this specifies
  56.      * the URL to use to make that connection. URL's are specific to the
  57.      * JDBC vendor.
  58.      */
  59.     private String url;
  60.     /**
  61.      * When using the DriverManager to connect to the database, this specifies
  62.      * the user name to log in with.
  63.      */
  64.     private String userName;
  65.     /**
  66.      * When using the DriverManager to connect to the database, this specifies
  67.      * the password to log in with.
  68.      */
  69.     private String password;
  70.     /**
  71.      * When using the DriverManager to connect to the database, this specifies
  72.      * any additional properties to use when connecting.
  73.      */
  74.     private Properties properties;
  75.     
  76.     /**
  77.      * Create a new DatabaseDataStoreConnection. Be sure to set the JDBC connection
  78.      * properties (user name, password, connection method, etc)
  79.      * prior to connecting this object.
  80.      */
  81.     public JDBCDataConnection() {
  82.     }
  83.     
  84.     
  85.     /**
  86.      * Create a new JDBCDataConnection and initializes it to connect to a
  87.      * database using the given params.
  88.      * @param driver
  89.      * @param url
  90.      * @param user
  91.      * @param passwd
  92.      */
  93.     public JDBCDataConnection(String driver, String url, String user,
  94.             String passwd) {
  95.         try {
  96.             Class.forName(driver);
  97.         } catch (Exception e) {
  98.             System.err.println("WARN: The driver passed to the " +
  99.                     "JDBCDataConnection constructor could not be loaded. " +
  100.                     "This may be due to the driver not being on the classpath");
  101.             e.printStackTrace();
  102.         }
  103.         this.setUrl(url);
  104.         this.setUserName(user);
  105.         this.setPassword(passwd);
  106.     }
  107.     
  108.     /**
  109.      * Create a new JDBCDataConnection and initializes it to connect to a
  110.      * database using the given params.
  111.      * @param driver
  112.      * @param url
  113.      * @param props
  114.      */
  115.     public JDBCDataConnection(String driver, String url, Properties props) {
  116.         try {
  117.             Class.forName(driver);
  118.         } catch (Exception e) {
  119.             System.err.println("WARN: The driver passed to the " +
  120.                     "JDBCDataConnection constructor could not be loaded. " +
  121.                     "This may be due to the driver not being on the classpath");
  122.             e.printStackTrace();
  123.         }
  124.         this.setUrl(url);
  125.         this.setProperties(props);
  126.     }
  127.     
  128.     /**
  129.      * Create a new JDBCDataConnection and initializes it to connect to a
  130.      * database using the given params.
  131.      * @param jndiContext
  132.      * @param user
  133.      * @param passwd
  134.      */
  135.     public JDBCDataConnection(String jndiContext, String user, String passwd) {
  136.         this.jndiContext = jndiContext;
  137.         this.setUserName(user);
  138.         this.setPassword(passwd);
  139.     }
  140.     
  141.     
  142.     /**
  143.      * @return the JDBC connection url
  144.      */
  145.     public String getUrl() {
  146.         return url;
  147.     }
  148.     /**
  149.      * @param url set the JDBC connection url
  150.      */
  151.     public void setUrl(String url) {
  152.         this.url = url;
  153.     }
  154.     /**
  155.      * @return the user name used to connect to the database
  156.      */
  157.     public String getUserName() {
  158.         return userName;
  159.     }
  160.     /**
  161.      * @param userName used to connect to the database
  162.      */
  163.     public void setUserName(String userName) {
  164.         this.userName = userName;
  165.     }
  166.     /**
  167.      * @return the password used to connect to the database
  168.      */
  169.     public String getPassword() {
  170.         return password;
  171.     }
  172.     /**
  173.      * @param password the password used to connect to the database
  174.      */
  175.     public void setPassword(String password) {
  176.         this.password = password;
  177.     }
  178.     /**
  179.      * @return JDBC connection properties
  180.      */
  181.     public Properties getProperties() {
  182.         return properties;
  183.     }
  184.     /**
  185.      * @param properties miscellaneous JDBC properties to use when connecting
  186.      *        to the database via the JDBC driver
  187.      */
  188.     public void setProperties(Properties properties) {
  189.         this.properties = properties;
  190.     }
  191.     /**
  192.      * Connect to the database. This method attempts to connect via jndiContext
  193.      * first, if possible. If not, then it tries to connect by using the
  194.      * DriverManager.
  195.      */
  196.     protected void connect() throws Exception {
  197.         //if the jndiContext is not null, then try to get the DataSource to use
  198.         //from jndi
  199.         if (jndiContext != null) {
  200.             try {
  201.                 connectByJNDI();
  202.             } catch (Exception e) {
  203.                 try {
  204.                     connectByDriverManager();
  205.                 } catch (Exception ex) {
  206.                     throw new Exception("Failed to connect to the database", e);
  207.                 }
  208.             }
  209.         } else {
  210.             try {
  211.                 connectByDriverManager();
  212.             } catch (Exception ex) {
  213.                 throw new Exception("Failed to connect to the database", ex);
  214.             }
  215.         }
  216.     }
  217.     
  218.     /**
  219.      * Attempts to get a JDBC Connection from a JNDI javax.sql.DataSource, using
  220.      * that connection for interacting with the database.
  221.      * @throws Exception
  222.      */
  223.     private void connectByJNDI() throws Exception {
  224.         InitialContext ctx = new InitialContext();
  225.         javax.sql.DataSource ds = (javax.sql.DataSource)ctx.lookup(jndiContext);
  226.         synchronized(connMutex) {
  227.             conn = ds.getConnection(getUserName(), getPassword());
  228.             conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
  229.         }
  230.     }
  231.     
  232.     /**
  233.      * Attempts to get a JDBC Connection from a DriverManager. If properties
  234.      * is not null, it tries to connect with those properties. If that fails,
  235.      * it then attempts to connect with a user name and password. If that fails,
  236.      * it attempts to connect without any credentials at all.
  237.      * <p>
  238.      * If, on the other hand, properties is null, it first attempts to connect
  239.      * with a username and password. Failing that, it tries to connect without
  240.      * any credentials at all.
  241.      * @throws Exception
  242.      */
  243.     private void connectByDriverManager() throws Exception {
  244.         synchronized(connMutex) {
  245.             if (getProperties() != null) {
  246.                 try {
  247.                     conn = DriverManager.getConnection(getUrl(), getProperties());
  248.                     conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
  249.                 } catch (Exception e) {
  250.                     try {
  251.                         conn = DriverManager.getConnection(getUrl(), getUserName(), getPassword());
  252.                         conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
  253.                     } catch (Exception ex) {
  254.                         conn = DriverManager.getConnection(getUrl());
  255.                         conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
  256.                     }
  257.                 }
  258.             } else {
  259.                 try {
  260.                     conn = DriverManager.getConnection(getUrl(), getUserName(), getPassword());
  261.                     
  262.                 } catch (Exception e) {
  263.                     e.printStackTrace();
  264.                     //try to connect without using the userName and password
  265.                     conn = DriverManager.getConnection(getUrl());
  266.                     
  267.                 }
  268.             }
  269.         }
  270.     }
  271.     
  272.     /**
  273.      * Disconnects from the database and causes all of the attached DataModels
  274.      * to flush their contents.
  275.      */
  276.     protected void disconnect() throws Exception {
  277.         synchronized(connMutex) {
  278.             if (conn != null) {
  279.                 conn.close();
  280.             }
  281.         }
  282.     }
  283.     
  284.     public ResultSet executeQuery(PreparedStatement ps) {
  285.         synchronized(connMutex) {
  286.             if (conn != null) {
  287.                 try {
  288.                     return ps.executeQuery();
  289.                 } catch (Exception e) {
  290.                     e.printStackTrace();
  291.                 }
  292.             }
  293.         }
  294.         return null;
  295.     }
  296.     public int executeUpdate(PreparedStatement ps) {
  297.         synchronized(connMutex) {
  298.             if (conn != null) {
  299.                 try {
  300.                     return ps.executeUpdate();
  301.                 } catch (Exception e) {
  302.                     e.printStackTrace();
  303.                 }
  304.             }
  305.             // TODO: hmm. may want a note somewhere that if connection not established, we will fail silently (PWW 04/25/05)
  306.         }
  307.         return 0;
  308.     }
  309.     
  310.     public PreparedStatement prepareStatement(String sql) throws Exception {
  311.         synchronized(connMutex) {
  312.             if (conn != null) {
  313.                 return conn.prepareStatement(sql);
  314.             }
  315.         }
  316.         return null;
  317.     }
  318.     
  319.     public void commit() {
  320.         try {
  321.             conn.commit();
  322.         } catch (Exception e) {
  323.             e.printStackTrace();
  324.         }
  325.     }
  326.     
  327.     public Connection getConnection() {
  328.         return conn;
  329.     }
  330. }