/** * Checks if player is registered with the given password * * @param p The Player * @param pass The Password * @return true: Player registered and correct password, false: Anything went wrong, or no access */ public boolean b(Player p, String pass) { if (!loaded) { MLog.e("(MAuth) Can't do check on " + p.getName() + ": HashMaps are not loaded."); return false; } if (!isRegistered(p.getName())) { MLog.e("(MAuth) Can't check player " + p.getName() + ": Never registered."); } return d(p.getName()) .equals( MCrypt.getHash( 1000, pass, "i8765rtghjklo987654redfghjukiloi8u7z654e34r56789ikjhgf87654rfghzjui876tghjkioi8u7z6trer456z7uj")); }
/** * Registers a new player. * * @param p The Player * @param pass The password * @return SUCCESS: All did fine, ERROR: Something went wrong. Check log. */ public MResult register(Player p, String pass) { if (c.contains(p.getName()) && !b(p, pass)) return MResult.RES_NOACCESS; if (a.containsKey(p.getName())) return MResult.RES_ALREADY; if (c(p, pass)) return MResult.RES_SUCCESS; MLog.e("Something went wrong while registering new player :("); return MResult.RES_ERROR; }
public static void saveHashes(String path, HashMap<String, String> hashes) { if (path.equalsIgnoreCase("")) { MLog.e("Can't save Hashes to not given file."); return; } File iFile = new File(path); FileOutputStream fos = null; ObjectOutputStream oos = null; if (!iFile.exists()) { MLog.e("Can't save Hashes to not existing file: " + path); return; } if (hashes == null) MLog.w("Writing 'null' to hash database means clearing."); try { fos = new FileOutputStream(iFile); oos = new ObjectOutputStream(fos); } catch (FileNotFoundException fnfex) { MLog.e("Can't save Hashes to not existing file: " + path); return; } catch (IOException ioex) { MLog.e("Can't create ObjectOutputStream while saving Hashes from " + path); return; } try { oos.writeObject(hashes); } catch (IOException ioex) { MLog.e("Error writing Stream in file: " + path); return; } // catch (ClassNotFoundException cnfex) { MLog.e("Error writing Stream in file // (ClassNotFoundException): " + path); return; } MLog.d("Saved Hashmap successfully"); return; }
private boolean c(Player p, String pass) { if (!loaded) { MLog.e("(MAuth) Can't register player " + p.getName() + ": HashMaps are not initialized."); return false; } if (isRegistered(p.getName())) { MLog.e("(MAuth) Can't register player " + p.getName()); return false; } a.put( p.getName(), MCrypt.getHash( 1000, pass, "i8765rtghjklo987654redfghjukiloi8u7z654e34r56789ikjhgf87654rfghzjui876tghjkioi8u7z6trer456z7uj")); MCrypt.saveHashes(b.getAbsolutePath(), a); return true; }
public static String getHash(int iterationNb, String password, String salt) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(salt.getBytes()); byte[] input; try { input = digest.digest(password.getBytes("UTF-8")); for (int i = 0; i < iterationNb; i++) { digest.reset(); input = digest.digest(input); } return new String(input); } catch (UnsupportedEncodingException ex) { MLog.e("Failure while doing crypt algorithm."); return ""; } } catch (NoSuchAlgorithmException ex) { MLog.e("Failure while doing crypt algorithm."); return ""; } }
public MAuthorizer(String a) { try { b = new File(a); this.a = new HashMap<>(); this.c = new ArrayList<>(); if (!b.exists()) { b.mkdirs(); b.createNewFile(); MCrypt.saveHashes(a, this.a); } } catch (IOException ioex) { MLog.e("(MAuth) Authorization file invalid."); } }
public static HashMap<String, String> loadHashes(String path) { if (path.equalsIgnoreCase("")) { MLog.e("Can't load Hases from not given file"); return null; } File iFile = new File(path); FileInputStream fis = null; ObjectInputStream ois = null; if (!iFile.exists()) { MLog.e("Can't load Hashes from not existing file: " + path); return null; } try { fis = new FileInputStream(iFile); ois = new ObjectInputStream(fis); } catch (FileNotFoundException fnfex) { MLog.e("Can't load Hashes from not existing file: " + path); return null; } catch (EOFException eofex) { HashMap<String, String> tres = new HashMap<String, String>(); saveHashes(path, tres); return tres; } catch (IOException ioex) { MLog.e("Can't create ObjectInputStream while loading Hashes from " + path); ioex.printStackTrace(); return null; } Object o = null; try { o = ois.readObject(); } catch (IOException ioex) { MLog.e("Error reading Stream in file: " + path); return null; } catch (ClassNotFoundException cnfex) { MLog.e("Error reading Stream in file (ClassNotFoundException): " + path); return null; } if (!(o instanceof HashMap)) { MLog.e("Invalid hash file at: " + path); return null; } MLog.d("Loaded Hashmap successfully"); return (HashMap<String, String>) o; }
final class ResourcePoolUtils { static final MLogger logger = MLog.getLogger(ResourcePoolUtils.class); 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); } static final ResourcePoolException convertThrowable(Throwable t) { return convertThrowable("Ouch! " + t.toString(), t); } }
/** * A simple factory class for creating DataSources. Generally, users will call * <tt>DataSources.unpooledDataSource()</tt> to get a basic DataSource, and then get a pooled * version by calling <tt>DataSources.pooledDataSource()</tt>. * * <p>Most users will not need to worry about configuration details. If you want to use a * PreparedStatement cache, be sure to call the version of <tt>DataSources.pooledDataSource()</tt> * that accepts a <tt>statement_cache_size</tt> parameter, and set that to be a number (much) * greater than zero. (For maximum performance, you would set this to be several times the number * kinds of PreparedStatements you expect your application to use.) * * <p>For those interested in detailed configuration, note that c3p0 pools can be configured by * explicit method calls on PoolConfig objects, by defining System properties, or by defining a * <tt>c3p0.properties</tt> file in your resource path. See {@link com.mchange.v2.c3p0.PoolConfig} * for details. */ public final class DataSources { static final MLogger logger = MLog.getLogger(DataSources.class); static final Set WRAPPER_CXN_POOL_DATA_SOURCE_OVERWRITE_PROPS; // 22 -- includes factory class location static final Set POOL_BACKED_DATA_SOURCE_OVERWRITE_PROPS; // 2 -- includes factory class location, excludes // pool-owner id token static { // As of c3p0-0.9.1 // // This list is no longer updated, as the PoolConfig approach to setting up DataSources // is now deprecated. (This was getting to be hard to maintain as new config properties // were added.) String[] props = new String[] { "checkoutTimeout", // 1 "acquireIncrement", // 2 "acquireRetryAttempts", // 3 "acquireRetryDelay", // 4 "autoCommitOnClose", // 5 "connectionTesterClassName", // 6 "forceIgnoreUnresolvedTransactions", // 7 "idleConnectionTestPeriod", // 8 "initialPoolSize", // 9 "maxIdleTime", // 10 "maxPoolSize", // 11 "maxStatements", // 12 "maxStatementsPerConnection", // 13 "minPoolSize", // 14 "propertyCycle", // 15 "breakAfterAcquireFailure", // 16 "testConnectionOnCheckout", // 17 "testConnectionOnCheckin", // 18 "usesTraditionalReflectiveProxies", // 19 "preferredTestQuery", // 20 "automaticTestTable", // 21 "factoryClassLocation" // 22 }; WRAPPER_CXN_POOL_DATA_SOURCE_OVERWRITE_PROPS = Collections.unmodifiableSet(new HashSet(Arrays.asList(props))); // As of c3p0-0.9.1 // // This list is no longer updated, as the PoolConfig approach to setting up DataSources // is now deprecated. (This was getting to be hard to maintain as new config properties // were added.) props = new String[] {"numHelperThreads", "factoryClassLocation"}; POOL_BACKED_DATA_SOURCE_OVERWRITE_PROPS = Collections.unmodifiableSet(new HashSet(Arrays.asList(props))); } /** * Defines an unpooled DataSource all of whose paramateres (especially jdbcUrl) should be set in * config files. */ public static DataSource unpooledDataSource() throws SQLException { DriverManagerDataSource out = new DriverManagerDataSource(); return out; } public static DataSource unpooledDataSource(String jdbcUrl) throws SQLException { DriverManagerDataSource out = new DriverManagerDataSource(); out.setJdbcUrl(jdbcUrl); return out; } /** * Defines an unpooled DataSource on the specified JDBC URL, authenticating with a username and * password. */ public static DataSource unpooledDataSource(String jdbcUrl, String user, String password) throws SQLException { Properties props = new Properties(); props.put(SqlUtils.DRIVER_MANAGER_USER_PROPERTY, user); props.put(SqlUtils.DRIVER_MANAGER_PASSWORD_PROPERTY, password); return unpooledDataSource(jdbcUrl, props); } /** * Defines an unpooled DataSource on the specified JDBC URL. * * @param driverProps the usual DriverManager properties for your JDBC driver (e.g. "user" and * "password" for all drivers that support authentication) * @see java.sql.DriverManager */ public static DataSource unpooledDataSource(String jdbcUrl, Properties driverProps) throws SQLException { DriverManagerDataSource out = new DriverManagerDataSource(); out.setJdbcUrl(jdbcUrl); out.setProperties(driverProps); return out; } /** * Creates a pooled version of an unpooled DataSource using default configuration information. * * <p><b>NOTE:</b> By default, statement pooling is turned off, because for simple databases that * do not pre-parse and optimize PreparedStatements, statement caching is a net performance loss. * But if your database <i>does</i> optimize PreparedStatements you'll want to turn * StatementCaching on via {@link #pooledDataSource(javax.sql.DataSource, int)}. * * @return a DataSource that can be cast to a {@link PooledDataSource} if you are interested in * pool statistics */ public static DataSource pooledDataSource(DataSource unpooledDataSource) throws SQLException { return pooledDataSource(unpooledDataSource, null, (Map) null); } /** * Creates a pooled version of an unpooled DataSource using default configuration information and * the specified startement cache size. Use a value greater than zero to turn statement caching * on. * * @return a DataSource that can be cast to a {@link PooledDataSource} if you are interested in * pool statistics */ public static DataSource pooledDataSource(DataSource unpooledDataSource, int statement_cache_size) throws SQLException { // PoolConfig pcfg = new PoolConfig(); // pcfg.setMaxStatements( statement_cache_size ); Map overrideProps = new HashMap(); overrideProps.put("maxStatements", new Integer(statement_cache_size)); return pooledDataSource(unpooledDataSource, null, overrideProps); } /** * 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; } } /* public static DataSource pooledDataSource( DataSource unpooledDataSource, String overrideDefaultUser, String overrideDefaultPassword ) throws SQLException { Map overrideProps; if (overrideDefaultUser != null) { overrideProps = new HashMap(); overrideProps.put( "overrideDefaultUser", overrideDefaultUser ); overrideProps.put( "overrideDefaultPassword", overrideDefaultPassword ); } else overrideProps = null; return pooledDataSource( unpooledDataSource, null, overrideProps ); } */ public static DataSource pooledDataSource(DataSource unpooledDataSource, String configName) throws SQLException { return pooledDataSource(unpooledDataSource, configName, null); } public static DataSource pooledDataSource(DataSource unpooledDataSource, Map overrideProps) throws SQLException { return pooledDataSource(unpooledDataSource, null, overrideProps); } 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; } } /** * Creates a pooled version of an unpooled DataSource using configuration information supplied * explicitly by a Java Properties object. * * @return a DataSource that can be cast to a {@link PooledDataSource} if you are interested in * pool statistics * @see com.mchange.v2.c3p0.PoolConfig */ public static DataSource pooledDataSource(DataSource unpooledDataSource, Properties props) throws SQLException { // return pooledDataSource( unpooledDataSource, new PoolConfig( props ) ); Properties peeledProps = new Properties(); for (Enumeration e = props.propertyNames(); e.hasMoreElements(); ) { String propKey = (String) e.nextElement(); String propVal = props.getProperty(propKey); String peeledKey = (propKey.startsWith("c3p0.") ? propKey.substring(5) : propKey); peeledProps.put(peeledKey, propVal); } return pooledDataSource(unpooledDataSource, null, peeledProps); } /** * Immediately releases resources (Threads and database Connections) that are held by a C3P0 * DataSource. * * <p>Only DataSources created by the poolingDataSource() method hold any non-memory resources. * Calling this method on unpooled DataSources is effectively a no-op. * * <p>You can safely presume that destroying a pooled DataSource that is wrapped around another * DataSource created by this library destroys both the outer and the wrapped DataSource. There is * no reason to hold a reference to a nested DataSource in order to explicitly destroy it. * * @see com.mchange.v2.c3p0.PoolConfig */ public static void destroy(DataSource pooledDataSource) throws SQLException { destroy(pooledDataSource, false); } /** * @deprecated forceDestroy() is no longer meaningful, as a set of pools is now directly * associated with a DataSource, and not potentially shared. (This simplification was made * possible by canonicalization of JNDI-looked-up DataSources within a virtual machine.) Just * use DataSources.destroy(). * @see #destroy */ public static void forceDestroy(DataSource pooledDataSource) throws SQLException { destroy(pooledDataSource, true); } private static void destroy(DataSource pooledDataSource, boolean force) throws SQLException { if (pooledDataSource instanceof PoolBackedDataSource) { ConnectionPoolDataSource cpds = ((PoolBackedDataSource) pooledDataSource).getConnectionPoolDataSource(); if (cpds instanceof WrapperConnectionPoolDataSource) destroy(((WrapperConnectionPoolDataSource) cpds).getNestedDataSource(), force); } if (pooledDataSource instanceof PooledDataSource) ((PooledDataSource) pooledDataSource).close(force); } private DataSources() {} }
/** * Tests if a Element <code>element</code> is valid for the <code>MSet</code>. * * @param element * @return boolean */ public static boolean isMatch(Element element) { if (!URelaxer2.isTargetElement(element, "http://www.w3.org/1998/Math/MathML", "set")) { return (false); } RStack target = new RStack(element); Element child; while (!target.isEmptyElement()) { if (MCi.isMatchHungry(target)) { } else if (MCn.isMatchHungry(target)) { } else if (MApply.isMatchHungry(target)) { } else if (MReln.isMatchHungry(target)) { } else if (MLambda.isMatchHungry(target)) { } else if (MCondition.isMatchHungry(target)) { } else if (MDeclare.isMatchHungry(target)) { } else if (MSep.isMatchHungry(target)) { } else if (MSemantics.isMatchHungry(target)) { } else if (MAnnotation.isMatchHungry(target)) { } else if (MAnnotationXml.isMatchHungry(target)) { } else if (MInterval.isMatchHungry(target)) { } else if (MList.isMatchHungry(target)) { } else if (MMatrix.isMatchHungry(target)) { } else if (MMatrixrow.isMatchHungry(target)) { } else if (MSet.isMatchHungry(target)) { } else if (MVector.isMatchHungry(target)) { } else if (MLowlimit.isMatchHungry(target)) { } else if (MUplimit.isMatchHungry(target)) { } else if (MBvar.isMatchHungry(target)) { } else if (MDegree.isMatchHungry(target)) { } else if (MLogbase.isMatchHungry(target)) { } else if (MInverse.isMatchHungry(target)) { } else if (MIdent.isMatchHungry(target)) { } else if (MAbs.isMatchHungry(target)) { } else if (MConjugate.isMatchHungry(target)) { } else if (MExp.isMatchHungry(target)) { } else if (MFactorial.isMatchHungry(target)) { } else if (MNot.isMatchHungry(target)) { } else if (MLn.isMatchHungry(target)) { } else if (MSin.isMatchHungry(target)) { } else if (MCos.isMatchHungry(target)) { } else if (MTan.isMatchHungry(target)) { } else if (MSec.isMatchHungry(target)) { } else if (MCsc.isMatchHungry(target)) { } else if (MCot.isMatchHungry(target)) { } else if (MSinh.isMatchHungry(target)) { } else if (MCosh.isMatchHungry(target)) { } else if (MTanh.isMatchHungry(target)) { } else if (MSech.isMatchHungry(target)) { } else if (MCsch.isMatchHungry(target)) { } else if (MCoth.isMatchHungry(target)) { } else if (MArcsin.isMatchHungry(target)) { } else if (MArccos.isMatchHungry(target)) { } else if (MArctan.isMatchHungry(target)) { } else if (MDeterminant.isMatchHungry(target)) { } else if (MTranspose.isMatchHungry(target)) { } else if (MQuotient.isMatchHungry(target)) { } else if (MDivide.isMatchHungry(target)) { } else if (MPower.isMatchHungry(target)) { } else if (MRem.isMatchHungry(target)) { } else if (MImplies.isMatchHungry(target)) { } else if (MSetdiff.isMatchHungry(target)) { } else if (MFn.isMatchHungry(target)) { } else if (MCompose.isMatchHungry(target)) { } else if (MPlus.isMatchHungry(target)) { } else if (MTimes.isMatchHungry(target)) { } else if (MMax.isMatchHungry(target)) { } else if (MMin.isMatchHungry(target)) { } else if (MGcd.isMatchHungry(target)) { } else if (MAnd.isMatchHungry(target)) { } else if (MOr.isMatchHungry(target)) { } else if (MXor.isMatchHungry(target)) { } else if (MUnion.isMatchHungry(target)) { } else if (MIntersect.isMatchHungry(target)) { } else if (MMean.isMatchHungry(target)) { } else if (MSdev.isMatchHungry(target)) { } else if (MVariance.isMatchHungry(target)) { } else if (MMedian.isMatchHungry(target)) { } else if (MMode.isMatchHungry(target)) { } else if (MSelector.isMatchHungry(target)) { } else if (MRoot.isMatchHungry(target)) { } else if (MMinus.isMatchHungry(target)) { } else if (MLog.isMatchHungry(target)) { } else if (MInt.isMatchHungry(target)) { } else if (MDiff.isMatchHungry(target)) { } else if (MPartialdiff.isMatchHungry(target)) { } else if (MSum.isMatchHungry(target)) { } else if (MProduct.isMatchHungry(target)) { } else if (MLimit.isMatchHungry(target)) { } else if (MMoment.isMatchHungry(target)) { } else if (MExists.isMatchHungry(target)) { } else if (MForall.isMatchHungry(target)) { } else if (MNeq.isMatchHungry(target)) { } else if (MIn.isMatchHungry(target)) { } else if (MNotin.isMatchHungry(target)) { } else if (MNotsubset.isMatchHungry(target)) { } else if (MNotprsubset.isMatchHungry(target)) { } else if (MTendsto.isMatchHungry(target)) { } else if (MEq.isMatchHungry(target)) { } else if (MLeq.isMatchHungry(target)) { } else if (MLt.isMatchHungry(target)) { } else if (MGeq.isMatchHungry(target)) { } else if (MGt.isMatchHungry(target)) { } else if (MSubset.isMatchHungry(target)) { } else if (MPrsubset.isMatchHungry(target)) { } else if (MMi.isMatchHungry(target)) { } else if (MMn.isMatchHungry(target)) { } else if (MMo.isMatchHungry(target)) { } else if (MMtext.isMatchHungry(target)) { } else if (MMs.isMatchHungry(target)) { } else if (MMspace.isMatchHungry(target)) { } else if (MMrow.isMatchHungry(target)) { } else if (MMfrac.isMatchHungry(target)) { } else if (MMsqrt.isMatchHungry(target)) { } else if (MMroot.isMatchHungry(target)) { } else if (MMstyle.isMatchHungry(target)) { } else if (MMerror.isMatchHungry(target)) { } else if (MMpadded.isMatchHungry(target)) { } else if (MMphantom.isMatchHungry(target)) { } else if (MMfenced.isMatchHungry(target)) { } else if (MMsub.isMatchHungry(target)) { } else if (MMsup.isMatchHungry(target)) { } else if (MMsubsup.isMatchHungry(target)) { } else if (MMunder.isMatchHungry(target)) { } else if (MMover.isMatchHungry(target)) { } else if (MMunderover.isMatchHungry(target)) { } else if (MMmultiscripts.isMatchHungry(target)) { } else if (MMtable.isMatchHungry(target)) { } else if (MMtr.isMatchHungry(target)) { } else if (MMtd.isMatchHungry(target)) { } else if (MMaligngroup.isMatchHungry(target)) { } else if (MMalignmark.isMatchHungry(target)) { } else if (MMaction.isMatchHungry(target)) { } else { break; } } if (!target.isEmptyElement()) { return (false); } return (true); }
/** Loads all hashes from passwort file */ public void a() { if (loaded) MLog.w("(MAuth) Loading again from Hashmap file... means: Reload without saving!"); if ((a = MCrypt.loadHashes(b.getAbsolutePath())) == null) a = new HashMap<>(); // MLog.d("(MAuth) Releasing MAuthorizer.a"); loaded = true; }
public final class C3P0PooledConnection extends AbstractC3P0PooledConnection { static final MLogger logger = MLog.getLogger(C3P0PooledConnection.class); static final Class[] PROXY_CTOR_ARGS = new Class[] {InvocationHandler.class}; static final Constructor CON_PROXY_CTOR; static final Method RS_CLOSE_METHOD; static final Method STMT_CLOSE_METHOD; static final Object[] CLOSE_ARGS; static final Set OBJECT_METHODS; /** @deprecated use or rewrite in terms of ReflectUtils.findProxyConstructor() */ private static Constructor createProxyConstructor(Class intfc) throws NoSuchMethodException { Class[] proxyInterfaces = new Class[] {intfc}; Class proxyCl = Proxy.getProxyClass(C3P0PooledConnection.class.getClassLoader(), proxyInterfaces); return proxyCl.getConstructor(PROXY_CTOR_ARGS); } static { try { CON_PROXY_CTOR = createProxyConstructor(ProxyConnection.class); Class[] argClasses = new Class[0]; RS_CLOSE_METHOD = ResultSet.class.getMethod("close", argClasses); STMT_CLOSE_METHOD = Statement.class.getMethod("close", argClasses); CLOSE_ARGS = new Object[0]; OBJECT_METHODS = Collections.unmodifiableSet(new HashSet(Arrays.asList(Object.class.getMethods()))); } catch (Exception e) { // e.printStackTrace(); logger.log( MLevel.SEVERE, "An Exception occurred in static initializer of" + C3P0PooledConnection.class.getName(), e); throw new InternalError( "Something is very wrong, or this is a pre 1.3 JVM." + "We cannot set up dynamic proxies and/or methods!"); } } // MT: post-constructor constants final ConnectionTester connectionTester; final boolean autoCommitOnClose; final boolean forceIgnoreUnresolvedTransactions; final boolean supports_setTypeMap; final boolean supports_setHoldability; final int dflt_txn_isolation; final String dflt_catalog; final int dflt_holdability; // MT: thread-safe final ConnectionEventSupport ces = new ConnectionEventSupport(this); final StatementEventSupport ses = new StatementEventSupport(this); // MT: threadsafe, but reassigned (on close) volatile Connection physicalConnection; volatile Exception invalidatingException = null; // MT: threadsafe, but reassigned, and a read + reassignment must happen // atomically. protected by this' lock. ProxyConnection exposedProxy; // MT: protected by this' lock int connection_status = ConnectionTester.CONNECTION_IS_OKAY; /* * contains all unclosed Statements not managed by a StatementCache * associated with the physical connection * * MT: protected by its own lock, not reassigned */ final Set uncachedActiveStatements = Collections.synchronizedSet(new HashSet()); // MT: Thread-safe, assigned volatile GooGooStatementCache scache; volatile boolean isolation_lvl_nondefault = false; volatile boolean catalog_nondefault = false; volatile boolean holdability_nondefault = false; public C3P0PooledConnection( Connection con, ConnectionTester connectionTester, boolean autoCommitOnClose, boolean forceIgnoreUnresolvedTransactions, ConnectionCustomizer cc, String pdsIdt) throws SQLException { try { if (cc != null) cc.onAcquire(con, pdsIdt); } catch (Exception e) { throw SqlUtils.toSQLException(e); } this.physicalConnection = con; this.connectionTester = connectionTester; this.autoCommitOnClose = autoCommitOnClose; this.forceIgnoreUnresolvedTransactions = forceIgnoreUnresolvedTransactions; this.supports_setTypeMap = C3P0ImplUtils.supportsMethod(con, "setTypeMap", new Class[] {Map.class}); this.supports_setHoldability = C3P0ImplUtils.supportsMethod(con, "setHoldability", new Class[] {int.class}); this.dflt_txn_isolation = con.getTransactionIsolation(); this.dflt_catalog = con.getCatalog(); this.dflt_holdability = (supports_setHoldability ? con.getHoldability() : ResultSet.CLOSE_CURSORS_AT_COMMIT); } // used by C3P0PooledConnectionPool Connection getPhysicalConnection() { return physicalConnection; } boolean isClosed() throws SQLException { return (physicalConnection == null); } void initStatementCache(GooGooStatementCache scache) { this.scache = scache; } // DEBUG // Exception origGet = null; // 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(); } } // must be called from sync'ed method to protecte // exposedProxy private Connection getCreateNewConnection() throws SQLException { try { // DEBUG // origGet = new Exception("[DOUBLE_GET_TESTER] -- Orig Get"); ensureOkay(); /* * we reset the physical connection when we close an exposed proxy * no need to do it again when we create one */ // reset(); return (exposedProxy = createProxyConnection()); } catch (SQLException e) { throw e; } catch (Exception e) { // e.printStackTrace(); logger.log(MLevel.WARNING, "Failed to acquire connection!", e); throw new SQLException("Failed to acquire connection!"); } } public void closeAll() throws SQLException { if (scache != null) scache.closeAll(physicalConnection); } public void close() throws SQLException { this.close(false); } 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); } // TODO: factor out repetitive debugging code private synchronized void close(boolean known_invalid) throws SQLException { // System.err.println("Closing " + this); if (physicalConnection != null) { try { StringBuffer debugOnlyLog = null; if (Debug.DEBUG && known_invalid) { debugOnlyLog = new StringBuffer(); debugOnlyLog.append("[ exceptions: "); } Exception exc = cleanupUncachedActiveStatements(); if (Debug.DEBUG && exc != null) { if (known_invalid) debugOnlyLog.append(exc.toString() + ' '); else logger.log( MLevel.WARNING, "An exception occurred while cleaning up uncached active Statements.", exc); // exc.printStackTrace(); } try { // we've got to use silentClose() rather than close() here, // 'cuz if there's still an exposedProxy (say a user forgot to // close his Connection) before we close, and we use regular (loud) // close, we will try to check this dead or dying PooledConnection // back into the pool. We only want to do this when close is called // on user proxies, and the underlying PooledConnection might still // be good. The PooledConnection itself should only be closed by the // pool. if (exposedProxy != null) exposedProxy.silentClose(known_invalid); } catch (Exception e) { if (Debug.DEBUG) { if (known_invalid) debugOnlyLog.append(e.toString() + ' '); else logger.log(MLevel.WARNING, "An exception occurred.", exc); // e.printStackTrace(); } exc = e; } try { this.closeAll(); } catch (Exception e) { if (Debug.DEBUG) { if (known_invalid) debugOnlyLog.append(e.toString() + ' '); else logger.log(MLevel.WARNING, "An exception occurred.", exc); // e.printStackTrace(); } exc = e; } try { physicalConnection.close(); } catch (Exception e) { if (Debug.DEBUG) { if (known_invalid) debugOnlyLog.append(e.toString() + ' '); else logger.log(MLevel.WARNING, "An exception occurred.", exc); e.printStackTrace(); } exc = e; } if (exc != null) { if (known_invalid) { debugOnlyLog.append(" ]"); if (Debug.DEBUG) { // System.err.print("[DEBUG]" + this + ": while closing a PooledConnection known // to be invalid, "); // System.err.println(" some exceptions occurred. This is probably not a // problem:"); // System.err.println( debugOnlyLog.toString() ); logger.fine( this + ": while closing a PooledConnection known to be invalid, " + " some exceptions occurred. This is probably not a problem: " + debugOnlyLog.toString()); } } else throw new SQLException( "At least one error occurred while attempting " + "to close() the PooledConnection: " + exc); } if (Debug.TRACE == Debug.TRACE_MAX) logger.fine("C3P0PooledConnection closed. [" + this + ']'); // System.err.println("C3P0PooledConnection closed. [" + this + ']'); } finally { physicalConnection = null; } } } public void addConnectionEventListener(ConnectionEventListener listener) { ces.addConnectionEventListener(listener); } public void removeConnectionEventListener(ConnectionEventListener listener) { ces.removeConnectionEventListener(listener); } 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); } public void removeStatementEventListener(StatementEventListener sel) { ses.removeStatementEventListener(sel); } private void reset() throws SQLException { reset(false); } 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); } } boolean closeAndRemoveResultSets(Set rsSet) { boolean okay = true; synchronized (rsSet) { for (Iterator ii = rsSet.iterator(); ii.hasNext(); ) { ResultSet rs = (ResultSet) ii.next(); try { rs.close(); } catch (SQLException e) { if (Debug.DEBUG) logger.log(MLevel.WARNING, "An exception occurred while cleaning up a ResultSet.", e); // e.printStackTrace(); okay = false; } finally { ii.remove(); } } } return okay; } void ensureOkay() throws SQLException { if (physicalConnection == null) throw new SQLException( invalidatingException == null ? "Connection is closed or broken." : "Connection is broken. Invalidating Exception: " + invalidatingException.toString()); } boolean closeAndRemoveResourcesInSet(Set s, Method closeMethod) { boolean okay = true; Set temp; synchronized (s) { temp = new HashSet(s); } for (Iterator ii = temp.iterator(); ii.hasNext(); ) { Object rsrc = ii.next(); try { closeMethod.invoke(rsrc, CLOSE_ARGS); } catch (Exception e) { Throwable t = e; if (t instanceof InvocationTargetException) t = ((InvocationTargetException) e).getTargetException(); logger.log(MLevel.WARNING, "An exception occurred while cleaning up a resource.", t); // t.printStackTrace(); okay = false; } finally { s.remove(rsrc); } } // We had to abandon the idea of simply iterating over s directly, because // our resource close methods sometimes try to remove the resource from // its parent Set. This is important (when the user closes the resources // directly), but leads to ConcurrenModificationExceptions while we are // iterating over the Set to close. So, now we iterate over a copy, but remove // from the original Set. Since removal is idempotent, it don't matter if // the close method already provoked a remove. Sucks that we have to copy // the set though. // // Original (direct iteration) version: // // synchronized (s) // { // for (Iterator ii = s.iterator(); ii.hasNext(); ) // { // Object rsrc = ii.next(); // try // { closeMethod.invoke(rsrc, CLOSE_ARGS); } // catch (Exception e) // { // Throwable t = e; // if (t instanceof InvocationTargetException) // t = ((InvocationTargetException) e).getTargetException(); // t.printStackTrace(); // okay = false; // } // finally // { ii.remove(); } // } // } return okay; } private SQLException cleanupUncachedActiveStatements() { // System.err.println("IN uncachedActiveStatements.size(): " + // uncachedActiveStatements.size()); boolean okay = closeAndRemoveResourcesInSet(uncachedActiveStatements, STMT_CLOSE_METHOD); // System.err.println("OUT uncachedActiveStatements.size(): " + // uncachedActiveStatements.size()); if (okay) return null; else return new SQLException( "An exception occurred while trying to " + "clean up orphaned resources."); } ProxyConnection createProxyConnection() throws Exception { // we should always have a separate handler for each proxy connection, so // that object methods behave as expected... the handler covers // all object methods on behalf of the proxy. InvocationHandler handler = new ProxyConnectionInvocationHandler(); return (ProxyConnection) CON_PROXY_CTOR.newInstance(new Object[] {handler}); } Statement createProxyStatement(Statement innerStmt) throws Exception { return this.createProxyStatement(false, innerStmt); } private static class StatementProxyingSetManagedResultSet extends SetManagedResultSet { private Statement proxyStatement; StatementProxyingSetManagedResultSet(Set activeResultSets) { super(activeResultSets); } public void setProxyStatement(Statement proxyStatement) { this.proxyStatement = proxyStatement; } public Statement getStatement() throws SQLException { return (proxyStatement == null ? super.getStatement() : proxyStatement); } } /* * 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); } } final class ProxyConnectionInvocationHandler implements InvocationHandler { // MT: ThreadSafe, but reassigned -- protected by this' lock Connection activeConnection = physicalConnection; DatabaseMetaData metaData = null; boolean connection_error_signaled = false; /* * contains all unclosed ResultSets derived from this Connection's metadata * associated with the physical connection * * MT: protected by this' lock */ final Set activeMetaDataResultSets = new HashSet(); // being careful with doRawConnectionOperation // we initialize lazily, because this will be very rarely used Set doRawResultSets = null; boolean txn_known_resolved = true; public String toString() { return "C3P0ProxyConnection [Invocation Handler: " + super.toString() + ']'; } private Object doRawConnectionOperation(Method m, Object target, Object[] args) throws IllegalAccessException, InvocationTargetException, SQLException, Exception { if (activeConnection == null) throw new SQLException( "Connection previously closed. You cannot operate on a closed Connection."); if (target == C3P0ProxyConnection.RAW_CONNECTION) target = activeConnection; for (int i = 0, len = args.length; i < len; ++i) if (args[i] == C3P0ProxyConnection.RAW_CONNECTION) args[i] = activeConnection; Object out = m.invoke(target, args); // we never cache Statements generated by an operation on the raw Connection if (out instanceof Statement) out = createProxyStatement(false, (Statement) out); else if (out instanceof ResultSet) { if (doRawResultSets == null) doRawResultSets = new HashSet(); out = new NullStatementSetManagedResultSet((ResultSet) out, doRawResultSets); } return out; } public synchronized Object invoke(Object proxy, Method m, Object[] args) throws Throwable { if (OBJECT_METHODS.contains(m)) return m.invoke(this, args); try { String mname = m.getName(); if (activeConnection != null) { if (mname.equals("rawConnectionOperation")) { ensureOkay(); txn_known_resolved = false; return doRawConnectionOperation((Method) args[0], args[1], (Object[]) args[2]); } else if (mname.equals("setTransactionIsolation")) { ensureOkay(); // don't modify txn_known_resolved m.invoke(activeConnection, args); int lvl = ((Integer) args[0]).intValue(); isolation_lvl_nondefault = (lvl != dflt_txn_isolation); // System.err.println("updated txn isolation to " + lvl + ", nondefault level? " + // isolation_lvl_nondefault); return null; } else if (mname.equals("setCatalog")) { ensureOkay(); // don't modify txn_known_resolved m.invoke(activeConnection, args); String catalog = (String) args[0]; catalog_nondefault = ObjectUtils.eqOrBothNull(catalog, dflt_catalog); return null; } else if (mname.equals("setHoldability")) { ensureOkay(); // don't modify txn_known_resolved m.invoke( activeConnection, args); // will throw an exception if setHoldability() not supported... int holdability = ((Integer) args[0]).intValue(); holdability_nondefault = (holdability != dflt_holdability); return null; } else if (mname.equals("createStatement")) { ensureOkay(); txn_known_resolved = false; Object stmt = m.invoke(activeConnection, args); return createProxyStatement((Statement) stmt); } else if (mname.equals("prepareStatement")) { ensureOkay(); txn_known_resolved = false; Object pstmt; if (scache == null) { pstmt = m.invoke(activeConnection, args); return createProxyStatement((Statement) pstmt); } else { pstmt = scache.checkoutStatement(physicalConnection, m, args); return createProxyStatement(true, (Statement) pstmt); } } else if (mname.equals("prepareCall")) { ensureOkay(); txn_known_resolved = false; Object cstmt; if (scache == null) { cstmt = m.invoke(activeConnection, args); return createProxyStatement((Statement) cstmt); } else { cstmt = scache.checkoutStatement(physicalConnection, m, args); return createProxyStatement(true, (Statement) cstmt); } } else if (mname.equals("getMetaData")) { ensureOkay(); txn_known_resolved = false; // views of tables etc. might be txn dependent DatabaseMetaData innerMd = activeConnection.getMetaData(); if (metaData == null) { // exposedProxy is protected by C3P0PooledConnection.this' lock synchronized (C3P0PooledConnection.this) { metaData = new SetManagedDatabaseMetaData(innerMd, activeMetaDataResultSets, exposedProxy); } } return metaData; } else if (mname.equals("silentClose")) { // the PooledConnection doesn't have to be okay doSilentClose(proxy, ((Boolean) args[0]).booleanValue(), this.txn_known_resolved); return null; } else if (mname.equals("close")) { // the PooledConnection doesn't have to be okay Exception e = doSilentClose(proxy, false, this.txn_known_resolved); if (!connection_error_signaled) ces.fireConnectionClosed(); // System.err.println("close() called on a ProxyConnection."); if (e != null) { // System.err.print("user close exception -- "); // e.printStackTrace(); throw e; } else return null; } // else if ( mname.equals("finalize") ) //REMOVE THIS CASE -- TMP DEBUG // { // System.err.println("Connection apparently finalized!"); // return m.invoke( activeConnection, args ); // } else { ensureOkay(); // we've disabled setting txn_known_resolved to true, ever, because // we failed to deal with the case that clients would work with previously // acquired Statements and ResultSets after a commit(), rollback(), or setAutoCommit(). // the new non-reflective proxies have been modified to deal with this case. // here, with soon-to-be-deprecated in "traditional reflective proxies mode" // we are reverting to the conservative, always-presume-you-have-to-rollback // policy. // txn_known_resolved = ( mname.equals("commit") || mname.equals( "rollback" ) || // mname.equals( "setAutoCommit" ) ); txn_known_resolved = false; return m.invoke(activeConnection, args); } } else { if (mname.equals("close") || mname.equals("silentClose")) return null; else if (mname.equals("isClosed")) return Boolean.TRUE; else { throw new SQLException("You can't operate on " + "a closed connection!!!"); } } } catch (InvocationTargetException e) { Throwable convertMe = e.getTargetException(); SQLException sqle = handleMaybeFatalToPooledConnection(convertMe, proxy, false); sqle.fillInStackTrace(); throw sqle; } } private Exception doSilentClose(Object proxyConnection, boolean pooled_connection_is_dead) { return doSilentClose(proxyConnection, pooled_connection_is_dead, false); } private Exception doSilentClose( Object proxyConnection, boolean pooled_connection_is_dead, boolean known_resolved_txn) { if (activeConnection != null) { synchronized ( C3P0PooledConnection .this) // uh oh... this is a nested lock acq... is there a deadlock hazard here? { if (C3P0PooledConnection.this.exposedProxy == proxyConnection) { C3P0PooledConnection.this.exposedProxy = null; // System.err.println("Reset exposed proxy."); // DEBUG // origGet = null; } else // else case -- DEBUG only logger.warning( "(c3p0 issue) doSilentClose( ... ) called on a proxyConnection " + "other than the current exposed proxy for its PooledConnection. [exposedProxy: " + exposedProxy + ", proxyConnection: " + proxyConnection); // System.err.println("[DEBUG] WARNING: doSilentClose( ... ) called on a // proxyConnection " + // "other than the current exposed proxy for its PooledConnection. [exposedProxy: // " + // exposedProxy + ", proxyConnection: " + proxyConnection); } Exception out = null; Exception exc1 = null, exc2 = null, exc3 = null, exc4 = null; try { if (!pooled_connection_is_dead) C3P0PooledConnection.this.reset(known_resolved_txn); } catch (Exception e) { exc1 = e; // if (Debug.DEBUG) // { // System.err.print("exc1 -- "); // exc1.printStackTrace(); // } } exc2 = cleanupUncachedActiveStatements(); // if (Debug.DEBUG && exc2 != null) // { // System.err.print("exc2 -- "); // exc2.printStackTrace(); // } String errSource; if (doRawResultSets != null) { activeMetaDataResultSets.addAll(doRawResultSets); errSource = "DataBaseMetaData or raw Connection operation"; } else errSource = "DataBaseMetaData"; if (!closeAndRemoveResultSets(activeMetaDataResultSets)) exc3 = new SQLException("Failed to close some " + errSource + " Result Sets."); // if (Debug.DEBUG && exc3 != null) // { // System.err.print("exc3 -- "); // exc3.printStackTrace(); // } if (scache != null) { try { scache.checkinAll(physicalConnection); } catch (Exception e) { exc4 = e; } // if (Debug.DEBUG && exc4 != null) // { // System.err.print("exc4 -- "); // exc4.printStackTrace(); // } } if (exc1 != null) { handleMaybeFatalToPooledConnection(exc1, proxyConnection, true); out = exc1; } else if (exc2 != null) { handleMaybeFatalToPooledConnection(exc2, proxyConnection, true); out = exc2; } else if (exc3 != null) { handleMaybeFatalToPooledConnection(exc3, proxyConnection, true); out = exc3; } else if (exc4 != null) { handleMaybeFatalToPooledConnection(exc4, proxyConnection, true); out = exc4; } // if (out != null) // { // System.err.print("out -- "); // out.printStackTrace(); // } activeConnection = null; return out; } else return null; } private SQLException handleMaybeFatalToPooledConnection( Throwable t, Object proxyConnection, boolean already_closed) { // System.err.println("handleMaybeFatalToPooledConnection()"); SQLException sqle = SqlUtils.toSQLException(t); int status = connectionTester.statusOnException(physicalConnection, sqle); updateConnectionStatus(status); if (status != ConnectionTester.CONNECTION_IS_OKAY) { if (Debug.DEBUG) { // System.err.print(C3P0PooledConnection.this + " will no longer be pooled because // it has been " + // "marked invalid by the following Exception: "); // t.printStackTrace(); logger.log( MLevel.INFO, C3P0PooledConnection.this + " will no longer be pooled because it has been marked invalid by an Exception.", t); } invalidatingException = sqle; /* ------ A users have complained that SQLExceptions ought not close their Connections underneath them under any circumstance. Signalling the Connection error after updating the Connection status should be sufficient from the pool's perspective, because the PooledConnection will be marked broken by the pool and will be destroyed on checkin. I think actually close()ing the Connection when it appears to be broken rather than waiting for users to close() it themselves is overly aggressive, so I'm commenting the old behavior out. The only potential downside to this approach is that users who do not close() in a finally clause properly might see their close()es skipped by exceptions that previously would have led to automatic close(). But relying on the automatic close() was never reliable (since it only ever happened when c3p0 determined a Connection to be absolutely broken), and is generally speaking a client error that c3p0 ought not be responsible for dealing with. I think it's right to leave this out. -- swaldman 2004-12-09 ------ if (! already_closed ) doSilentClose( proxyConnection, true ); */ if (!connection_error_signaled) { ces.fireConnectionErrorOccurred(sqle); connection_error_signaled = true; } } return sqle; } } interface ProxyConnection extends C3P0ProxyConnection { void silentClose(boolean known_invalid) throws SQLException; } public synchronized int getConnectionStatus() { return this.connection_status; } private synchronized void updateConnectionStatus(int status) { switch (this.connection_status) { case ConnectionTester.DATABASE_IS_INVALID: // can't get worse than this, do nothing. break; case ConnectionTester.CONNECTION_IS_INVALID: if (status == ConnectionTester.DATABASE_IS_INVALID) doBadUpdate(status); break; case ConnectionTester.CONNECTION_IS_OKAY: if (status != ConnectionTester.CONNECTION_IS_OKAY) doBadUpdate(status); break; default: throw new InternalError(this + " -- Illegal Connection Status: " + this.connection_status); } } // must be called from sync'ed method private void doBadUpdate(int new_status) { this.connection_status = new_status; try { this.close(true); } catch (SQLException e) { // System.err.print("Broken Connection Close Error: "); // e.printStackTrace(); logger.log(MLevel.WARNING, "Broken Connection Close Error. ", e); } } }
/* * The primary purpose of C3P0Registry is to maintain a mapping of "identityTokens" * to c3p0 DataSources so that if the same DataSource is looked up (and deserialized * or dereferenced) via JNDI, c3p0 can ensure that the same instance is always returned. * But there are subtle issues here. If C3P0Registry maintains hard references to * DataSources, then they can never be garbage collected. But if c3p0 retains only * weak references, then applications that look up DataSources, then dereference them, * and then re-look them up again (not a great idea, but not uncommon) might see * distinct DataSources over multiple lookups. * * C3P0 resolves this issue has followed: At first creation or lookup of a PooledDataSource, * c3p0 creates a hard reference to that DataSource. So long as the DataSource has not * been close()ed or DataSources.destroy()ed, subsequent lookups will consistently * return the same DataSource. If the DataSource is never closed, then there is a potential * memory leak (as well as the potential Thread leak and Connection leak). But if * the DataSource is close()ed, only weak refernces to the DataSource will be retained. * A lookup of a DataSource after it has been close()ed within the current VM may * return the previously close()ed instance, or may return a fresh instance, depending * on whether the weak reference has been cleared. In other words, the result of * looking up a DataSource after having close()ed it in the current VM is undefined. * * Note that unpooled c3p0 DataSources are always held by weak references, since * they are never explicitly close()ed. The result of looking up an unpooled DataSource, * modifying it, dereferencing it, and then relooking up is therefore undefined as well. * * These issues are mostly academic. Under normal use scenarios, how c3p0 deals with * maintaining its registry doesn't much matter. In the past, c3p0 maintained hard * references to DataSources indefinitely. At least one user ran into side effects * of the unwanted retention of old DataSources (in a process left to run for months * at a time, and frequently reconstructing multiple DataSources), so now we take care * to ensure that when users properly close() and dereference DataSources, they can * indeed be garbage collected. */ public final class C3P0Registry { private static final String MC_PARAM = "com.mchange.v2.c3p0.management.ManagementCoordinator"; // MT: thread-safe static final MLogger logger = MLog.getLogger(C3P0Registry.class); // MT: protected by class' lock static boolean banner_printed = false; // MT: protected by class' lock static boolean registry_mbean_registered = false; // MT: thread-safe, immutable private static CoalesceChecker CC = IdentityTokenizedCoalesceChecker.INSTANCE; // MT: protected by class' lock // a weak, unsynchronized coalescer private static Coalescer idtCoalescer = CoalescerFactory.createCoalescer(CC, true, false); // MT: protected by class' lock private static Map tokensToTokenized = new DoubleWeakHashMap(); // MT: protected by class' lock private static HashSet unclosedPooledDataSources = new HashSet(); // MT: protected by its own lock private static Map classNamesToConnectionTesters = Collections.synchronizedMap(new HashMap()); // MT: protected by its own lock private static Map classNamesToConnectionCustomizers = Collections.synchronizedMap(new HashMap()); private static ManagementCoordinator mc; 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 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(); } } 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); } } } // 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; } } // must be called from a static, sync'ed method private static void attemptRegisterRegistryMBean() { if (!registry_mbean_registered) { mc.attemptManageC3P0Registry(); registry_mbean_registered = true; } } // must be called with class' lock private static boolean isIncorporated(IdentityTokenized idt) { return tokensToTokenized.keySet().contains(idt.getIdentityToken()); } // must be called with class' lock private static void incorporate(IdentityTokenized idt) { tokensToTokenized.put(idt.getIdentityToken(), idt); if (idt instanceof PooledDataSource) { unclosedPooledDataSources.add(idt); mc.attemptManagePooledDataSource((PooledDataSource) idt); } } public static synchronized IdentityTokenized reregister(IdentityTokenized idt) { if (idt instanceof PooledDataSource) { banner(); attemptRegisterRegistryMBean(); } if (idt.getIdentityToken() == null) throw new RuntimeException( "[c3p0 issue] The identityToken of a registered object should be set prior to registration."); IdentityTokenized coalesceCheck = (IdentityTokenized) idtCoalescer.coalesce(idt); if (!isIncorporated(coalesceCheck)) incorporate(coalesceCheck); return coalesceCheck; } public static synchronized void markClosed(PooledDataSource pds) { unclosedPooledDataSources.remove(pds); mc.attemptUnmanagePooledDataSource(pds); if (unclosedPooledDataSources.isEmpty()) { mc.attemptUnmanageC3P0Registry(); registry_mbean_registered = false; } } public static synchronized Set getPooledDataSources() { return (Set) unclosedPooledDataSources.clone(); } /** @return the set of all PooledDataSources sharing the given dataSourceName */ public static synchronized Set pooledDataSourcesByName(String dataSourceName) { Set out = new HashSet(); for (Iterator ii = unclosedPooledDataSources.iterator(); ii.hasNext(); ) { PooledDataSource pds = (PooledDataSource) ii.next(); if (pds.getDataSourceName().equals(dataSourceName)) out.add(pds); } return out; } /** * <b>Note:</b> If multiple PooledDataSources in your JVM share the same <tt>dataSourceName</tt>, * which of those multiple DataSources will be returned by this method is undefined! * * @return a PooledDataSource with the given <tt>dataSourceName</tt>, if at least one exists. * <tt>null</tt> otherwise. */ public static synchronized PooledDataSource pooledDataSourceByName(String dataSourceName) { for (Iterator ii = unclosedPooledDataSources.iterator(); ii.hasNext(); ) { PooledDataSource pds = (PooledDataSource) ii.next(); if (pds.getDataSourceName().equals(dataSourceName)) return pds; } return null; } public static synchronized Set allIdentityTokens() { Set out = Collections.unmodifiableSet(tokensToTokenized.keySet()); // System.err.println( "allIdentityTokens(): " + out ); return out; } public static synchronized Set allIdentityTokenized() { HashSet out = new HashSet(); out.addAll(tokensToTokenized.values()); // System.err.println( "allIdentityTokenized(): " + out ); return Collections.unmodifiableSet(out); } public static synchronized Set allPooledDataSources() { Set out = Collections.unmodifiableSet(unclosedPooledDataSources); // System.err.println( "allPooledDataSources(): " + out ); return out; } public static synchronized int getNumPooledDataSources() { return unclosedPooledDataSources.size(); } public static synchronized int getNumPoolsAllDataSources() throws SQLException { int count = 0; for (Iterator ii = unclosedPooledDataSources.iterator(); ii.hasNext(); ) { PooledDataSource pds = (PooledDataSource) ii.next(); count += pds.getNumUserPools(); } return count; } public synchronized int getNumThreadsAllThreadPools() throws SQLException { int count = 0; for (Iterator ii = unclosedPooledDataSources.iterator(); ii.hasNext(); ) { PooledDataSource pds = (PooledDataSource) ii.next(); count += pds.getNumHelperThreads(); } return count; } }
public abstract class AbstractPoolBackedDataSource extends PoolBackedDataSourceBase implements PooledDataSource { static final MLogger logger = MLog.getLogger(AbstractPoolBackedDataSource.class); static final String NO_CPDS_ERR_MSG = "Attempted to use an uninitialized PoolBackedDataSource. " + "Please call setConnectionPoolDataSource( ... ) to initialize."; // MT: protected by this' lock transient C3P0PooledConnectionPoolManager poolManager; transient boolean is_closed = false; // MT: end protected by this' lock protected AbstractPoolBackedDataSource(boolean autoregister) { super(autoregister); setUpPropertyEvents(); } protected AbstractPoolBackedDataSource(String configName) { this(true); initializeNamedConfig(configName); } private void setUpPropertyEvents() { PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { resetPoolManager(); } }; this.addPropertyChangeListener(l); } 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); } } // Commented out method is just super.getReference() with a lot of extra printing // public javax.naming.Reference getReference() throws javax.naming.NamingException // { // System.err.println("getReference()!!!!"); // new Exception("PRINT-STACK-TRACE").printStackTrace(); // javax.naming.Reference out = super.getReference(); // System.err.println(out); // return out; // } // report our ID token as dataSourceName if we have no // name explicitly set public String getDataSourceName() { String out = super.getDataSourceName(); if (out == null) out = this.getIdentityToken(); return out; } // implementation of javax.sql.DataSource public Connection getConnection() throws SQLException { PooledConnection pc = getPoolManager().getPool().checkoutPooledConnection(); return pc.getConnection(); } public Connection getConnection(String username, String password) throws SQLException { PooledConnection pc = getPoolManager().getPool(username, password).checkoutPooledConnection(); return pc.getConnection(); } public PrintWriter getLogWriter() throws SQLException { return assertCpds().getLogWriter(); } public void setLogWriter(PrintWriter out) throws SQLException { assertCpds().setLogWriter(out); } public int getLoginTimeout() throws SQLException { return assertCpds().getLoginTimeout(); } public void setLoginTimeout(int seconds) throws SQLException { assertCpds().setLoginTimeout(seconds); } // implementation of com.mchange.v2.c3p0.PoolingDataSource public int getNumConnections() throws SQLException { return getPoolManager().getPool().getNumConnections(); } public int getNumIdleConnections() throws SQLException { return getPoolManager().getPool().getNumIdleConnections(); } public int getNumBusyConnections() throws SQLException { return getPoolManager().getPool().getNumBusyConnections(); } public int getNumUnclosedOrphanedConnections() throws SQLException { return getPoolManager().getPool().getNumUnclosedOrphanedConnections(); } public int getNumConnectionsDefaultUser() throws SQLException { return getNumConnections(); } public int getNumIdleConnectionsDefaultUser() throws SQLException { return getNumIdleConnections(); } public int getNumBusyConnectionsDefaultUser() throws SQLException { return getNumBusyConnections(); } public int getNumUnclosedOrphanedConnectionsDefaultUser() throws SQLException { return getNumUnclosedOrphanedConnections(); } public int getStatementCacheNumStatementsDefaultUser() throws SQLException { return getPoolManager().getPool().getStatementCacheNumStatements(); } public int getStatementCacheNumCheckedOutDefaultUser() throws SQLException { return getPoolManager().getPool().getStatementCacheNumCheckedOut(); } public int getStatementCacheNumConnectionsWithCachedStatementsDefaultUser() throws SQLException { return getPoolManager().getPool().getStatementCacheNumConnectionsWithCachedStatements(); } public float getEffectivePropertyCycleDefaultUser() throws SQLException { return getPoolManager().getPool().getEffectivePropertyCycle(); } public long getStartTimeMillisDefaultUser() throws SQLException { return getPoolManager().getPool().getStartTime(); } public long getUpTimeMillisDefaultUser() throws SQLException { return getPoolManager().getPool().getUpTime(); } public long getNumFailedCheckinsDefaultUser() throws SQLException { return getPoolManager().getPool().getNumFailedCheckins(); } public long getNumFailedCheckoutsDefaultUser() throws SQLException { return getPoolManager().getPool().getNumFailedCheckouts(); } public long getNumFailedIdleTestsDefaultUser() throws SQLException { return getPoolManager().getPool().getNumFailedIdleTests(); } public int getNumThreadsAwaitingCheckoutDefaultUser() throws SQLException { return getPoolManager().getPool().getNumThreadsAwaitingCheckout(); } public int getThreadPoolSize() throws SQLException { return getPoolManager().getThreadPoolSize(); } public int getThreadPoolNumActiveThreads() throws SQLException { return getPoolManager().getThreadPoolNumActiveThreads(); } public int getThreadPoolNumIdleThreads() throws SQLException { return getPoolManager().getThreadPoolNumIdleThreads(); } public int getThreadPoolNumTasksPending() throws SQLException { return getPoolManager().getThreadPoolNumTasksPending(); } public String sampleThreadPoolStackTraces() throws SQLException { return getPoolManager().getThreadPoolStackTraces(); } public String sampleThreadPoolStatus() throws SQLException { return getPoolManager().getThreadPoolStatus(); } public String sampleStatementCacheStatusDefaultUser() throws SQLException { return getPoolManager().getPool().dumpStatementCacheStatus(); } public String sampleStatementCacheStatus(String username, String password) throws SQLException { return assertAuthPool(username, password).dumpStatementCacheStatus(); } public Throwable getLastAcquisitionFailureDefaultUser() throws SQLException { return getPoolManager().getPool().getLastAcquisitionFailure(); } public Throwable getLastCheckinFailureDefaultUser() throws SQLException { return getPoolManager().getPool().getLastCheckinFailure(); } public Throwable getLastCheckoutFailureDefaultUser() throws SQLException { return getPoolManager().getPool().getLastCheckoutFailure(); } public Throwable getLastIdleTestFailureDefaultUser() throws SQLException { return getPoolManager().getPool().getLastIdleTestFailure(); } public Throwable getLastConnectionTestFailureDefaultUser() throws SQLException { return getPoolManager().getPool().getLastConnectionTestFailure(); } public Throwable getLastAcquisitionFailure(String username, String password) throws SQLException { return assertAuthPool(username, password).getLastAcquisitionFailure(); } public Throwable getLastCheckinFailure(String username, String password) throws SQLException { return assertAuthPool(username, password).getLastCheckinFailure(); } public Throwable getLastCheckoutFailure(String username, String password) throws SQLException { return assertAuthPool(username, password).getLastCheckoutFailure(); } public Throwable getLastIdleTestFailure(String username, String password) throws SQLException { return assertAuthPool(username, password).getLastIdleTestFailure(); } public Throwable getLastConnectionTestFailure(String username, String password) throws SQLException { return assertAuthPool(username, password).getLastConnectionTestFailure(); } public int getNumThreadsAwaitingCheckout(String username, String password) throws SQLException { return assertAuthPool(username, password).getNumThreadsAwaitingCheckout(); } public String sampleLastAcquisitionFailureStackTraceDefaultUser() throws SQLException { Throwable t = getLastAcquisitionFailureDefaultUser(); return t == null ? null : ThrowableUtils.extractStackTrace(t); } public String sampleLastCheckinFailureStackTraceDefaultUser() throws SQLException { Throwable t = getLastCheckinFailureDefaultUser(); return t == null ? null : ThrowableUtils.extractStackTrace(t); } public String sampleLastCheckoutFailureStackTraceDefaultUser() throws SQLException { Throwable t = getLastCheckoutFailureDefaultUser(); return t == null ? null : ThrowableUtils.extractStackTrace(t); } public String sampleLastIdleTestFailureStackTraceDefaultUser() throws SQLException { Throwable t = getLastIdleTestFailureDefaultUser(); return t == null ? null : ThrowableUtils.extractStackTrace(t); } public String sampleLastConnectionTestFailureStackTraceDefaultUser() throws SQLException { Throwable t = getLastConnectionTestFailureDefaultUser(); return t == null ? null : ThrowableUtils.extractStackTrace(t); } public String sampleLastAcquisitionFailureStackTrace(String username, String password) throws SQLException { Throwable t = getLastAcquisitionFailure(username, password); return t == null ? null : ThrowableUtils.extractStackTrace(t); } public String sampleLastCheckinFailureStackTrace(String username, String password) throws SQLException { Throwable t = getLastCheckinFailure(username, password); return t == null ? null : ThrowableUtils.extractStackTrace(t); } public String sampleLastCheckoutFailureStackTrace(String username, String password) throws SQLException { Throwable t = getLastCheckoutFailure(username, password); return t == null ? null : ThrowableUtils.extractStackTrace(t); } public String sampleLastIdleTestFailureStackTrace(String username, String password) throws SQLException { Throwable t = getLastIdleTestFailure(username, password); return t == null ? null : ThrowableUtils.extractStackTrace(t); } public String sampleLastConnectionTestFailureStackTrace(String username, String password) throws SQLException { Throwable t = getLastConnectionTestFailure(username, password); return t == null ? null : ThrowableUtils.extractStackTrace(t); } public void softResetDefaultUser() throws SQLException { getPoolManager().getPool().reset(); } public int getNumConnections(String username, String password) throws SQLException { return assertAuthPool(username, password).getNumConnections(); } public int getNumIdleConnections(String username, String password) throws SQLException { return assertAuthPool(username, password).getNumIdleConnections(); } public int getNumBusyConnections(String username, String password) throws SQLException { return assertAuthPool(username, password).getNumBusyConnections(); } public int getNumUnclosedOrphanedConnections(String username, String password) throws SQLException { return assertAuthPool(username, password).getNumUnclosedOrphanedConnections(); } public int getStatementCacheNumStatements(String username, String password) throws SQLException { return assertAuthPool(username, password).getStatementCacheNumStatements(); } public int getStatementCacheNumCheckedOut(String username, String password) throws SQLException { return assertAuthPool(username, password).getStatementCacheNumCheckedOut(); } public int getStatementCacheNumConnectionsWithCachedStatements(String username, String password) throws SQLException { return assertAuthPool(username, password).getStatementCacheNumConnectionsWithCachedStatements(); } public float getEffectivePropertyCycle(String username, String password) throws SQLException { return assertAuthPool(username, password).getEffectivePropertyCycle(); } public long getStartTimeMillis(String username, String password) throws SQLException { return assertAuthPool(username, password).getStartTime(); } public long getUpTimeMillis(String username, String password) throws SQLException { return assertAuthPool(username, password).getUpTime(); } public long getNumFailedCheckins(String username, String password) throws SQLException { return assertAuthPool(username, password).getNumFailedCheckins(); } public long getNumFailedCheckouts(String username, String password) throws SQLException { return assertAuthPool(username, password).getNumFailedCheckouts(); } public long getNumFailedIdleTests(String username, String password) throws SQLException { return assertAuthPool(username, password).getNumFailedIdleTests(); } public void softReset(String username, String password) throws SQLException { assertAuthPool(username, password).reset(); } public int getNumBusyConnectionsAllUsers() throws SQLException { return getPoolManager().getNumBusyConnectionsAllAuths(); } public int getNumIdleConnectionsAllUsers() throws SQLException { return getPoolManager().getNumIdleConnectionsAllAuths(); } public int getNumConnectionsAllUsers() throws SQLException { return getPoolManager().getNumConnectionsAllAuths(); } public int getNumUnclosedOrphanedConnectionsAllUsers() throws SQLException { return getPoolManager().getNumUnclosedOrphanedConnectionsAllAuths(); } public int getStatementCacheNumStatementsAllUsers() throws SQLException { return getPoolManager().getStatementCacheNumStatementsAllUsers(); } public int getStatementCacheNumCheckedOutStatementsAllUsers() throws SQLException { return getPoolManager().getStatementCacheNumCheckedOutStatementsAllUsers(); } public synchronized int getStatementCacheNumConnectionsWithCachedStatementsAllUsers() throws SQLException { return getPoolManager().getStatementCacheNumConnectionsWithCachedStatementsAllUsers(); } public void softResetAllUsers() throws SQLException { getPoolManager().softResetAllAuths(); } public int getNumUserPools() throws SQLException { return getPoolManager().getNumManagedAuths(); } public Collection getAllUsers() throws SQLException { LinkedList out = new LinkedList(); Set auths = getPoolManager().getManagedAuths(); for (Iterator ii = auths.iterator(); ii.hasNext(); ) out.add(((DbAuth) ii.next()).getUser()); return Collections.unmodifiableList(out); } public synchronized void hardReset() { resetPoolManager(); } 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().")); } } /** * @deprecated the force_destroy argument is now meaningless, as pools are no longer potentially * shared between multiple DataSources. */ public void close(boolean force_destroy) { close(); } // other code public synchronized void resetPoolManager() // used by other, wrapping datasources in package, and in mbean package { resetPoolManager(true); } public synchronized void resetPoolManager( boolean close_checked_out_connections) // used by other, wrapping datasources in package, and in // mbean package { if (poolManager != null) { poolManager.close(close_checked_out_connections); poolManager = null; } } private synchronized ConnectionPoolDataSource assertCpds() throws SQLException { if (is_closed) throw new SQLException(this + " has been closed() -- you can no longer use it."); ConnectionPoolDataSource out = this.getConnectionPoolDataSource(); if (out == null) throw new SQLException(NO_CPDS_ERR_MSG); return out; } 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; } private C3P0PooledConnectionPool assertAuthPool(String username, String password) throws SQLException { C3P0PooledConnectionPool authPool = getPoolManager().getPool(username, password, false); if (authPool == null) throw new SQLException( "No pool has been yet been established for Connections authenticated by user '" + username + "' with the password provided. [Use getConnection( username, password ) " + "to initialize such a pool.]"); else return authPool; } // serialization stuff -- set up bound/constrained property event handlers on deserialization private static final long serialVersionUID = 1; private static final short VERSION = 0x0001; private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeShort(VERSION); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { short version = ois.readShort(); switch (version) { case VERSION: setUpPropertyEvents(); break; default: throw new IOException("Unsupported Serialized Version: " + version); } } }
public class JavaBeanReferenceMaker implements ReferenceMaker { private static final MLogger logger = MLog.getLogger(JavaBeanReferenceMaker.class); static final String REF_PROPS_KEY = "com.mchange.v2.naming.JavaBeanReferenceMaker.REF_PROPS_KEY"; static final Object[] EMPTY_ARGS = new Object[0]; static final byte[] NULL_TOKEN_BYTES = new byte[0]; String factoryClassName = "com.mchange.v2.naming.JavaBeanObjectFactory"; String defaultFactoryClassLocation = null; Set referenceProperties = new HashSet(); ReferenceIndirector indirector = new ReferenceIndirector(); public Hashtable getEnvironmentProperties() { return indirector.getEnvironmentProperties(); } public void setEnvironmentProperties(Hashtable environmentProperties) { indirector.setEnvironmentProperties(environmentProperties); } public void setFactoryClassName(String factoryClassName) { this.factoryClassName = factoryClassName; } public String getFactoryClassName() { return factoryClassName; } public String getDefaultFactoryClassLocation() { return defaultFactoryClassLocation; } public void setDefaultFactoryClassLocation(String defaultFactoryClassLocation) { this.defaultFactoryClassLocation = defaultFactoryClassLocation; } public void addReferenceProperty(String propName) { referenceProperties.add(propName); } public void removeReferenceProperty(String propName) { referenceProperties.remove(propName); } 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()); } } }
/** @param element */ private void init(Element element) { RStack stack = new RStack(element); classValue = URelaxer2.getAttributePropertyAsString( element, "http://www.w3.org/1998/Math/MathML", "class"); style = URelaxer2.getAttributePropertyAsString( element, "http://www.w3.org/1998/Math/MathML", "style"); id = URelaxer2.getAttributePropertyAsString(element, "http://www.w3.org/1998/Math/MathML", "id"); other = URelaxer2.getAttributePropertyAsString( element, "http://www.w3.org/1998/Math/MathML", "other"); content.clear(); while (!stack.isEmptyElement()) { if (MCi.isMatch(stack)) { addContent(new MCi(stack)); } else if (MCn.isMatch(stack)) { addContent(new MCn(stack)); } else if (MApply.isMatch(stack)) { addContent(new MApply(stack)); } else if (MReln.isMatch(stack)) { addContent(new MReln(stack)); } else if (MLambda.isMatch(stack)) { addContent(new MLambda(stack)); } else if (MCondition.isMatch(stack)) { addContent(new MCondition(stack)); } else if (MDeclare.isMatch(stack)) { addContent(new MDeclare(stack)); } else if (MSep.isMatch(stack)) { addContent(new MSep(stack)); } else if (MSemantics.isMatch(stack)) { addContent(new MSemantics(stack)); } else if (MAnnotation.isMatch(stack)) { addContent(new MAnnotation(stack)); } else if (MAnnotationXml.isMatch(stack)) { addContent(new MAnnotationXml(stack)); } else if (MInterval.isMatch(stack)) { addContent(new MInterval(stack)); } else if (MList.isMatch(stack)) { addContent(new MList(stack)); } else if (MMatrix.isMatch(stack)) { addContent(new MMatrix(stack)); } else if (MMatrixrow.isMatch(stack)) { addContent(new MMatrixrow(stack)); } else if (MSet.isMatch(stack)) { addContent(new MSet(stack)); } else if (MVector.isMatch(stack)) { addContent(new MVector(stack)); } else if (MLowlimit.isMatch(stack)) { addContent(new MLowlimit(stack)); } else if (MUplimit.isMatch(stack)) { addContent(new MUplimit(stack)); } else if (MBvar.isMatch(stack)) { addContent(new MBvar(stack)); } else if (MDegree.isMatch(stack)) { addContent(new MDegree(stack)); } else if (MLogbase.isMatch(stack)) { addContent(new MLogbase(stack)); } else if (MInverse.isMatch(stack)) { addContent(new MInverse(stack)); } else if (MIdent.isMatch(stack)) { addContent(new MIdent(stack)); } else if (MAbs.isMatch(stack)) { addContent(new MAbs(stack)); } else if (MConjugate.isMatch(stack)) { addContent(new MConjugate(stack)); } else if (MExp.isMatch(stack)) { addContent(new MExp(stack)); } else if (MFactorial.isMatch(stack)) { addContent(new MFactorial(stack)); } else if (MNot.isMatch(stack)) { addContent(new MNot(stack)); } else if (MLn.isMatch(stack)) { addContent(new MLn(stack)); } else if (MSin.isMatch(stack)) { addContent(new MSin(stack)); } else if (MCos.isMatch(stack)) { addContent(new MCos(stack)); } else if (MTan.isMatch(stack)) { addContent(new MTan(stack)); } else if (MSec.isMatch(stack)) { addContent(new MSec(stack)); } else if (MCsc.isMatch(stack)) { addContent(new MCsc(stack)); } else if (MCot.isMatch(stack)) { addContent(new MCot(stack)); } else if (MSinh.isMatch(stack)) { addContent(new MSinh(stack)); } else if (MCosh.isMatch(stack)) { addContent(new MCosh(stack)); } else if (MTanh.isMatch(stack)) { addContent(new MTanh(stack)); } else if (MSech.isMatch(stack)) { addContent(new MSech(stack)); } else if (MCsch.isMatch(stack)) { addContent(new MCsch(stack)); } else if (MCoth.isMatch(stack)) { addContent(new MCoth(stack)); } else if (MArcsin.isMatch(stack)) { addContent(new MArcsin(stack)); } else if (MArccos.isMatch(stack)) { addContent(new MArccos(stack)); } else if (MArctan.isMatch(stack)) { addContent(new MArctan(stack)); } else if (MDeterminant.isMatch(stack)) { addContent(new MDeterminant(stack)); } else if (MTranspose.isMatch(stack)) { addContent(new MTranspose(stack)); } else if (MQuotient.isMatch(stack)) { addContent(new MQuotient(stack)); } else if (MDivide.isMatch(stack)) { addContent(new MDivide(stack)); } else if (MPower.isMatch(stack)) { addContent(new MPower(stack)); } else if (MRem.isMatch(stack)) { addContent(new MRem(stack)); } else if (MImplies.isMatch(stack)) { addContent(new MImplies(stack)); } else if (MSetdiff.isMatch(stack)) { addContent(new MSetdiff(stack)); } else if (MFn.isMatch(stack)) { addContent(new MFn(stack)); } else if (MCompose.isMatch(stack)) { addContent(new MCompose(stack)); } else if (MPlus.isMatch(stack)) { addContent(new MPlus(stack)); } else if (MTimes.isMatch(stack)) { addContent(new MTimes(stack)); } else if (MMax.isMatch(stack)) { addContent(new MMax(stack)); } else if (MMin.isMatch(stack)) { addContent(new MMin(stack)); } else if (MGcd.isMatch(stack)) { addContent(new MGcd(stack)); } else if (MAnd.isMatch(stack)) { addContent(new MAnd(stack)); } else if (MOr.isMatch(stack)) { addContent(new MOr(stack)); } else if (MXor.isMatch(stack)) { addContent(new MXor(stack)); } else if (MUnion.isMatch(stack)) { addContent(new MUnion(stack)); } else if (MIntersect.isMatch(stack)) { addContent(new MIntersect(stack)); } else if (MMean.isMatch(stack)) { addContent(new MMean(stack)); } else if (MSdev.isMatch(stack)) { addContent(new MSdev(stack)); } else if (MVariance.isMatch(stack)) { addContent(new MVariance(stack)); } else if (MMedian.isMatch(stack)) { addContent(new MMedian(stack)); } else if (MMode.isMatch(stack)) { addContent(new MMode(stack)); } else if (MSelector.isMatch(stack)) { addContent(new MSelector(stack)); } else if (MRoot.isMatch(stack)) { addContent(new MRoot(stack)); } else if (MMinus.isMatch(stack)) { addContent(new MMinus(stack)); } else if (MLog.isMatch(stack)) { addContent(new MLog(stack)); } else if (MInt.isMatch(stack)) { addContent(new MInt(stack)); } else if (MDiff.isMatch(stack)) { addContent(new MDiff(stack)); } else if (MPartialdiff.isMatch(stack)) { addContent(new MPartialdiff(stack)); } else if (MSum.isMatch(stack)) { addContent(new MSum(stack)); } else if (MProduct.isMatch(stack)) { addContent(new MProduct(stack)); } else if (MLimit.isMatch(stack)) { addContent(new MLimit(stack)); } else if (MMoment.isMatch(stack)) { addContent(new MMoment(stack)); } else if (MExists.isMatch(stack)) { addContent(new MExists(stack)); } else if (MForall.isMatch(stack)) { addContent(new MForall(stack)); } else if (MNeq.isMatch(stack)) { addContent(new MNeq(stack)); } else if (MIn.isMatch(stack)) { addContent(new MIn(stack)); } else if (MNotin.isMatch(stack)) { addContent(new MNotin(stack)); } else if (MNotsubset.isMatch(stack)) { addContent(new MNotsubset(stack)); } else if (MNotprsubset.isMatch(stack)) { addContent(new MNotprsubset(stack)); } else if (MTendsto.isMatch(stack)) { addContent(new MTendsto(stack)); } else if (MEq.isMatch(stack)) { addContent(new MEq(stack)); } else if (MLeq.isMatch(stack)) { addContent(new MLeq(stack)); } else if (MLt.isMatch(stack)) { addContent(new MLt(stack)); } else if (MGeq.isMatch(stack)) { addContent(new MGeq(stack)); } else if (MGt.isMatch(stack)) { addContent(new MGt(stack)); } else if (MSubset.isMatch(stack)) { addContent(new MSubset(stack)); } else if (MPrsubset.isMatch(stack)) { addContent(new MPrsubset(stack)); } else if (MMi.isMatch(stack)) { addContent(new MMi(stack)); } else if (MMn.isMatch(stack)) { addContent(new MMn(stack)); } else if (MMo.isMatch(stack)) { addContent(new MMo(stack)); } else if (MMtext.isMatch(stack)) { addContent(new MMtext(stack)); } else if (MMs.isMatch(stack)) { addContent(new MMs(stack)); } else if (MMspace.isMatch(stack)) { addContent(new MMspace(stack)); } else if (MMrow.isMatch(stack)) { addContent(new MMrow(stack)); } else if (MMfrac.isMatch(stack)) { addContent(new MMfrac(stack)); } else if (MMsqrt.isMatch(stack)) { addContent(new MMsqrt(stack)); } else if (MMroot.isMatch(stack)) { addContent(new MMroot(stack)); } else if (MMstyle.isMatch(stack)) { addContent(new MMstyle(stack)); } else if (MMerror.isMatch(stack)) { addContent(new MMerror(stack)); } else if (MMpadded.isMatch(stack)) { addContent(new MMpadded(stack)); } else if (MMphantom.isMatch(stack)) { addContent(new MMphantom(stack)); } else if (MMfenced.isMatch(stack)) { addContent(new MMfenced(stack)); } else if (MMsub.isMatch(stack)) { addContent(new MMsub(stack)); } else if (MMsup.isMatch(stack)) { addContent(new MMsup(stack)); } else if (MMsubsup.isMatch(stack)) { addContent(new MMsubsup(stack)); } else if (MMunder.isMatch(stack)) { addContent(new MMunder(stack)); } else if (MMover.isMatch(stack)) { addContent(new MMover(stack)); } else if (MMunderover.isMatch(stack)) { addContent(new MMunderover(stack)); } else if (MMmultiscripts.isMatch(stack)) { addContent(new MMmultiscripts(stack)); } else if (MMtable.isMatch(stack)) { addContent(new MMtable(stack)); } else if (MMtr.isMatch(stack)) { addContent(new MMtr(stack)); } else if (MMtd.isMatch(stack)) { addContent(new MMtd(stack)); } else if (MMaligngroup.isMatch(stack)) { addContent(new MMaligngroup(stack)); } else if (MMalignmark.isMatch(stack)) { addContent(new MMalignmark(stack)); } else if (MMaction.isMatch(stack)) { addContent(new MMaction(stack)); } else { break; } } }
public class ActiveManagementCoordinator implements ManagementCoordinator { private static final String C3P0_REGISTRY_NAME = "com.mchange.v2.c3p0:type=C3P0Registry"; // MT: thread-safe static final MLogger logger = MLog.getLogger(ActiveManagementCoordinator.class); MBeanServer mbs; public ActiveManagementCoordinator() throws Exception { this.mbs = ManagementFactory.getPlatformMBeanServer(); } public void attemptManageC3P0Registry() { try { ObjectName name = new ObjectName(C3P0_REGISTRY_NAME); 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); } } public void attemptUnmanageC3P0Registry() { try { ObjectName name = new ObjectName(C3P0_REGISTRY_NAME); 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); } } 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); } } 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 String getPdsObjectNameStr(PooledDataSource pds) { return "com.mchange.v2.c3p0:type=PooledDataSource[" + pds.getIdentityToken() + "]"; } }
public class ActiveManagementCoordinator implements ManagementCoordinator { public static final String C3P0_REGISTRY_NAME_KEY = "com.mchange.v2.c3p0.management.RegistryName"; private static final String C3P0_REGISTRY_NAME_PFX = "com.mchange.v2.c3p0:type=C3P0Registry"; public static final String EXCLUDE_IDENTITY_TOKEN_KEY = "com.mchange.v2.c3p0.management.ExcludeIdentityToken"; // MT: thread-safe static final MLogger logger = MLog.getLogger(ActiveManagementCoordinator.class); static final boolean EXCLUDE_IDENTITY_TOKEN; static { String excludeStr = C3P0Config.getMultiPropertiesConfig().getProperty(EXCLUDE_IDENTITY_TOKEN_KEY); if (excludeStr == null) EXCLUDE_IDENTITY_TOKEN = false; else EXCLUDE_IDENTITY_TOKEN = Boolean.parseBoolean(excludeStr.trim().toLowerCase()); if (EXCLUDE_IDENTITY_TOKEN) logger.info( EXCLUDE_IDENTITY_TOKEN_KEY + " set to true; please ensure unique dataSourceName values are set for all PooledDataSources."); } final MBeanServer mbs; final String regName; public ActiveManagementCoordinator() throws Exception { this.mbs = ManagementFactory.getPlatformMBeanServer(); this.regName = getRegistryName(); } 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); } } 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); } } 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 void attemptUnmanagePooledDataSource(PooledDataSource pds) { String nameStr = null; try { nameStr = getPdsObjectNameStr(pds); ObjectName name = new ObjectName(nameStr); if (mbs.isRegistered(name)) { mbs.unregisterMBean(name); if (logger.isLoggable(MLevel.FINE)) logger.log(MLevel.FINE, "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 == null ? pds.toString() : nameStr) + "] ", e); } } static String getPdsObjectNameStr(PooledDataSource pds) { String dataSourceName = pds.getDataSourceName(); // if we are excluding the identity token attribute, then we always need a valid name attribute. // hopefully users who set EXCLUDE_IDENTITY_TOKEN will update dataSourceName to a reasonable // value. // in the meantime, we use the identity token value for the name. // // but note that at present, pds.getDataSourceName() returns the identity token when // dataSourceName // is unset or set to null. So, this predicate is unlikely ever to be true. if (dataSourceName == null && EXCLUDE_IDENTITY_TOKEN) dataSourceName = pds.getIdentityToken(); // when EXCLUDE_IDENTITY_TOKEN is false, in practice we nearly always generate a 3-attribute // name (type, identityToken, name), because even when dataSourceName is not set or set to null, // getDataSourceName() returns the identity token rather than null. // // when EXCLUDE_IDENTITY_TOKEN is true, we reliably generate a two-attribute name. StringBuilder sb = new StringBuilder(256); sb.append("com.mchange.v2.c3p0:type=PooledDataSource"); if (!EXCLUDE_IDENTITY_TOKEN) { sb.append(",identityToken="); sb.append(pds.getIdentityToken()); } if (dataSourceName != null) { sb.append(",name="); sb.append(dataSourceName); } return sb.toString(); // String out = "com.mchange.v2.c3p0:type=PooledDataSource,identityToken=" + // pds.getIdentityToken(); // if ( dataSourceName != null ) // out += ",name=" + dataSourceName; // return out; } private static String getRegistryName() { String name = C3P0Config.getMultiPropertiesConfig().getProperty(C3P0_REGISTRY_NAME_KEY); if (name == null) name = C3P0_REGISTRY_NAME_PFX; // a name property is optional else name = C3P0_REGISTRY_NAME_PFX + ",name=" + name; return name; } }
public class DefaultC3P0ConfigFinder implements C3P0ConfigFinder { static final String XML_CFG_FILE_KEY = "com.mchange.v2.c3p0.cfg.xml"; static final String CLASSLOADER_RESOURCE_PREFIX = "classloader:"; static final MLogger logger = MLog.getLogger(DefaultC3P0ConfigFinder.class); final boolean warn_of_xml_overrides; public DefaultC3P0ConfigFinder(boolean warn_of_xml_overrides) { this.warn_of_xml_overrides = warn_of_xml_overrides; } public DefaultC3P0ConfigFinder() { this(false); } public C3P0Config findConfig() throws Exception { C3P0Config out; HashMap flatDefaults = C3P0ConfigUtils.extractHardcodedC3P0Defaults(); // this includes System properties, but we have to check for System properties // again, since we want system properties to override unspecified user, default-config // properties in the XML flatDefaults.putAll(C3P0ConfigUtils.extractC3P0PropertiesResources()); String cfgFile = C3P0Config.getPropsFileConfigProperty(XML_CFG_FILE_KEY); if (cfgFile == null) { C3P0Config xmlConfig = C3P0ConfigXmlUtils.extractXmlConfigFromDefaultResource(); if (xmlConfig != null) { insertDefaultsUnderNascentConfig(flatDefaults, xmlConfig); out = xmlConfig; mbOverrideWarning("resource", C3P0ConfigXmlUtils.XML_CONFIG_RSRC_PATH); } else out = C3P0ConfigUtils.configFromFlatDefaults(flatDefaults); } else { cfgFile = cfgFile.trim(); InputStream is = null; try { if (cfgFile.startsWith(CLASSLOADER_RESOURCE_PREFIX)) { ClassLoader cl = this.getClass().getClassLoader(); String rsrcPath = cfgFile.substring(CLASSLOADER_RESOURCE_PREFIX.length()); // eliminate leading slash because ClassLoader.getResource // is always absolute and does not expect a leading slash if (rsrcPath.startsWith("/")) rsrcPath = rsrcPath.substring(1); is = cl.getResourceAsStream(rsrcPath); if (is == null) throw new FileNotFoundException( "Specified ClassLoader resource '" + rsrcPath + "' could not be found. " + "[ Found in configuration: " + XML_CFG_FILE_KEY + '=' + cfgFile + " ]"); mbOverrideWarning("resource", rsrcPath); } else { is = new BufferedInputStream(new FileInputStream(cfgFile)); mbOverrideWarning("file", cfgFile); } C3P0Config xmlConfig = C3P0ConfigXmlUtils.extractXmlConfigFromInputStream(is); insertDefaultsUnderNascentConfig(flatDefaults, xmlConfig); out = xmlConfig; } finally { try { if (is != null) is.close(); } catch (Exception e) { e.printStackTrace(); } } } // overwrite default, unspecified user config with System properties // defined values Properties sysPropConfig = C3P0ConfigUtils.findAllC3P0SystemProperties(); out.defaultConfig.props.putAll(sysPropConfig); return out; } private void insertDefaultsUnderNascentConfig(HashMap flatDefaults, C3P0Config config) { flatDefaults.putAll(config.defaultConfig.props); config.defaultConfig.props = flatDefaults; } 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."); } }
public final class SqlUtils { static final MLogger logger = MLog.getLogger(SqlUtils.class); // protected by SqlUtils.class' lock static final DateFormat tsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS"); public static final String DRIVER_MANAGER_USER_PROPERTY = "user"; public static final String DRIVER_MANAGER_PASSWORD_PROPERTY = "password"; public static String escapeBadSqlPatternChars(String s) { StringBuffer sb = new StringBuffer(s); for (int i = 0, len = sb.length(); i < len; ++i) if (sb.charAt(i) == '\'') { sb.insert(i, '\''); ++len; i += 2; } return sb.toString(); } public static synchronized String escapeAsTimestamp(Date date) { return "{ts '" + tsdf.format(date) + "'}"; } public static SQLException toSQLException(Throwable t) { return toSQLException(null, t); } public static SQLException toSQLException(String msg, Throwable t) { return toSQLException(msg, null, t); } 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); } } public static SQLClientInfoException toSQLClientInfoException(Throwable t) { if (t instanceof SQLClientInfoException) return (SQLClientInfoException) t; else if (t.getCause() instanceof SQLClientInfoException) return (SQLClientInfoException) t.getCause(); else if (t instanceof SQLException) { SQLException sqle = (SQLException) t; return new SQLClientInfoException( sqle.getMessage(), sqle.getSQLState(), sqle.getErrorCode(), null, t); } else return new SQLClientInfoException(t.getMessage(), null, t); } private SqlUtils() {} }
/** @deprecated Please use com.mchange.v2.c3p0.jboss.C3P0PooledDataSource */ public class C3P0PooledDataSource implements C3P0PooledDataSourceMBean { private static final MLogger logger = MLog.getLogger(C3P0PooledDataSource.class); String jndiName; ComboPooledDataSource combods = new ComboPooledDataSource(); private void rebind() throws NamingException { rebind(null); } private void rebind(String unbindName) throws NamingException { InitialContext ictx = new InitialContext(); if (unbindName != null) ictx.unbind(unbindName); if (jndiName != null) { // Thanks to David D. Kilzer for this code to auto-create // subcontext paths! Name name = ictx.getNameParser(jndiName).parse(jndiName); Context ctx = ictx; for (int i = 0, max = name.size() - 1; i < max; i++) { try { ctx = ctx.createSubcontext(name.get(i)); } catch (NameAlreadyBoundException ignore) { ctx = (Context) ctx.lookup(name.get(i)); } } ictx.rebind(jndiName, combods); } } // Jndi Setup Names public void setJndiName(String jndiName) throws NamingException { String unbindName = this.jndiName; this.jndiName = jndiName; rebind(unbindName); } public String getJndiName() { return jndiName; } // DriverManagerDataSourceProperties (count: 4) public String getDescription() { return combods.getDescription(); } public void setDescription(String description) throws NamingException { combods.setDescription(description); rebind(); } public String getDriverClass() { return combods.getDriverClass(); } public void setDriverClass(String driverClass) throws PropertyVetoException, NamingException { combods.setDriverClass(driverClass); rebind(); } public String getJdbcUrl() { return combods.getJdbcUrl(); } public void setJdbcUrl(String jdbcUrl) throws NamingException { combods.setJdbcUrl(jdbcUrl); rebind(); } // DriverManagerDataSource "virtual properties" based on properties public String getUser() { return combods.getUser(); } public void setUser(String user) throws NamingException { combods.setUser(user); rebind(); } public String getPassword() { return combods.getPassword(); } public void setPassword(String password) throws NamingException { combods.setPassword(password); rebind(); } // WrapperConnectionPoolDataSource properties (count: 21) public int getCheckoutTimeout() { return combods.getCheckoutTimeout(); } public void setCheckoutTimeout(int checkoutTimeout) throws NamingException { combods.setCheckoutTimeout(checkoutTimeout); rebind(); } public int getAcquireIncrement() { return combods.getAcquireIncrement(); } public void setAcquireIncrement(int acquireIncrement) throws NamingException { combods.setAcquireIncrement(acquireIncrement); rebind(); } public int getAcquireRetryAttempts() { return combods.getAcquireRetryAttempts(); } public void setAcquireRetryAttempts(int acquireRetryAttempts) throws NamingException { combods.setAcquireRetryAttempts(acquireRetryAttempts); rebind(); } public int getAcquireRetryDelay() { return combods.getAcquireRetryDelay(); } public void setAcquireRetryDelay(int acquireRetryDelay) throws NamingException { combods.setAcquireRetryDelay(acquireRetryDelay); rebind(); } public boolean isAutoCommitOnClose() { return combods.isAutoCommitOnClose(); } public void setAutoCommitOnClose(boolean autoCommitOnClose) throws NamingException { combods.setAutoCommitOnClose(autoCommitOnClose); rebind(); } public String getConnectionTesterClassName() { return combods.getConnectionTesterClassName(); } public void setConnectionTesterClassName(String connectionTesterClassName) throws PropertyVetoException, NamingException { combods.setConnectionTesterClassName(connectionTesterClassName); rebind(); } public String getAutomaticTestTable() { return combods.getAutomaticTestTable(); } public void setAutomaticTestTable(String automaticTestTable) throws NamingException { combods.setAutomaticTestTable(automaticTestTable); rebind(); } public boolean isForceIgnoreUnresolvedTransactions() { return combods.isForceIgnoreUnresolvedTransactions(); } public void setForceIgnoreUnresolvedTransactions(boolean forceIgnoreUnresolvedTransactions) throws NamingException { combods.setForceIgnoreUnresolvedTransactions(forceIgnoreUnresolvedTransactions); rebind(); } public int getIdleConnectionTestPeriod() { return combods.getIdleConnectionTestPeriod(); } public void setIdleConnectionTestPeriod(int idleConnectionTestPeriod) throws NamingException { combods.setIdleConnectionTestPeriod(idleConnectionTestPeriod); rebind(); } public int getInitialPoolSize() { return combods.getInitialPoolSize(); } public void setInitialPoolSize(int initialPoolSize) throws NamingException { combods.setInitialPoolSize(initialPoolSize); rebind(); } public int getMaxIdleTime() { return combods.getMaxIdleTime(); } public void setMaxIdleTime(int maxIdleTime) throws NamingException { combods.setMaxIdleTime(maxIdleTime); rebind(); } public int getMaxPoolSize() { return combods.getMaxPoolSize(); } public void setMaxPoolSize(int maxPoolSize) throws NamingException { combods.setMaxPoolSize(maxPoolSize); rebind(); } public int getMaxStatements() { return combods.getMaxStatements(); } public void setMaxStatements(int maxStatements) throws NamingException { combods.setMaxStatements(maxStatements); rebind(); } public int getMaxStatementsPerConnection() { return combods.getMaxStatementsPerConnection(); } public void setMaxStatementsPerConnection(int maxStatementsPerConnection) throws NamingException { combods.setMaxStatementsPerConnection(maxStatementsPerConnection); rebind(); } public int getMinPoolSize() { return combods.getMinPoolSize(); } public void setMinPoolSize(int minPoolSize) throws NamingException { combods.setMinPoolSize(minPoolSize); rebind(); } public int getPropertyCycle() { return combods.getPropertyCycle(); } public void setPropertyCycle(int propertyCycle) throws NamingException { combods.setPropertyCycle(propertyCycle); rebind(); } public boolean isBreakAfterAcquireFailure() { return combods.isBreakAfterAcquireFailure(); } public void setBreakAfterAcquireFailure(boolean breakAfterAcquireFailure) throws NamingException { combods.setBreakAfterAcquireFailure(breakAfterAcquireFailure); rebind(); } public boolean isTestConnectionOnCheckout() { return combods.isTestConnectionOnCheckout(); } public void setTestConnectionOnCheckout(boolean testConnectionOnCheckout) throws NamingException { combods.setTestConnectionOnCheckout(testConnectionOnCheckout); rebind(); } public boolean isTestConnectionOnCheckin() { return combods.isTestConnectionOnCheckin(); } public void setTestConnectionOnCheckin(boolean testConnectionOnCheckin) throws NamingException { combods.setTestConnectionOnCheckin(testConnectionOnCheckin); rebind(); } public boolean isUsesTraditionalReflectiveProxies() { return combods.isUsesTraditionalReflectiveProxies(); } public void setUsesTraditionalReflectiveProxies(boolean usesTraditionalReflectiveProxies) throws NamingException { combods.setUsesTraditionalReflectiveProxies(usesTraditionalReflectiveProxies); rebind(); } public String getPreferredTestQuery() { return combods.getPreferredTestQuery(); } public void setPreferredTestQuery(String preferredTestQuery) throws NamingException { combods.setPreferredTestQuery(preferredTestQuery); rebind(); } // PoolBackedDataSource properties (count: 2) public String getDataSourceName() { return combods.getDataSourceName(); } public void setDataSourceName(String name) throws NamingException { combods.setDataSourceName(name); rebind(); } public int getNumHelperThreads() { return combods.getNumHelperThreads(); } public void setNumHelperThreads(int numHelperThreads) throws NamingException { combods.setNumHelperThreads(numHelperThreads); rebind(); } // shared properties (count: 1) public String getFactoryClassLocation() { return combods.getFactoryClassLocation(); } public void setFactoryClassLocation(String factoryClassLocation) throws NamingException { combods.setFactoryClassLocation(factoryClassLocation); rebind(); } // PooledDataSource statistics public int getNumUserPools() throws SQLException { return combods.getNumUserPools(); } public int getNumConnectionsDefaultUser() throws SQLException { return combods.getNumConnectionsDefaultUser(); } public int getNumIdleConnectionsDefaultUser() throws SQLException { return combods.getNumIdleConnectionsDefaultUser(); } public int getNumBusyConnectionsDefaultUser() throws SQLException { return combods.getNumBusyConnectionsDefaultUser(); } public int getNumUnclosedOrphanedConnectionsDefaultUser() throws SQLException { return combods.getNumUnclosedOrphanedConnectionsDefaultUser(); } public int getNumConnections(String username, String password) throws SQLException { return combods.getNumConnections(username, password); } public int getNumIdleConnections(String username, String password) throws SQLException { return combods.getNumIdleConnections(username, password); } public int getNumBusyConnections(String username, String password) throws SQLException { return combods.getNumBusyConnections(username, password); } public int getNumUnclosedOrphanedConnections(String username, String password) throws SQLException { return combods.getNumUnclosedOrphanedConnections(username, password); } public int getNumConnectionsAllUsers() throws SQLException { return combods.getNumConnectionsAllUsers(); } public int getNumIdleConnectionsAllUsers() throws SQLException { return combods.getNumIdleConnectionsAllUsers(); } public int getNumBusyConnectionsAllUsers() throws SQLException { return combods.getNumBusyConnectionsAllUsers(); } public int getNumUnclosedOrphanedConnectionsAllUsers() throws SQLException { return combods.getNumUnclosedOrphanedConnectionsAllUsers(); } // PooledDataSource operations public void softResetDefaultUser() throws SQLException { combods.softResetDefaultUser(); } public void softReset(String username, String password) throws SQLException { combods.softReset(username, password); } public void softResetAllUsers() throws SQLException { combods.softResetAllUsers(); } public void hardReset() throws SQLException { combods.hardReset(); } public void close() throws SQLException { combods.close(); } // JBoss only... (but these methods need not be called for the mbean to work) public void create() throws Exception {} // the mbean works without this, but if called we start populating the pool early public void start() throws Exception { // System.err.println("Bound C3P0 PooledDataSource to name '" + jndiName + "'. Starting..."); logger.log(MLevel.INFO, "Bound C3P0 PooledDataSource to name ''{0}''. Starting...", jndiName); combods.getNumBusyConnectionsDefaultUser(); // just touch the datasource to start it up. } public void stop() {} public void destroy() {} }