Пример #1
0
  static {
    classNamesToConnectionTesters.put(
        C3P0Defaults.connectionTesterClassName(), C3P0Defaults.connectionTester());

    String userManagementCoordinator = C3P0ConfigUtils.getPropsFileConfigProperty(MC_PARAM);
    if (userManagementCoordinator != null) {
      try {
        mc = (ManagementCoordinator) Class.forName(userManagementCoordinator).newInstance();
      } catch (Exception e) {
        if (logger.isLoggable(MLevel.WARNING))
          logger.log(
              MLevel.WARNING,
              "Could not instantiate user-specified ManagementCoordinator "
                  + userManagementCoordinator
                  + ". Using NullManagementCoordinator (c3p0 JMX management disabled!)",
              e);
        mc = new NullManagementCoordinator();
      }
    } else {
      try {
        Class.forName("java.lang.management.ManagementFactory");

        mc =
            (ManagementCoordinator)
                Class.forName("com.mchange.v2.c3p0.management.ActiveManagementCoordinator")
                    .newInstance();
      } catch (Exception e) {
        if (logger.isLoggable(MLevel.INFO))
          logger.log(
              MLevel.INFO, "jdk1.5 management interfaces unavailable... JMX support disabled.", e);
        mc = new NullManagementCoordinator();
      }
    }
  }
  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);
    }
  }
Пример #3
0
  /**
   * Creates a pooled version of an unpooled DataSource using configuration information supplied
   * explicitly by a {@link com.mchange.v2.c3p0.PoolConfig}.
   *
   * @return a DataSource that can be cast to a {@link PooledDataSource} if you are interested in
   *     pool statistics
   * @deprecated if you want to set properties programmatically, please construct a
   *     ComboPooledDataSource and set its properties rather than using PoolConfig
   */
  public static DataSource pooledDataSource(DataSource unpooledDataSource, PoolConfig pcfg)
      throws SQLException {
    try {
      WrapperConnectionPoolDataSource wcpds = new WrapperConnectionPoolDataSource();
      wcpds.setNestedDataSource(unpooledDataSource);

      // set PoolConfig info -- WrapperConnectionPoolDataSource properties
      BeansUtils.overwriteSpecificAccessibleProperties(
          pcfg, wcpds, WRAPPER_CXN_POOL_DATA_SOURCE_OVERWRITE_PROPS);

      PoolBackedDataSource nascent_pbds = new PoolBackedDataSource();
      nascent_pbds.setConnectionPoolDataSource(wcpds);
      BeansUtils.overwriteSpecificAccessibleProperties(
          pcfg, nascent_pbds, POOL_BACKED_DATA_SOURCE_OVERWRITE_PROPS);

      return nascent_pbds;
    }
    // 	catch ( PropertyVetoException e )
    // 	    {
    // 		e.printStackTrace();
    // 		PropertyChangeEvent evt = e.getPropertyChangeEvent();
    // 		throw new SQLException("Illegal value attempted for property " + evt.getPropertyName() + ":
    // " + evt.getNewValue());
    // 	    }
    catch (Exception e) {
      // e.printStackTrace();
      SQLException sqle =
          SqlUtils.toSQLException("Exception configuring pool-backed DataSource: " + e, e);
      if (Debug.DEBUG
          && Debug.TRACE >= Debug.TRACE_MED
          && logger.isLoggable(MLevel.FINE)
          && e != sqle) logger.log(MLevel.FINE, "Converted exception to throwable SQLException", e);
      throw sqle;
    }
  }
Пример #4
0
  public static DataSource pooledDataSource(
      DataSource unpooledDataSource, String configName, Map overrideProps) throws SQLException {
    try {
      WrapperConnectionPoolDataSource wcpds = new WrapperConnectionPoolDataSource(configName);
      wcpds.setNestedDataSource(unpooledDataSource);
      if (overrideProps != null)
        BeansUtils.overwriteAccessiblePropertiesFromMap(
            overrideProps, wcpds, false, null, true, MLevel.WARNING, MLevel.WARNING, false);

      PoolBackedDataSource nascent_pbds = new PoolBackedDataSource(configName);
      nascent_pbds.setConnectionPoolDataSource(wcpds);
      if (overrideProps != null)
        BeansUtils.overwriteAccessiblePropertiesFromMap(
            overrideProps, nascent_pbds, false, null, true, MLevel.WARNING, MLevel.WARNING, false);

      return nascent_pbds;
    }
    // 	catch ( PropertyVetoException e )
    // 	    {
    // 		e.printStackTrace();
    // 		PropertyChangeEvent evt = e.getPropertyChangeEvent();
    // 		throw new SQLException("Illegal value attempted for property " + evt.getPropertyName() + ":
    // " + evt.getNewValue());
    // 	    }
    catch (Exception e) {
      // e.printStackTrace();
      SQLException sqle =
          SqlUtils.toSQLException("Exception configuring pool-backed DataSource: " + e, e);
      if (Debug.DEBUG
          && Debug.TRACE >= Debug.TRACE_MED
          && logger.isLoggable(MLevel.FINE)
          && e != sqle) logger.log(MLevel.FINE, "Converted exception to throwable SQLException", e);
      throw sqle;
    }
  }
 public void attemptUnmanageC3P0Registry() {
   try {
     ObjectName name = new ObjectName(regName);
     if (mbs.isRegistered(name)) {
       mbs.unregisterMBean(name);
       if (logger.isLoggable(MLevel.FINER))
         logger.log(MLevel.FINER, "C3P0Registry mbean unregistered.");
     } else if (logger.isLoggable(MLevel.FINE))
       logger.fine(
           "The C3P0Registry mbean was not found in the registry, so could not be unregistered.");
   } catch (Exception e) {
     if (logger.isLoggable(MLevel.WARNING))
       logger.log(
           MLevel.WARNING,
           "An Exception occurred while trying to unregister the C3P0RegistryManager mBean." + e);
   }
 }
Пример #6
0
 static final ResourcePoolException convertThrowable(String msg, Throwable t) {
   if (Debug.DEBUG) {
     // t.printStackTrace();
     if (logger.isLoggable(MLevel.FINE))
       logger.log(MLevel.FINE, "Converting throwable to ResourcePoolException...", t);
   }
   if (t instanceof ResourcePoolException) return (ResourcePoolException) t;
   else return new ResourcePoolException(msg, t);
 }
Пример #7
0
  public void addStatementEventListener(StatementEventListener sel) {
    if (logger.isLoggable(MLevel.INFO))
      logger.info(
          "Per the JDBC4 spec, "
              + this.getClass().getName()
              + " accepts StatementListeners, but for now there is no circumstance under which they are notified!");

    ses.addStatementEventListener(sel);
  }
Пример #8
0
 private void mbOverrideWarning(String srcType, String srcName) {
   if (warn_of_xml_overrides && logger.isLoggable(MLevel.WARNING))
     logger.log(
         MLevel.WARNING,
         "Configuation defined in "
             + srcType
             + "'"
             + srcName
             + "' overrides all other c3p0 config.");
 }
Пример #9
0
  private void reset(boolean known_resolved_txn) throws SQLException {
    ensureOkay();
    C3P0ImplUtils.resetTxnState(
        physicalConnection,
        forceIgnoreUnresolvedTransactions,
        autoCommitOnClose,
        known_resolved_txn);
    if (isolation_lvl_nondefault) {
      physicalConnection.setTransactionIsolation(dflt_txn_isolation);
      isolation_lvl_nondefault = false;
    }
    if (catalog_nondefault) {
      physicalConnection.setCatalog(dflt_catalog);
      catalog_nondefault = false;
    }
    if (holdability_nondefault) // we don't test if holdability is supported, 'cuz it can never go
                                // nondefault if it's not.
    {
      physicalConnection.setHoldability(dflt_holdability);
      holdability_nondefault = false;
    }

    try {
      physicalConnection.setReadOnly(false);
    } catch (Throwable t) {
      if (logger.isLoggable(MLevel.FINE))
        logger.log(
            MLevel.FINE,
            "A Throwable occurred while trying to reset the readOnly property of our Connection to false!",
            t);
    }

    try {
      if (supports_setTypeMap) physicalConnection.setTypeMap(Collections.EMPTY_MAP);
    } catch (Throwable t) {
      if (logger.isLoggable(MLevel.FINE))
        logger.log(
            MLevel.FINE,
            "A Throwable occurred while trying to reset the typeMap property of our Connection to Collections.EMPTY_MAP!",
            t);
    }
  }
Пример #10
0
  public static SQLException toSQLException(String msg, String sqlState, Throwable t) {
    if (t instanceof SQLException) {
      if (Debug.DEBUG && Debug.TRACE == Debug.TRACE_MAX && logger.isLoggable(MLevel.FINER)) {
        SQLException s = (SQLException) t;
        StringBuffer tmp = new StringBuffer(255);
        tmp.append("Attempted to convert SQLException to SQLException. Leaving it alone.");
        tmp.append(" [SQLState: ");
        tmp.append(s.getSQLState());
        tmp.append("; errorCode: ");
        tmp.append(s.getErrorCode());
        tmp.append(']');
        if (msg != null) tmp.append(" Ignoring suggested message: '" + msg + "'.");
        logger.log(MLevel.FINER, tmp.toString(), t);

        SQLException s2 = s;
        while ((s2 = s2.getNextException()) != null)
          logger.log(MLevel.FINER, "Nested SQLException or SQLWarning: ", s2);
      }
      return (SQLException) t;
    } else {
      if (Debug.DEBUG) {
        // t.printStackTrace();
        if (logger.isLoggable(MLevel.FINE))
          logger.log(MLevel.FINE, "Converting Throwable to SQLException...", t);
      }

      if (msg == null)
        msg = "An SQLException was provoked by the following failure: " + t.toString();
      if (VersionUtils.isAtLeastJavaVersion14()) {
        SQLException out = new SQLException(msg);
        out.initCause(t);
        return out;
      } else
        return new SQLException(
            msg
                + System.getProperty("line.separator")
                + "[Cause: "
                + ThrowableUtils.extractStackTrace(t)
                + ']',
            sqlState);
    }
  }
Пример #11
0
 public void attemptUnmanagePooledDataSource(PooledDataSource pds) {
   String nameStr = getPdsObjectNameStr(pds);
   try {
     ObjectName name = new ObjectName(nameStr);
     if (mbs.isRegistered(name)) {
       mbs.unregisterMBean(name);
       if (logger.isLoggable(MLevel.FINER))
         logger.log(MLevel.FINER, "MBean: " + nameStr + " unregistered.");
     } else if (logger.isLoggable(MLevel.FINE))
       logger.fine(
           "The mbean "
               + nameStr
               + " was not found in the registry, so could not be unregistered.");
   } catch (Exception e) {
     if (logger.isLoggable(MLevel.WARNING))
       logger.log(
           MLevel.WARNING,
           "An Exception occurred while unregistering mBean. [" + nameStr + "] " + e);
   }
 }
 private synchronized C3P0PooledConnectionPoolManager getPoolManager() throws SQLException {
   if (poolManager == null) {
     ConnectionPoolDataSource cpds = assertCpds();
     poolManager =
         new C3P0PooledConnectionPoolManager(
             cpds, null, null, this.getNumHelperThreads(), this.getIdentityToken());
     if (logger.isLoggable(MLevel.INFO))
       logger.info(
           "Initializing c3p0 pool... "
               + this.toString() /* + "; using pool manager: " + poolManager */);
   }
   return poolManager;
 }
  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);
    }
  }
Пример #14
0
 // must be called from a static sync'ed method
 private static void banner() {
   if (!banner_printed) {
     if (logger.isLoggable(MLevel.INFO))
       logger.info(
           "Initializing c3p0-"
               + C3P0Substitutions.VERSION
               + " [built "
               + C3P0Substitutions.TIMESTAMP
               + "; debug? "
               + C3P0Substitutions.DEBUG
               + "; trace: "
               + C3P0Substitutions.TRACE
               + ']');
     banner_printed = true;
   }
 }
  public synchronized void close() {
    resetPoolManager();
    is_closed = true;

    C3P0Registry.markClosed(this);

    if (Debug.DEBUG && Debug.TRACE == Debug.TRACE_MAX && logger.isLoggable(MLevel.FINEST)) {
      logger.log(
          MLevel.FINEST,
          this.getClass().getName()
              + '@'
              + Integer.toHexString(System.identityHashCode(this))
              + " has been closed. ",
          new Exception("DEBUG STACK TRACE for PoolBackedDataSource.close()."));
    }
  }
 protected void initializeNamedConfig(String configName) {
   try {
     if (configName != null) {
       C3P0Config.bindNamedConfigToBean(this, configName);
       if (this.getDataSourceName()
           .equals(this.getIdentityToken())) // dataSourceName has not been specified in config
       this.setDataSourceName(configName);
     }
   } catch (Exception e) {
     if (logger.isLoggable(MLevel.WARNING))
       logger.log(
           MLevel.WARNING,
           "Error binding PoolBackedDataSource to named-config '"
               + configName
               + "'. Some default-config values may be used.",
           e);
   }
 }
Пример #17
0
 public static ConnectionTester getConnectionTester(String className) {
   try {
     ConnectionTester out = (ConnectionTester) classNamesToConnectionTesters.get(className);
     if (out == null) {
       out = (ConnectionTester) Class.forName(className).newInstance();
       classNamesToConnectionTesters.put(className, out);
     }
     return out;
   } catch (Exception e) {
     if (logger.isLoggable(MLevel.WARNING))
       logger.log(
           MLevel.WARNING,
           "Could not create for find ConnectionTester with class name '"
               + className
               + "'. Using default.",
           e);
     return C3P0Defaults.connectionTester();
   }
 }
Пример #18
0
 synchronized void closeMaybeCheckedOut(boolean checked_out) throws SQLException {
   if (checked_out) {
     // reset transaction state
     try {
       C3P0ImplUtils.resetTxnState(
           physicalConnection, forceIgnoreUnresolvedTransactions, autoCommitOnClose, false);
     } catch (Exception e) {
       if (logger.isLoggable(MLevel.FINER))
         logger.log(
             MLevel.FINER,
             "Failed to reset the transaction state of  "
                 + physicalConnection
                 + "just prior to close(). "
                 + "Only relevant at all if this was a Connection being forced close()ed midtransaction.",
             e);
     }
   }
   close(false);
 }
Пример #19
0
 public static ConnectionCustomizer getConnectionCustomizer(String className) throws SQLException {
   if (className == null) return null;
   else {
     try {
       ConnectionCustomizer out =
           (ConnectionCustomizer) classNamesToConnectionCustomizers.get(className);
       if (out == null) {
         out = (ConnectionCustomizer) Class.forName(className).newInstance();
         classNamesToConnectionCustomizers.put(className, out);
       }
       return out;
     } catch (Exception e) {
       if (logger.isLoggable(MLevel.WARNING))
         logger.log(
             MLevel.WARNING,
             "Could not create for find ConnectionCustomizer with class name '" + className + "'.",
             e);
       throw SqlUtils.toSQLException(e);
     }
   }
 }
Пример #20
0
 // MT: called only from inner(), effectively synchrtonized
 private DataSource dereference() throws SQLException {
   Object jndiName = this.getJndiName();
   Hashtable jndiEnv = this.getJndiEnv();
   try {
     InitialContext ctx;
     if (jndiEnv != null) ctx = new InitialContext(jndiEnv);
     else ctx = new InitialContext();
     if (jndiName instanceof String) return (DataSource) ctx.lookup((String) jndiName);
     else if (jndiName instanceof Name) return (DataSource) ctx.lookup((Name) jndiName);
     else
       throw new SQLException(
           "Could not find ConnectionPoolDataSource with " + "JNDI name: " + jndiName);
   } catch (NamingException e) {
     // e.printStackTrace();
     if (logger.isLoggable(MLevel.WARNING))
       logger.log(
           MLevel.WARNING,
           "An Exception occurred while trying to look up a target DataSource via JNDI!",
           e);
     throw SqlUtils.toSQLException(e);
   }
 }
Пример #21
0
  public void attemptManagePooledDataSource(PooledDataSource pds) {
    String name = getPdsObjectNameStr(pds);
    try {
      // 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
                + "] "
                + "[c3p0 will still functioning normally, but management via JMX may not be possible.]",
            e);
    }
  }
Пример #22
0
  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());
    }
  }