public void attemptManageC3P0Registry() {
    try {
      ObjectName name = new ObjectName(regName);
      C3P0RegistryManager mbean = new C3P0RegistryManager();

      if (mbs.isRegistered(name)) {
        if (logger.isLoggable(MLevel.WARNING)) {
          logger.warning(
              "A C3P0Registry mbean is already registered. "
                  + "This probably means that an application using c3p0 was undeployed, "
                  + "but not all PooledDataSources were closed prior to undeployment. "
                  + "This may lead to resource leaks over time. Please take care to close "
                  + "all PooledDataSources.");
        }
        mbs.unregisterMBean(name);
      }
      mbs.registerMBean(mbean, name);
    } catch (Exception e) {
      if (logger.isLoggable(MLevel.WARNING))
        logger.log(
            MLevel.WARNING,
            "Failed to set up C3P0RegistryManager mBean. "
                + "[c3p0 will still function normally, but management via JMX may not be possible.]",
            e);
    }
  }
  // synchronized to protect exposedProxy
  public synchronized Connection getConnection() throws SQLException {
    if (exposedProxy != null) {
      // DEBUG
      // System.err.println("[DOUBLE_GET_TESTER] -- double getting a Connection from " + this );
      // new Exception("[DOUBLE_GET_TESTER] -- Double-Get Stack Trace").printStackTrace();
      // origGet.printStackTrace();

      // 		System.err.println("c3p0 -- Uh oh... getConnection() was called on a PooledConnection
      // when " +
      // 				   "it had already provided a client with a Connection that has not yet been " +
      // 				   "closed. This probably indicates a bug in the connection pool!!!");

      logger.warning(
          "c3p0 -- Uh oh... getConnection() was called on a PooledConnection when "
              + "it had already provided a client with a Connection that has not yet been "
              + "closed. This probably indicates a bug in the connection pool!!!");

      return exposedProxy;
    } else {
      return getCreateNewConnection();
    }
  }
  public void attemptManagePooledDataSource(PooledDataSource pds) {
    String name = null;
    try {
      name = getPdsObjectNameStr(pds);
      ObjectName oname = new ObjectName(name);
      if (mbs.isRegistered(oname)) {
        if (logger.isLoggable(MLevel.WARNING))
          logger.warning(
              "You are attempting to register an mbean '"
                  + name
                  + "', but an mbean by that name is already registered. "
                  + "The new mbean will replace the old one in the MBean server. "
                  + (EXCLUDE_IDENTITY_TOKEN
                      ? "Since you have excluded the guaranteed-unique identity token, you must take care to give each PooledDataSource a unique dataSourceName."
                      : "This should not happen unless you have (pathologically) modified the DataSource's guaranteed-unique identityToken."));
      }

      // PooledDataSourceManager mbean = new PooledDataSourceManager( pds );
      // mbs.registerMBean(mbean, ObjectName.getInstance(name));
      // if (logger.isLoggable(MLevel.FINER))
      //    logger.log(MLevel.FINER, "MBean: " + name + " registered.");

      // DynamicPooledDataSourceManagerMBean registers itself on construction (and logs its own
      // registration)
      DynamicPooledDataSourceManagerMBean mbean =
          new DynamicPooledDataSourceManagerMBean(pds, name, mbs);
    } catch (Exception e) {
      if (logger.isLoggable(MLevel.WARNING))
        logger.log(
            MLevel.WARNING,
            "Failed to set up a PooledDataSourceManager mBean. [ "
                + (name == null ? pds.toString() : name)
                + " ] c3p0 will still function normally, but management of this DataSource by JMX may not be possible.",
            e);
    }
  }
  public Reference createReference(Object bean) throws NamingException {
    try {
      BeanInfo bi = Introspector.getBeanInfo(bean.getClass());
      PropertyDescriptor[] pds = bi.getPropertyDescriptors();
      List refAddrs = new ArrayList();
      String factoryClassLocation = defaultFactoryClassLocation;

      boolean using_ref_props = referenceProperties.size() > 0;

      // we only include this so that on dereference we are not surprised to find some properties
      // missing
      if (using_ref_props)
        refAddrs.add(
            new BinaryRefAddr(REF_PROPS_KEY, SerializableUtils.toByteArray(referenceProperties)));

      for (int i = 0, len = pds.length; i < len; ++i) {
        PropertyDescriptor pd = pds[i];
        String propertyName = pd.getName();
        // System.err.println("Making Reference: " + propertyName);

        if (using_ref_props && !referenceProperties.contains(propertyName)) {
          // System.err.println("Not a ref_prop -- continuing.");
          continue;
        }

        Class propertyType = pd.getPropertyType();
        Method getter = pd.getReadMethod();
        Method setter = pd.getWriteMethod();
        if (getter != null
            && setter != null) // only use properties that are both readable and writable
        {
          Object val = getter.invoke(bean, EMPTY_ARGS);
          // System.err.println( "val: " + val );
          if (propertyName.equals("factoryClassLocation")) {
            if (String.class != propertyType)
              throw new NamingException(
                  this.getClass().getName()
                      + " requires a factoryClassLocation property to be a string, "
                      + propertyType.getName()
                      + " is not valid.");
            factoryClassLocation = (String) val;
          }

          if (val == null) {
            RefAddr addMe = new BinaryRefAddr(propertyName, NULL_TOKEN_BYTES);
            refAddrs.add(addMe);
          } else if (Coerce.canCoerce(propertyType)) {
            RefAddr addMe = new StringRefAddr(propertyName, String.valueOf(val));
            refAddrs.add(addMe);
          } else // other Object properties
          {
            RefAddr addMe = null;
            PropertyEditor pe = BeansUtils.findPropertyEditor(pd);
            if (pe != null) {
              pe.setValue(val);
              String textValue = pe.getAsText();
              if (textValue != null) addMe = new StringRefAddr(propertyName, textValue);
            }
            if (addMe == null) // property editor approach failed
            addMe =
                  new BinaryRefAddr(
                      propertyName,
                      SerializableUtils.toByteArray(
                          val, indirector, IndirectPolicy.INDIRECT_ON_EXCEPTION));
            refAddrs.add(addMe);
          }
        } else {
          // 				System.err.println(this.getClass().getName() +
          // 						   ": Skipping " + propertyName + " because it is " + (setter == null ?
          // "read-only." : "write-only."));

          if (logger.isLoggable(MLevel.WARNING))
            logger.warning(
                this.getClass().getName()
                    + ": Skipping "
                    + propertyName
                    + " because it is "
                    + (setter == null ? "read-only." : "write-only."));
        }
      }
      Reference out =
          new Reference(bean.getClass().getName(), factoryClassName, factoryClassLocation);
      for (Iterator ii = refAddrs.iterator(); ii.hasNext(); ) out.add((RefAddr) ii.next());
      return out;
    } catch (Exception e) {
      // e.printStackTrace();
      if (Debug.DEBUG && logger.isLoggable(MLevel.FINE))
        logger.log(MLevel.FINE, "Exception trying to create Reference.", e);

      throw new NamingException("Could not create reference from bean: " + e.toString());
    }
  }
  /*
   * TODO: factor all this convolution out into
   *       C3P0Statement
   */
  Statement createProxyStatement( // final Method cachedStmtProducingMethod,
      // final Object[] cachedStmtProducingMethodArgs,
      final boolean inner_is_cached,
      final Statement innerStmt)
      throws Exception {
    final Set activeResultSets = Collections.synchronizedSet(new HashSet());
    final Connection parentConnection = exposedProxy;

    if (Debug.DEBUG && parentConnection == null) {
      // 		System.err.print("PROBABLE C3P0 BUG -- ");
      // 		System.err.println(this + ": created a proxy Statement when there is no active, exposed
      // proxy Connection???");

      logger.warning(
          "PROBABLE C3P0 BUG -- "
              + this
              + ": created a proxy Statement when there is no active, exposed proxy Connection???");
    }

    // we can use this one wrapper under all circumstances
    // except jdbc3 CallableStatement multiple open ResultSets...
    // avoid object allocation in statement methods where possible.
    final StatementProxyingSetManagedResultSet mainResultSet =
        new StatementProxyingSetManagedResultSet(activeResultSets);

    class WrapperStatementHelper {
      Statement wrapperStmt;
      Statement nakedInner;

      public WrapperStatementHelper(Statement wrapperStmt, Statement nakedInner) {
        this.wrapperStmt = wrapperStmt;
        this.nakedInner = nakedInner;

        if (!inner_is_cached) uncachedActiveStatements.add(wrapperStmt);
      }

      private boolean closeAndRemoveActiveResultSets() {
        return closeAndRemoveResultSets(activeResultSets);
      }

      public ResultSet wrap(ResultSet rs) {
        if (mainResultSet.getInner() == null) {
          mainResultSet.setInner(rs);
          mainResultSet.setProxyStatement(wrapperStmt);
          return mainResultSet;
        } else {
          // for the case of multiple open ResultSets
          StatementProxyingSetManagedResultSet out =
              new StatementProxyingSetManagedResultSet(activeResultSets);
          out.setInner(rs);
          out.setProxyStatement(wrapperStmt);
          return out;
        }
      }

      public void doClose() throws SQLException {
        boolean okay = closeAndRemoveActiveResultSets();

        if (inner_is_cached) // this statement was cached
        scache.checkinStatement(innerStmt);
        else {
          innerStmt.close();
          uncachedActiveStatements.remove(wrapperStmt);
        }

        if (!okay) throw new SQLException("Failed to close an orphaned ResultSet properly.");
      }

      public Object doRawStatementOperation(Method m, Object target, Object[] args)
          throws IllegalAccessException, InvocationTargetException, SQLException {
        if (target == C3P0ProxyStatement.RAW_STATEMENT) target = nakedInner;
        for (int i = 0, len = args.length; i < len; ++i)
          if (args[i] == C3P0ProxyStatement.RAW_STATEMENT) args[i] = nakedInner;

        Object out = m.invoke(target, args);

        if (out instanceof ResultSet) out = wrap((ResultSet) out);

        return out;
      }
    }

    if (innerStmt instanceof CallableStatement) {
      class ProxyCallableStatement extends FilterCallableStatement implements C3P0ProxyStatement {
        WrapperStatementHelper wsh;

        ProxyCallableStatement(CallableStatement is) {
          super(is);
          this.wsh = new WrapperStatementHelper(this, is);
        }

        public Connection getConnection() {
          return parentConnection;
        }

        public ResultSet getResultSet() throws SQLException {
          return wsh.wrap(super.getResultSet());
        }

        public ResultSet getGeneratedKeys() throws SQLException {
          return wsh.wrap(super.getGeneratedKeys());
        }

        public ResultSet executeQuery(String sql) throws SQLException {
          return wsh.wrap(super.executeQuery(sql));
        }

        public ResultSet executeQuery() throws SQLException {
          return wsh.wrap(super.executeQuery());
        }

        public Object rawStatementOperation(Method m, Object target, Object[] args)
            throws IllegalAccessException, InvocationTargetException, SQLException {
          return wsh.doRawStatementOperation(m, target, args);
        }

        public void close() throws SQLException {
          wsh.doClose();
        }
      }

      return new ProxyCallableStatement((CallableStatement) innerStmt);
    } else if (innerStmt instanceof PreparedStatement) {
      class ProxyPreparedStatement extends FilterPreparedStatement implements C3P0ProxyStatement {
        WrapperStatementHelper wsh;

        ProxyPreparedStatement(PreparedStatement ps) {
          super(ps);
          this.wsh = new WrapperStatementHelper(this, ps);
        }

        public Connection getConnection() {
          return parentConnection;
        }

        public ResultSet getResultSet() throws SQLException {
          return wsh.wrap(super.getResultSet());
        }

        public ResultSet getGeneratedKeys() throws SQLException {
          return wsh.wrap(super.getGeneratedKeys());
        }

        public ResultSet executeQuery(String sql) throws SQLException {
          return wsh.wrap(super.executeQuery(sql));
        }

        public ResultSet executeQuery() throws SQLException {
          return wsh.wrap(super.executeQuery());
        }

        public Object rawStatementOperation(Method m, Object target, Object[] args)
            throws IllegalAccessException, InvocationTargetException, SQLException {
          return wsh.doRawStatementOperation(m, target, args);
        }

        public void close() throws SQLException {
          wsh.doClose();
        }
      }

      return new ProxyPreparedStatement((PreparedStatement) innerStmt);
    } else {
      class ProxyStatement extends FilterStatement implements C3P0ProxyStatement {
        WrapperStatementHelper wsh;

        ProxyStatement(Statement s) {
          super(s);
          this.wsh = new WrapperStatementHelper(this, s);
        }

        public Connection getConnection() {
          return parentConnection;
        }

        public ResultSet getResultSet() throws SQLException {
          return wsh.wrap(super.getResultSet());
        }

        public ResultSet getGeneratedKeys() throws SQLException {
          return wsh.wrap(super.getGeneratedKeys());
        }

        public ResultSet executeQuery(String sql) throws SQLException {
          return wsh.wrap(super.executeQuery(sql));
        }

        public Object rawStatementOperation(Method m, Object target, Object[] args)
            throws IllegalAccessException, InvocationTargetException, SQLException {
          return wsh.doRawStatementOperation(m, target, args);
        }

        public void close() throws SQLException {
          wsh.doClose();
        }
      }

      return new ProxyStatement(innerStmt);
    }
  }