xconnection.java

来自「java jdk 1.4的源码」· Java 代码 · 共 1,398 行 · 第 1/3 页

JAVA
1,398
字号
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation.  All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright *    notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright *    notice, this list of conditions and the following disclaimer in *    the documentation and/or other materials provided with the *    distribution. * * 3. The end-user documentation included with the redistribution, *    if any, must include the following acknowledgment: *       "This product includes software developed by the *        Apache Software Foundation (http://www.apache.org/)." *    Alternately, this acknowledgment may appear in the software itself, *    if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must *    not be used to endorse or promote products derived from this *    software without prior written permission. For written *    permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", *    nor may "Apache" appear in their name, without prior written *    permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com.  For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */package org.apache.xalan.lib.sql;import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Date;import java.sql.Timestamp;import java.sql.Time;import java.util.Properties;import java.util.Vector;import java.util.StringTokenizer;import java.lang.IllegalArgumentException;import org.w3c.dom.Element;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.NodeList;import org.w3c.dom.Node;import java.util.Vector;import java.util.Enumeration;import java.math.BigDecimal;import org.apache.xml.dtm.DTM;import org.apache.xml.dtm.DTMManager;import org.apache.xml.dtm.ref.DTMManagerDefault;import org.apache.xpath.XPathContext;import org.apache.xalan.extensions.ExpressionContext;import org.apache.xpath.objects.XBooleanStatic;import org.w3c.dom.*;import java.sql.*;import java.util.*;/** * An XSLT extension that allows a stylesheet to * access JDBC data.  * * It is accessed by specifying a namespace URI as follows: * <pre> *    xmlns:sql="http://xml.apache.org/xalan/sql" * </pre> * * From the stylesheet perspective, * XConnection provides 3 extension functions: new(), * query(), and close(). * Use new() to call one of XConnection constructors, which * establishes a JDBC driver connection to a data source and * returns an XConnection object. * Then use the XConnection object query() method to return a * result set in the form of a row-set element. * When you have finished working with the row-set, call the * XConnection object close() method to terminate the connection. */public class XConnection{  /**   * Flag for DEBUG mode   */  private static final boolean DEBUG = false;  /**   * The Current Connection Pool in Use. An XConnection can only   * represent one query at a time, prior to doing some type of query.   */  private ConnectionPool m_ConnectionPool = null;  /**   * If a default Connection Pool is used. i.e. A connection Pool   * that is created internally, then do we actually allow pools   * to be created. Due to the archititure of the Xalan Extensions,   * there is no notification of when the Extension is being unloaded and   * as such, there is a good chance that JDBC COnnections are not closed.   * A finalized is provided to try and catch this situation but since   * support of finalizers is inconsistant across JVM's this may cause   * a problem. The robustness of the JDBC Driver is also at issue here.   * if a controlled shutdown is provided by the driver then default   * conntectiom pools are OK.   */  private boolean m_DefaultPoolingEnabled = false;  /**   * As we do queries, we will produce SQL Documents. Any ony may produce   * one or more SQL Documents so that the current connection information   * may be easilly reused. This collection will hold a collection of all   * the documents created. As Documents are closed, they will be removed   * from the collection and told to free all the used resources.   */  private Vector m_OpenSQLDocuments = new Vector();  /**   * Let's keep a copy of the ConnectionPoolMgr in   * alive here so we are keeping the static pool alive   * We will also use this Pool Manager to register our default pools.   */  private ConnectionPoolManager m_PoolMgr = new ConnectionPoolManager();  /**   * For PreparedStatements, we need a place to   * to store the parameters in a vector.   */  private Vector m_ParameterList = new Vector();  /**   * Allow the SQL Extensions to return null on error. The Error information will   * be stored in a seperate Error Document that can easily be retrived using the   * getError() method.   * %REVIEW% This functionality will probably be buried inside the SQLDocument.   */  private SQLErrorDocument m_Error = null;  /**   */  private boolean m_IsDefaultPool = false;  /**   * This flag will be used to indicate to the SQLDocument to use   * Streaming mode. Streeaming Mode will reduce the memory footprint   * to a fixed amount but will not let you traverse the tree more than   * once since the Row data will be reused for every Row in the Query.   */  private boolean m_IsStreamingEnabled = true;  /**   */  public XConnection( )  {  }  // The original constructors will be kept around for backwards  // compatibility. Future Stylesheets should use the approaite  // connect method to receive full error information.  //  /**   * @param exprContext   * @param ConnPoolName   */  public XConnection( ExpressionContext exprContext, String ConnPoolName )  {    connect(exprContext, ConnPoolName);  }  /**   * @param exprContext   * @param driver   * @param dbURL   */  public XConnection( ExpressionContext exprContext, String driver, String dbURL )  {    connect(exprContext, driver, dbURL);  }  /**   * @param exprContext   * @param list   */  public XConnection( ExpressionContext exprContext, NodeList list )  {    connect(exprContext, list);  }  /**   * @param exprContext   * @param driver   * @param dbURL   * @param user   * @param password   */  public XConnection( ExpressionContext exprContext, String driver, String dbURL, String user, String password )  {    connect(exprContext, driver, dbURL, user, password);  }  /**   * @param exprContext   * @param driver   * @param dbURL   * @param protocolElem   */  public XConnection( ExpressionContext exprContext, String driver, String dbURL, Element protocolElem )  {    connect(exprContext, driver, dbURL, protocolElem);  }  /**   * Create an XConnection using the name of an existing Connection Pool   * @param exprContext   * @param ConnPoolName   * @return   */  public XBooleanStatic connect( ExpressionContext exprContext, String ConnPoolName )  {    try    {      m_ConnectionPool = m_PoolMgr.getPool(ConnPoolName);      if (m_ConnectionPool == null)        throw new java.lang.IllegalArgumentException("Invalid Pool Name");      m_IsDefaultPool = false;      return new XBooleanStatic(true);    }    catch (Exception e)    {      buildErrorDocument(exprContext, e);      return new XBooleanStatic(false);    }  }  /**   * Create an XConnection object with just a driver and database URL.   * @param exprContext   * @param driver JDBC driver of the form foo.bar.Driver.   * @param dbURL database URL of the form jdbc:subprotocol:subname.   * @return   */  public XBooleanStatic connect( ExpressionContext exprContext, String driver, String dbURL )  {    try    {      init(driver, dbURL, new Properties());      return new XBooleanStatic(true);    }    catch(SQLException e)    {      buildErrorDocument(exprContext, e);      return new XBooleanStatic(false);    }    catch (Exception e)    {      buildErrorDocument(exprContext, e);      return new XBooleanStatic(false);    }  }  /**   * @param exprContext   * @param protocolElem   * @return   */  public XBooleanStatic connect( ExpressionContext exprContext, Element protocolElem )  {    try    {      initFromElement(protocolElem);      return new XBooleanStatic(true);    }    catch(SQLException e)    {      buildErrorDocument(exprContext, e);      return new XBooleanStatic(false);    }    catch (Exception e)    {      buildErrorDocument(exprContext, e);      return new XBooleanStatic(false);    }  }  /**   * @param exprContext   * @param list   * @return   */  public XBooleanStatic connect( ExpressionContext exprContext, NodeList list )  {    try    {      initFromElement( (Element) list.item(0) );      return new XBooleanStatic(true);    }    catch(SQLException e)    {      buildErrorDocument(exprContext, e);      return new XBooleanStatic(false);    }    catch (Exception e)    {      buildErrorDocument(exprContext, e);      return new XBooleanStatic(false);    }  }  /**   * Create an XConnection object with user ID and password.   * @param exprContext   * @param driver JDBC driver of the form foo.bar.Driver.   * @param dbURL database URL of the form jdbc:subprotocol:subname.   * @param user user ID.   * @param password connection password.   * @return   */  public XBooleanStatic connect( ExpressionContext exprContext, String driver, String dbURL, String user, String password )  {    try    {      Properties prop = new Properties();      prop.put("user", user);      prop.put("password", password);      init(driver, dbURL, prop);      return new XBooleanStatic(true);    }    catch(SQLException e)    {      buildErrorDocument(exprContext, e);      return new XBooleanStatic(false);    }    catch (Exception e)    {      buildErrorDocument(exprContext, e);      return new XBooleanStatic(false);    }  }  /**   * Create an XConnection object with a connection protocol   * @param exprContext   * @param driver JDBC driver of the form foo.bar.Driver.   * @param dbURL database URL of the form jdbc:subprotocol:subname.   * @param protocolElem list of string tag/value connection arguments,   * normally including at least "user" and "password".   * @return   */  public XBooleanStatic connect( ExpressionContext exprContext, String driver, String dbURL, Element protocolElem )  {    try    {      Properties prop = new Properties();      NamedNodeMap atts = protocolElem.getAttributes();      for (int i = 0; i < atts.getLength(); i++)      {        prop.put(atts.item(i).getNodeName(), atts.item(i).getNodeValue());      }      init(driver, dbURL, prop);      return new XBooleanStatic(true);    }    catch(SQLException e)    {      buildErrorDocument(exprContext, e);      return new XBooleanStatic(false);    }    catch (Exception e)    {      buildErrorDocument(exprContext, e);      return new XBooleanStatic(false);    }  }  /**   * Allow the database connection information to be sepcified in   * the XML tree. The connection information could also be   * externally originated and passed in as an XSL Parameter.   * The required XML Format is as follows.   * A document fragment is needed to specify the connection information   * the top tag name is not specific for this code, we are only interested   * in the tags inside.   * <DBINFO-TAG>   * Specify the driver name for this connection pool   * <dbdriver>drivername</dbdriver>   * Specify the URL for the driver in this connection pool   * <dburl>url</dburl>   * Specify the password for this connection pool   * <password>password</password>   * Specify the username for this connection pool   * <user>username</user>   * You can add extra protocol items including the User Name & Password   * with the protocol tag. For each extra protocol item, add a new element   * where the name of the item is specified as the name attribute and   * and its value as the elements value.   * <protocol name="name of value">value</protocol>   * </DBINFO-TAG>   * @param e   * @return   * @throws SQLException   */  private void initFromElement( Element e )throws SQLException  {    Properties prop = new Properties();    String driver = "";    String dbURL = "";    Node n = e.getFirstChild();    if (null == n) return; // really need to throw an error    do    {      String nName = n.getNodeName();      if (nName.equalsIgnoreCase("dbdriver"))      {        driver = "";        Node n1 = n.getFirstChild();        if (null != n1)        {          driver = n1.getNodeValue();        }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?