mirror of
https://github.com/ebean-orm/ebean.git
synced 2026-11-18 14:58:47 +00:00
initial add of EbeanORM server based on v2.8.1
This commit is contained in:
1 parent
2b74d0f9d9
commit
96ce4c0ddf
1188 files changed
+135034
No files matched your search
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A buffer especially designed for Busy PooledConnections.
|
||||
* <p>
|
||||
* All thread safety controlled externally (by PooledConnectionQueue).
|
||||
* </p>
|
||||
* <p>
|
||||
* It has a set of 'slots' and PooledConnections know which slot they went into
|
||||
* and this allows for fast addition and removal (by slotId without looping).
|
||||
* The capacity will increase on demand by the 'growBy' amount.
|
||||
* </p>
|
||||
*
|
||||
* @author rbygrave
|
||||
*
|
||||
*/
|
||||
class BusyConnectionBuffer {
|
||||
|
||||
private PooledConnection[] slots;
|
||||
|
||||
private int growBy;
|
||||
|
||||
private int size;
|
||||
|
||||
private int pos = -1;
|
||||
|
||||
/**
|
||||
* Create the buffer with an initial capacity and fixed growBy.
|
||||
* We generally do not want the buffer to grow very often.
|
||||
*
|
||||
* @param capacity
|
||||
* the initial capacity
|
||||
* @param growBy
|
||||
* the fixed amount to grow the buffer by.
|
||||
*/
|
||||
protected BusyConnectionBuffer(int capacity, int growBy) {
|
||||
this.slots = new PooledConnection[capacity];
|
||||
this.growBy = growBy;
|
||||
}
|
||||
|
||||
/**
|
||||
* We can only grow (not shrink) the capacity.
|
||||
*/
|
||||
private void setCapacity(int newCapacity) {
|
||||
if (newCapacity > slots.length){
|
||||
PooledConnection[] current = this.slots;
|
||||
this.slots = new PooledConnection[newCapacity];
|
||||
System.arraycopy(current, 0, this.slots, 0, current.length);
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return Arrays.toString(slots);
|
||||
}
|
||||
|
||||
protected int getCapacity() {
|
||||
return slots.length;
|
||||
}
|
||||
|
||||
protected int size(){
|
||||
return size;
|
||||
}
|
||||
|
||||
protected boolean isEmpty(){
|
||||
return size == 0;
|
||||
}
|
||||
|
||||
protected int add(PooledConnection pc){
|
||||
if (size == slots.length){
|
||||
// grow the capacity
|
||||
setCapacity(slots.length + growBy);
|
||||
}
|
||||
++size;
|
||||
int slot = nextEmptySlot();
|
||||
pc.setSlotId(slot);
|
||||
slots[slot] = pc;
|
||||
return size;
|
||||
}
|
||||
|
||||
protected boolean remove(PooledConnection pc) {
|
||||
--size;
|
||||
int slotId = pc.getSlotId();
|
||||
if (slots[slotId] != pc){
|
||||
return false;
|
||||
}
|
||||
slots[slotId] = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get a shallow read only List of the busy connections.
|
||||
* <p>
|
||||
* Note that the {@link #remove(PooledConnection)} MUST be used to remove PooledConnections.
|
||||
* </p>
|
||||
* @return
|
||||
*/
|
||||
protected List<PooledConnection> getShallowCopy() {
|
||||
ArrayList<PooledConnection> tmp = new ArrayList<PooledConnection>();
|
||||
for (int i = 0; i < slots.length; i++) {
|
||||
if (slots[i] != null){
|
||||
tmp.add(slots[i]);
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableList(tmp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the position of the next empty slot.
|
||||
*/
|
||||
private int nextEmptySlot() {
|
||||
|
||||
// search forward
|
||||
while(++pos < slots.length) {
|
||||
if (slots[pos] == null){
|
||||
return pos;
|
||||
}
|
||||
}
|
||||
// search from beginning
|
||||
pos = -1;
|
||||
while(++pos < slots.length) {
|
||||
if (slots[pos] == null){
|
||||
return pos;
|
||||
}
|
||||
}
|
||||
|
||||
// not expecting this
|
||||
throw new RuntimeException("No Empty Slot Found?");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
|
||||
/**
|
||||
* Listens for alerting events such as DataSource down.
|
||||
*/
|
||||
public interface DataSourceAlertListener {
|
||||
|
||||
/**
|
||||
* Send an Alert saying the dataSource is down.
|
||||
*/
|
||||
public void dataSourceDown(String dataSourceName);
|
||||
|
||||
/**
|
||||
* Send an Alert saying the dataSource is back up.
|
||||
*/
|
||||
public void dataSourceUp(String dataSourceName);
|
||||
|
||||
/**
|
||||
* Send an Alert saying the dataSource has reached a high
|
||||
* number of connections.
|
||||
*/
|
||||
public void warning(String subject, String msg);
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A general DataSource exception.
|
||||
*/
|
||||
public class DataSourceException extends RuntimeException
|
||||
{
|
||||
static final long serialVersionUID = 7061559938704539844L;
|
||||
|
||||
public DataSourceException(Exception cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public DataSourceException(String s, Exception cause) {
|
||||
super(s, cause);
|
||||
}
|
||||
|
||||
public DataSourceException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebean.config.DataSourceConfig;
|
||||
|
||||
/**
|
||||
* Manages access to named DataSources using singleton scope.
|
||||
*/
|
||||
public final class DataSourceGlobalManager {
|
||||
|
||||
private static final DataSourceManager manager = new DataSourceManager();
|
||||
|
||||
private DataSourceGlobalManager() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true when the dataSource is shutting down.
|
||||
*/
|
||||
public static boolean isShuttingDown() {
|
||||
return manager.isShuttingDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shutdown the dataSources.
|
||||
*/
|
||||
public static void shutdown() {
|
||||
manager.shutdown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the list of DataSourcePool's.
|
||||
*/
|
||||
public static List<DataSourcePool> getPools() {
|
||||
return manager.getPools();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a DataSource pool by its name.
|
||||
*/
|
||||
public static DataSourcePool getDataSource(String name) {
|
||||
return manager.getDataSource(name);
|
||||
}
|
||||
|
||||
public static DataSourcePool getDataSource(String name, DataSourceConfig dsConfig) {
|
||||
return manager.getDataSource(name, dsConfig);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Hashtable;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebean.config.DataSourceConfig;
|
||||
import com.avaje.ebean.config.GlobalProperties;
|
||||
import com.avaje.ebeaninternal.api.ClassUtil;
|
||||
import com.avaje.ebeaninternal.server.lib.BackgroundRunnable;
|
||||
import com.avaje.ebeaninternal.server.lib.BackgroundThread;
|
||||
|
||||
|
||||
/**
|
||||
* Manages access to named DataSources.
|
||||
*/
|
||||
public class DataSourceManager implements DataSourceNotify {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(DataSourceManager.class.getName());
|
||||
|
||||
/**
|
||||
* An alerter that notifies when the database has problems.
|
||||
*/
|
||||
private final DataSourceAlertListener alertlistener;
|
||||
|
||||
/**
|
||||
* Cache of the named DataSources.
|
||||
*/
|
||||
private final Hashtable<String,DataSourcePool> dsMap = new Hashtable<String, DataSourcePool>();
|
||||
|
||||
/**
|
||||
* Monitor for creating dataSources.
|
||||
*/
|
||||
private final Object monitor = new Object();
|
||||
|
||||
/**
|
||||
* The database checker registered with BackgroundThread.
|
||||
*/
|
||||
private final BackgroundRunnable dbChecker;
|
||||
|
||||
/**
|
||||
* The frequency to test db while it is up.
|
||||
*/
|
||||
private final int dbUpFreqInSecs;
|
||||
|
||||
/**
|
||||
* The frequency to test db while it is down.
|
||||
*/
|
||||
private final int dbDownFreqInSecs;
|
||||
|
||||
/**
|
||||
* Set to true when shutting down.
|
||||
*/
|
||||
private boolean shuttingDown;
|
||||
|
||||
private boolean deregisterDriver;
|
||||
|
||||
/**
|
||||
* Construct with explicit ConfigProperties.
|
||||
*/
|
||||
public DataSourceManager() {
|
||||
|
||||
this.alertlistener = createAlertListener();
|
||||
|
||||
// perform heart beat every 30 seconds by default
|
||||
this.dbUpFreqInSecs = GlobalProperties.getInt("datasource.heartbeatfreq",30);
|
||||
this.dbDownFreqInSecs = GlobalProperties.getInt("datasource.deadbeatfreq",10);
|
||||
this.dbChecker = new BackgroundRunnable(new Checker(), dbUpFreqInSecs);
|
||||
this.deregisterDriver = GlobalProperties.getBoolean("datasource.deregisterDriver", true);
|
||||
|
||||
try {
|
||||
BackgroundThread.add(dbChecker);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
|
||||
private DataSourceAlertListener createAlertListener() throws DataSourceException {
|
||||
|
||||
String alertCN = GlobalProperties.get("datasource.alert.class", null);
|
||||
if (alertCN == null){
|
||||
return new SimpleAlerter();
|
||||
|
||||
} else {
|
||||
try {
|
||||
return (DataSourceAlertListener)ClassUtil.newInstance(alertCN, this.getClass());
|
||||
|
||||
} catch (Exception ex){
|
||||
throw new DataSourceException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an alert to say the dataSource is back up.
|
||||
*/
|
||||
public void notifyDataSourceUp(String dataSourceName){
|
||||
|
||||
dbChecker.setFreqInSecs(dbUpFreqInSecs);
|
||||
|
||||
if (alertlistener != null){
|
||||
alertlistener.dataSourceUp(dataSourceName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an alert to say the dataSource is down.
|
||||
*/
|
||||
public void notifyDataSourceDown(String dataSourceName){
|
||||
|
||||
dbChecker.setFreqInSecs(dbDownFreqInSecs);
|
||||
|
||||
if (alertlistener != null){
|
||||
alertlistener.dataSourceDown(dataSourceName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an alert to say the dataSource is getting close to its max size.
|
||||
*/
|
||||
public void notifyWarning(String subject, String msg){
|
||||
if (alertlistener != null){
|
||||
alertlistener.warning(subject, msg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true when the dataSource is shutting down.
|
||||
*/
|
||||
public boolean isShuttingDown() {
|
||||
synchronized(monitor) {
|
||||
return shuttingDown;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shutdown the dataSources.
|
||||
*/
|
||||
public void shutdown() {
|
||||
|
||||
synchronized(monitor) {
|
||||
|
||||
this.shuttingDown = true;
|
||||
|
||||
Collection<DataSourcePool> values = dsMap.values();
|
||||
for (DataSourcePool ds : values) {
|
||||
try {
|
||||
ds.shutdown();
|
||||
} catch (DataSourceException e) {
|
||||
// should never be thrown as the DataSources are all created...
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
if (deregisterDriver){
|
||||
for (DataSourcePool ds : values) {
|
||||
ds.deregisterDriver();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the DataSourcePool's.
|
||||
*/
|
||||
public List<DataSourcePool> getPools() {
|
||||
synchronized(monitor) {
|
||||
// create a copy of the DataSourcePool's
|
||||
ArrayList<DataSourcePool> list = new ArrayList<DataSourcePool>();
|
||||
list.addAll(dsMap.values());
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the dataSource using the default ConfigProperties.
|
||||
*/
|
||||
public DataSourcePool getDataSource(String name) {
|
||||
return getDataSource(name, null);
|
||||
}
|
||||
|
||||
|
||||
public DataSourcePool getDataSource(String name, DataSourceConfig dsConfig){
|
||||
|
||||
if (name == null){
|
||||
throw new IllegalArgumentException("name not defined");
|
||||
}
|
||||
|
||||
synchronized(monitor){
|
||||
DataSourcePool pool = dsMap.get(name);
|
||||
if (pool == null){
|
||||
if (dsConfig == null){
|
||||
dsConfig = new DataSourceConfig();
|
||||
dsConfig.loadSettings(name);
|
||||
}
|
||||
pool = new DataSourcePool(this, name, dsConfig);
|
||||
dsMap.put(name, pool);
|
||||
}
|
||||
return pool;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that the database is up by performing a simple query. This should
|
||||
* be done periodically. By default every 30 seconds.
|
||||
*/
|
||||
private void checkDataSource() {
|
||||
|
||||
synchronized (monitor) {
|
||||
if (!isShuttingDown()) {
|
||||
Iterator<DataSourcePool> it = dsMap.values().iterator();
|
||||
while (it.hasNext()) {
|
||||
DataSourcePool ds = it.next();
|
||||
ds.checkDataSource();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs every dbUpFreqInSecs to make sure dataSource is up.
|
||||
*/
|
||||
private final class Checker implements Runnable {
|
||||
|
||||
public void run() {
|
||||
checkDataSource();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
/**
|
||||
* Listener for notifications about the DataSource such as when the DataSource
|
||||
* goes down, up or gets close to it's maximum size.
|
||||
* <p>
|
||||
* The intention is to send email notifications to an administrator (or similar)
|
||||
* when these events occur on the DataSource.
|
||||
* </p>
|
||||
*/
|
||||
public interface DataSourceNotify {
|
||||
|
||||
/**
|
||||
* Send an alert to say the dataSource is back up.
|
||||
*/
|
||||
public void notifyDataSourceUp(String dataSourceName);
|
||||
|
||||
/**
|
||||
* Send an alert to say the dataSource is down.
|
||||
*/
|
||||
public void notifyDataSourceDown(String dataSourceName);
|
||||
|
||||
/**
|
||||
* Send an alert to say the dataSource is getting close to its max size.
|
||||
*/
|
||||
public void notifyWarning(String subject, String msg);
|
||||
}
|
||||
@@ -0,0 +1,927 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import com.avaje.ebean.config.DataSourceConfig;
|
||||
import com.avaje.ebeaninternal.api.ClassUtil;
|
||||
|
||||
/**
|
||||
* A robust DataSource.
|
||||
* <p>
|
||||
* <ul>
|
||||
* <li>Manages the number of connections closing connections that have been idle
|
||||
* for some time.
|
||||
* <li>Notifies when the datasource goes down and comes back up.
|
||||
* <li>Checks for expected downtime which is useful for schedule db backups.
|
||||
* <li>Provides PreparedStatement caching
|
||||
* <li>Knows the busy connections
|
||||
* <li>Traces connections that have been leaked
|
||||
* </ul>
|
||||
* </p>
|
||||
*/
|
||||
public class DataSourcePool implements DataSource {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(DataSourcePool.class.getName());
|
||||
|
||||
/**
|
||||
* The name given to this dataSource.
|
||||
*/
|
||||
private final String name;
|
||||
|
||||
/**
|
||||
* Used to notify of changes to the DataSource status.
|
||||
*/
|
||||
private final DataSourceNotify notify;
|
||||
|
||||
/**
|
||||
* Optional listener that can be notified when connections are got from and
|
||||
* put back into the pool.
|
||||
*/
|
||||
private final DataSourcePoolListener poolListener;
|
||||
|
||||
/**
|
||||
* Properties used to create a Connection.
|
||||
*/
|
||||
private final Properties connectionProps;
|
||||
|
||||
/**
|
||||
* The jdbc connection url.
|
||||
*/
|
||||
private final String databaseUrl;
|
||||
|
||||
/**
|
||||
* The jdbc driver.
|
||||
*/
|
||||
private final String databaseDriver;
|
||||
|
||||
/**
|
||||
* The sql used to test a connection.
|
||||
*/
|
||||
private final String heartbeatsql;
|
||||
|
||||
/**
|
||||
* The transaction isolation level as per java.sql.Connection.
|
||||
*/
|
||||
private final int transactionIsolation;
|
||||
|
||||
/**
|
||||
* The default autoCommit setting for Connections in this pool.
|
||||
*/
|
||||
private final boolean autoCommit;
|
||||
|
||||
/**
|
||||
* Flag set to true to capture stackTraces (can be expensive).
|
||||
*/
|
||||
private boolean captureStackTrace;
|
||||
|
||||
/**
|
||||
* The max size of the stack trace to report.
|
||||
*/
|
||||
private int maxStackTraceSize;
|
||||
|
||||
/**
|
||||
* flag to indicate we have sent an alert message.
|
||||
*/
|
||||
private boolean dataSourceDownAlertSent;
|
||||
|
||||
/**
|
||||
* The time the pool was last trimmed.
|
||||
*/
|
||||
private long lastTrimTime;
|
||||
|
||||
/**
|
||||
* Assume that the DataSource is up. heartBeat checking will discover when
|
||||
* it goes down, and comes back up again.
|
||||
*/
|
||||
private boolean dataSourceUp = true;
|
||||
|
||||
/**
|
||||
* The current alert.
|
||||
*/
|
||||
private boolean inWarningMode;
|
||||
|
||||
/**
|
||||
* The minimum number of connections this pool will maintain.
|
||||
*/
|
||||
private int minConnections;
|
||||
|
||||
/**
|
||||
* The maximum number of connections this pool will grow to.
|
||||
*/
|
||||
private int maxConnections;
|
||||
|
||||
/**
|
||||
* The number of connections to exceed before a warning Alert is fired.
|
||||
*/
|
||||
private int warningSize;
|
||||
|
||||
/**
|
||||
* The time a thread will wait for a connection to become available.
|
||||
*/
|
||||
private int waitTimeoutMillis;
|
||||
|
||||
/**
|
||||
* The size of the preparedStatement cache;
|
||||
*/
|
||||
private int pstmtCacheSize;
|
||||
|
||||
/**
|
||||
* By default trim connections that are inactive for longer than this time.
|
||||
*/
|
||||
private int maxInactiveTimeSecs;
|
||||
|
||||
private final PooledConnectionQueue queue;
|
||||
|
||||
/**
|
||||
* Used to find and close() leaked connections. Leaked connections are
|
||||
* thought to be busy but have not been used for some time. Each time a
|
||||
* connection is used it sets it's lastUsedTime.
|
||||
*/
|
||||
private long leakTimeMinutes;
|
||||
|
||||
public DataSourcePool(DataSourceNotify notify, String name, DataSourceConfig params) {
|
||||
|
||||
this.notify = notify;
|
||||
this.name = name;
|
||||
this.poolListener = createPoolListener(params.getPoolListener());
|
||||
|
||||
this.autoCommit = false;
|
||||
this.transactionIsolation = params.getIsolationLevel();
|
||||
|
||||
this.maxInactiveTimeSecs = params.getMaxInactiveTimeSecs();
|
||||
this.leakTimeMinutes = params.getLeakTimeMinutes();
|
||||
this.captureStackTrace = params.isCaptureStackTrace();
|
||||
this.maxStackTraceSize = params.getMaxStackTraceSize();
|
||||
this.databaseDriver = params.getDriver();
|
||||
this.databaseUrl = params.getUrl();
|
||||
this.pstmtCacheSize = params.getPstmtCacheSize();
|
||||
|
||||
this.minConnections = params.getMinConnections();
|
||||
this.maxConnections = params.getMaxConnections();
|
||||
this.waitTimeoutMillis = params.getWaitTimeoutMillis();
|
||||
this.heartbeatsql = params.getHeartbeatSql();
|
||||
|
||||
queue = new PooledConnectionQueue(this);
|
||||
|
||||
String un = params.getUsername();
|
||||
String pw = params.getPassword();
|
||||
if (un == null) {
|
||||
throw new RuntimeException("DataSource user is null?");
|
||||
}
|
||||
if (pw == null) {
|
||||
throw new RuntimeException("DataSource password is null?");
|
||||
}
|
||||
this.connectionProps = new Properties();
|
||||
this.connectionProps.setProperty("user", un);
|
||||
this.connectionProps.setProperty("password", pw);
|
||||
|
||||
Map<String, String> customProperties = params.getCustomProperties();
|
||||
if (customProperties != null){
|
||||
Set<Entry<String,String>> entrySet = customProperties.entrySet();
|
||||
for (Entry<String, String> entry : entrySet) {
|
||||
this.connectionProps.setProperty(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
initialise();
|
||||
} catch (SQLException ex) {
|
||||
throw new DataSourceException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the DataSourcePoolListener if there is one.
|
||||
*/
|
||||
private DataSourcePoolListener createPoolListener(String cn) {
|
||||
if (cn == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return (DataSourcePoolListener)ClassUtil.newInstance(cn, this.getClass());
|
||||
} catch (Exception e) {
|
||||
throw new DataSourceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void initialise() throws SQLException {
|
||||
|
||||
// Ensure database driver is loaded
|
||||
try {
|
||||
ClassUtil.forName(this.databaseDriver, this.getClass());
|
||||
} catch (Throwable e) {
|
||||
throw new PersistenceException("Problem loading Database Driver [" + this.databaseDriver + "]: "
|
||||
+ e.getMessage(), e);
|
||||
}
|
||||
|
||||
String transIsolation = TransactionIsolation.getLevelDescription(transactionIsolation);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("DataSourcePool [").append(name);
|
||||
sb.append("] autoCommit[").append(autoCommit);
|
||||
sb.append("] transIsolation[").append(transIsolation);
|
||||
sb.append("] min[").append(minConnections);
|
||||
sb.append("] max[").append(maxConnections).append("]");
|
||||
|
||||
logger.info(sb.toString());
|
||||
|
||||
queue.ensureMinimumConnections();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns false.
|
||||
*/
|
||||
public boolean isWrapperFor(Class<?> arg0) throws SQLException {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Not Implemented.
|
||||
*/
|
||||
public <T> T unwrap(Class<T> arg0) throws SQLException {
|
||||
throw new SQLException("Not Implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the dataSource name.
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the max size of stack traces used when trying to find connection pool leaks.
|
||||
* <p>
|
||||
* This is only used when {@link #isCaptureStackTrace()} is true.
|
||||
* </p>
|
||||
*/
|
||||
public int getMaxStackTraceSize() {
|
||||
return maxStackTraceSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns false when the dataSource is down.
|
||||
*/
|
||||
public boolean isDataSourceUp() {
|
||||
return dataSourceUp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the pool hits the warning level.
|
||||
*/
|
||||
protected void notifyWarning(String msg) {
|
||||
|
||||
if (!inWarningMode) {
|
||||
// send an Error to the event log...
|
||||
inWarningMode = true;
|
||||
logger.warning(msg);
|
||||
if (notify != null) {
|
||||
String subject = "DataSourcePool [" + name + "] warning";
|
||||
notify.notifyWarning(subject, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyDataSourceIsDown(SQLException ex) {
|
||||
|
||||
if (!dataSourceDownAlertSent) {
|
||||
String msg = "FATAL: DataSourcePool [" + name + "] is down!!!";
|
||||
logger.log(Level.SEVERE, msg, ex);
|
||||
if (notify != null) {
|
||||
notify.notifyDataSourceDown(name);
|
||||
}
|
||||
dataSourceDownAlertSent = true;
|
||||
|
||||
}
|
||||
if (dataSourceUp) {
|
||||
reset();
|
||||
}
|
||||
dataSourceUp = false;
|
||||
}
|
||||
|
||||
private void notifyDataSourceIsUp() {
|
||||
if (dataSourceDownAlertSent) {
|
||||
String msg = "RESOLVED FATAL: DataSourcePool [" + name + "] is back up!";
|
||||
logger.log(Level.SEVERE, msg);
|
||||
if (notify != null) {
|
||||
notify.notifyDataSourceUp(name);
|
||||
}
|
||||
dataSourceDownAlertSent = false;
|
||||
|
||||
} else if (!dataSourceUp) {
|
||||
logger.log(Level.WARNING, "DataSourcePool [" + name + "] is back up!");
|
||||
}
|
||||
|
||||
if (!dataSourceUp) {
|
||||
dataSourceUp = true;
|
||||
reset();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the dataSource is up. Trim connections.
|
||||
*/
|
||||
protected void checkDataSource() {
|
||||
Connection conn = null;
|
||||
try {
|
||||
// test to see if we can create a new connection...
|
||||
conn = getConnection();
|
||||
testConnection(conn);
|
||||
|
||||
notifyDataSourceIsUp();
|
||||
|
||||
if (System.currentTimeMillis() > (lastTrimTime + (maxInactiveTimeSecs * 1000))) {
|
||||
queue.trim(maxInactiveTimeSecs);
|
||||
lastTrimTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
} catch (SQLException ex) {
|
||||
notifyDataSourceIsDown(ex);
|
||||
} finally {
|
||||
try {
|
||||
if (conn != null) {
|
||||
conn.close();
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
logger.log(Level.WARNING, "Can't close connection in checkDataSource!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Connection that will not be part of the connection pool.
|
||||
*
|
||||
* <p>
|
||||
* When this connection is closed it will not go back into the pool.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If withDefaults is true then the Connection will have the autoCommit and
|
||||
* transaction isolation set to the defaults for the pool.
|
||||
* </p>
|
||||
*/
|
||||
public Connection createUnpooledConnection() throws SQLException {
|
||||
|
||||
try {
|
||||
Connection conn = DriverManager.getConnection(databaseUrl, connectionProps);
|
||||
conn.setAutoCommit(autoCommit);
|
||||
conn.setTransactionIsolation(transactionIsolation);
|
||||
return conn;
|
||||
|
||||
} catch (SQLException ex) {
|
||||
notifyDataSourceIsDown(null);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a new maximum size. The pool should respect this new maximum
|
||||
* immediately and not require a restart. You may want to increase the
|
||||
* maxConnections if the pool gets large and hits the warning level.
|
||||
*/
|
||||
public void setMaxSize(int max) {
|
||||
queue.setMaxSize(max);
|
||||
this.maxConnections = max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the max size this pool can grow to.
|
||||
*/
|
||||
public int getMaxSize() {
|
||||
return maxConnections;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the min size this pool should maintain.
|
||||
*/
|
||||
public void setMinSize(int min) {
|
||||
queue.setMinSize(min);
|
||||
this.minConnections = min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the min size this pool should maintain.
|
||||
*/
|
||||
public int getMinSize() {
|
||||
return minConnections;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a new maximum size. The pool should respect this new maximum
|
||||
* immediately and not require a restart. You may want to increase the
|
||||
* maxConnections if the pool gets large and hits the warning and or alert
|
||||
* levels.
|
||||
*/
|
||||
public void setWarningSize(int warningSize) {
|
||||
queue.setWarningSize(warningSize);
|
||||
this.warningSize = warningSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the warning size. When the pool hits this size it can send a
|
||||
* notify message to an administrator.
|
||||
*/
|
||||
public int getWarningSize() {
|
||||
return warningSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the time in millis that threads will wait when the pool has hit
|
||||
* the max size. These threads wait for connections to be returned by the
|
||||
* busy connections.
|
||||
*/
|
||||
public int getWaitTimeoutMillis() {
|
||||
return waitTimeoutMillis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the time after which inactive connections are trimmed.
|
||||
*/
|
||||
public void setMaxInactiveTimeSecs(int maxInactiveTimeSecs) {
|
||||
this.maxInactiveTimeSecs = maxInactiveTimeSecs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the time after which inactive connections are trimmed.
|
||||
*/
|
||||
public int getMaxInactiveTimeSecs() {
|
||||
return maxInactiveTimeSecs;
|
||||
}
|
||||
|
||||
private void testConnection(Connection conn) throws SQLException {
|
||||
|
||||
if (heartbeatsql == null) {
|
||||
return;
|
||||
}
|
||||
Statement stmt = null;
|
||||
ResultSet rset = null;
|
||||
try {
|
||||
// It should only error IF the DataSource is down ? (or a network
|
||||
// issue?)
|
||||
stmt = conn.createStatement();
|
||||
rset = stmt.executeQuery(heartbeatsql);
|
||||
conn.commit();
|
||||
|
||||
} finally {
|
||||
try {
|
||||
if (rset != null) {
|
||||
rset.close();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
try {
|
||||
if (stmt != null) {
|
||||
stmt.close();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make sure the connection is still ok to use. If not then remove it from
|
||||
* the pool.
|
||||
*/
|
||||
protected boolean validateConnection(PooledConnection conn) {
|
||||
try {
|
||||
if (heartbeatsql == null) {
|
||||
logger.info("Can not test connection as heartbeatsql is not set");
|
||||
return false;
|
||||
}
|
||||
|
||||
testConnection(conn);
|
||||
return true;
|
||||
|
||||
} catch (Exception e) {
|
||||
String desc = "heartbeatsql test failed on connection[" + conn.getName() + "]";
|
||||
logger.warning(desc);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by the PooledConnection themselves, returning themselves to the
|
||||
* pool when they have been finished with.
|
||||
* <p>
|
||||
* Note that connections may not be added back to the pool if returnToPool
|
||||
* is false or if they where created before the recycleTime. In both of
|
||||
* these cases the connection is fully closed and not pooled.
|
||||
* </p>
|
||||
*
|
||||
* @param pooledConnection
|
||||
* the returning connection
|
||||
*
|
||||
*/
|
||||
protected void returnConnection(PooledConnection pooledConnection) {
|
||||
|
||||
if (poolListener != null) {
|
||||
poolListener.onBeforeReturnConnection(pooledConnection);
|
||||
}
|
||||
queue.returnPooledConnection(pooledConnection);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns information describing connections that are currently being used.
|
||||
*/
|
||||
public String getBusyConnectionInformation() {
|
||||
|
||||
return queue.getBusyConnectionInformation();
|
||||
}
|
||||
|
||||
/**
|
||||
* Dumps the busy connection information to the logs.
|
||||
* <p>
|
||||
* This includes the stackTrace elements if they are being captured. This is
|
||||
* useful when needing to look a potential connection pool leaks.
|
||||
* </p>
|
||||
*/
|
||||
public void dumpBusyConnectionInformation() {
|
||||
|
||||
queue.dumpBusyConnectionInformation();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close any busy connections that have not been used for some time.
|
||||
* <p>
|
||||
* These connections are considered to have leaked from the connection pool.
|
||||
* </p>
|
||||
* <p>
|
||||
* Connection leaks occur when code doesn't ensure that connections are
|
||||
* closed() after they have been finished with. There should be an
|
||||
* appropriate try catch finally block to ensure connections are always
|
||||
* closed and put back into the pool.
|
||||
* </p>
|
||||
*/
|
||||
public void closeBusyConnections(long leakTimeMinutes) {
|
||||
|
||||
queue.closeBusyConnections(leakTimeMinutes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Grow the pool by creating a new connection. The connection can either be
|
||||
* added to the available list, or returned.
|
||||
* <p>
|
||||
* This method is protected by synchronisation in calling methods.
|
||||
* </p>
|
||||
*/
|
||||
protected PooledConnection createConnectionForQueue(int connId) throws SQLException {
|
||||
|
||||
try {
|
||||
Connection c = createUnpooledConnection();
|
||||
|
||||
PooledConnection pc = new PooledConnection(this, connId, c);
|
||||
pc.resetForUse();
|
||||
|
||||
if (!dataSourceUp) {
|
||||
notifyDataSourceIsUp();
|
||||
}
|
||||
return pc;
|
||||
|
||||
} catch (SQLException ex) {
|
||||
notifyDataSourceIsDown(ex);
|
||||
throw ex;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Close all the connections in the pool.
|
||||
* <p>
|
||||
* <ul>
|
||||
* <li>Checks that the database is up.
|
||||
* <li>Resets the Alert level.
|
||||
* <li>Closes busy connections that have not been used for some time (aka
|
||||
* leaks).
|
||||
* <li>This closes all the currently available connections.
|
||||
* <li>Busy connections are closed when they are returned to the pool.
|
||||
* </ul>
|
||||
* </p>
|
||||
*/
|
||||
public void reset() {
|
||||
queue.reset(leakTimeMinutes);
|
||||
inWarningMode = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a pooled connection.
|
||||
*/
|
||||
public Connection getConnection() throws SQLException {
|
||||
return getPooledConnection();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a connection from the pool.
|
||||
* <p>
|
||||
* This will grow the pool if all the current connections are busy. This
|
||||
* will go into a wait if the pool has hit its maximum size.
|
||||
* </p>
|
||||
*/
|
||||
public PooledConnection getPooledConnection() throws SQLException {
|
||||
|
||||
PooledConnection c = queue.getPooledConnection();
|
||||
|
||||
if (captureStackTrace) {
|
||||
c.setStackTrace(Thread.currentThread().getStackTrace());
|
||||
}
|
||||
|
||||
if (poolListener != null) {
|
||||
poolListener.onAfterBorrowConnection(c);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to the DataSourceAlertListener to test it. This is so that
|
||||
* you can make sure the alerter is configured correctly etc.
|
||||
*/
|
||||
public void testAlert() {
|
||||
|
||||
String subject = "Test DataSourcePool [" + name + "]";
|
||||
String msg = "Just testing if alert message is sent successfully.";
|
||||
|
||||
if (notify != null) {
|
||||
notify.notifyWarning(subject, msg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This will close all the free connections, and then go into a wait loop,
|
||||
* waiting for the busy connections to be freed.
|
||||
*
|
||||
* <p>
|
||||
* The DataSources's should be shutdown AFTER thread pools. Leaked
|
||||
* Connections are not waited on, as that would hang the server.
|
||||
* </p>
|
||||
*/
|
||||
public void shutdown() {
|
||||
queue.shutdown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the default autoCommit setting Connections in this pool will use.
|
||||
*
|
||||
* @return true if the pool defaults autoCommit to true
|
||||
*/
|
||||
public boolean getAutoCommit() {
|
||||
return autoCommit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the default transaction isolation level connections in this pool
|
||||
* should have.
|
||||
*
|
||||
* @return the default transaction isolation level
|
||||
*/
|
||||
public int getTransactionIsolation() {
|
||||
return transactionIsolation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the connection pool is currently capturing the StackTrace
|
||||
* when connections are 'got' from the pool.
|
||||
* <p>
|
||||
* This is set to true to help diagnose connection pool leaks.
|
||||
* </p>
|
||||
*/
|
||||
public boolean isCaptureStackTrace() {
|
||||
return captureStackTrace;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set this to true means that the StackElements are captured every time a
|
||||
* connection is retrieved from the pool. This can be used to identify
|
||||
* connection pool leaks.
|
||||
*/
|
||||
public void setCaptureStackTrace(boolean captureStackTrace) {
|
||||
this.captureStackTrace = captureStackTrace;
|
||||
}
|
||||
|
||||
/**
|
||||
* Not implemented and shouldn't be used.
|
||||
*/
|
||||
public Connection getConnection(String username, String password) throws SQLException {
|
||||
throw new SQLException("Method not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Not implemented and shouldn't be used.
|
||||
*/
|
||||
public int getLoginTimeout() throws SQLException {
|
||||
throw new SQLException("Method not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Not implemented and shouldn't be used.
|
||||
*/
|
||||
public void setLoginTimeout(int seconds) throws SQLException {
|
||||
throw new SQLException("Method not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns null.
|
||||
*/
|
||||
public PrintWriter getLogWriter() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Not implemented.
|
||||
*/
|
||||
public void setLogWriter(PrintWriter writer) throws SQLException {
|
||||
throw new SQLException("Method not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* For detecting and closing leaked connections. Connections that have been
|
||||
* busy for more than leakTimeMinutes are considered leaks and will be
|
||||
* closed on a reset().
|
||||
* <p>
|
||||
* If you want to use a connection for that longer then you should consider
|
||||
* creating an unpooled connection or setting longRunning to true on that
|
||||
* connection.
|
||||
* </p>
|
||||
*/
|
||||
public void setLeakTimeMinutes(long leakTimeMinutes) {
|
||||
this.leakTimeMinutes = leakTimeMinutes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of minutes after which a busy connection could be
|
||||
* considered leaked from the connection pool.
|
||||
*/
|
||||
public long getLeakTimeMinutes() {
|
||||
return leakTimeMinutes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the preparedStatement cache size.
|
||||
*/
|
||||
public int getPstmtCacheSize() {
|
||||
return pstmtCacheSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the preparedStatement cache size.
|
||||
*/
|
||||
public void setPstmtCacheSize(int pstmtCacheSize) {
|
||||
this.pstmtCacheSize = pstmtCacheSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current status of the connection pool.
|
||||
* <p>
|
||||
* If you pass reset = true then the counters such as
|
||||
* hitCount, waitCount and highWaterMark are reset.
|
||||
* </p>
|
||||
*/
|
||||
public Status getStatus(boolean reset) {
|
||||
return queue.getStatus(reset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deregister the JDBC driver.
|
||||
*/
|
||||
public void deregisterDriver() {
|
||||
try {
|
||||
DriverManager.deregisterDriver(DriverManager.getDriver(this.databaseUrl));
|
||||
String msg = "Deregistered the JDBC driver "+this.databaseDriver;
|
||||
logger.log(Level.FINE, msg);
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error trying to deregister the JDBC driver "+this.databaseDriver;
|
||||
logger.log(Level.WARNING, msg, e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class Status {
|
||||
|
||||
private final String name;
|
||||
private final int minSize;
|
||||
private final int maxSize;
|
||||
private final int free;
|
||||
private final int busy;
|
||||
private final int waiting;
|
||||
private final int highWaterMark;
|
||||
private final int waitCount;
|
||||
private final int hitCount;
|
||||
|
||||
protected Status(String name, int minSize, int maxSize, int free, int busy, int waiting, int highWaterMark,
|
||||
int waitCount, int hitCount) {
|
||||
this.name = name;
|
||||
this.minSize = minSize;
|
||||
this.maxSize = maxSize;
|
||||
this.free = free;
|
||||
this.busy = busy;
|
||||
this.waiting = waiting;
|
||||
this.highWaterMark = highWaterMark;
|
||||
this.waitCount = waitCount;
|
||||
this.hitCount = hitCount;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "min:" + minSize + " max:" + maxSize + " free:" + free + " busy:" + busy + " waiting:" + waiting
|
||||
+ " highWaterMark:" + highWaterMark + " waitCount:" + waitCount + " hitCount:" + hitCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the DataSource name.
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the min pool size.
|
||||
*/
|
||||
public int getMinSize() {
|
||||
return minSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the max pool size.
|
||||
*/
|
||||
public int getMaxSize() {
|
||||
return maxSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current number of free connections in the pool.
|
||||
*/
|
||||
public int getFree() {
|
||||
return free;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current number of busy connections in the pool.
|
||||
*/
|
||||
public int getBusy() {
|
||||
return busy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current number of threads waiting for a connection.
|
||||
*/
|
||||
public int getWaiting() {
|
||||
return waiting;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the high water mark of busy connections.
|
||||
*/
|
||||
public int getHighWaterMark() {
|
||||
return highWaterMark;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the total number of times a thread had to wait.
|
||||
*/
|
||||
public int getWaitCount() {
|
||||
return waitCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the total number of times there was an attempt to get a
|
||||
* connection.
|
||||
* <p>
|
||||
* If the attempt to get a connection failed with a timeout or other
|
||||
* exception those attempts are still included in this hit count.
|
||||
* </p>
|
||||
*/
|
||||
public int getHitCount() {
|
||||
return hitCount;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.sql.Connection;
|
||||
|
||||
|
||||
/**
|
||||
* A {@link DataSourcePool} listener which allows you to hook on the
|
||||
* borrow/return process of getting or returning connections from the pool.
|
||||
* <p>
|
||||
* In the configuration use the poolListener key to configure which listener to
|
||||
* use.
|
||||
* </p>
|
||||
* <p>
|
||||
* Example: datasource.ora10.poolListener=my.very.fancy.PoolListener
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Notice: This listener only works if you are using the default Avaje
|
||||
* {@link DataSourcePool}.
|
||||
* </p>
|
||||
*/
|
||||
public interface DataSourcePoolListener {
|
||||
|
||||
/**
|
||||
* Called after a connection has been retrieved from the connection pool
|
||||
*/
|
||||
public void onAfterBorrowConnection(Connection c);
|
||||
|
||||
/**
|
||||
* Called before a connection will be put back to the connection pool
|
||||
*/
|
||||
public void onBeforeReturnConnection(Connection c);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.URL;
|
||||
import java.sql.Array;
|
||||
import java.sql.Blob;
|
||||
import java.sql.Clob;
|
||||
import java.sql.Date;
|
||||
import java.sql.ParameterMetaData;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.Ref;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Time;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Calendar;
|
||||
|
||||
/**
|
||||
* Extended PreparedStatement that supports caching.
|
||||
* <p>
|
||||
* Designed so that it can be cached by the PooledConnection. It additionally
|
||||
* notes any Exceptions that occur and this is used to ensure bad connections
|
||||
* are removed from the connection pool.
|
||||
* </p>
|
||||
*/
|
||||
public class ExtendedPreparedStatement extends ExtendedStatement implements PreparedStatement {
|
||||
|
||||
/**
|
||||
* The SQL used to create the underlying PreparedStatement.
|
||||
*/
|
||||
final String sql;
|
||||
|
||||
/**
|
||||
* The key used to cache this in the connection.
|
||||
*/
|
||||
final String cacheKey;
|
||||
|
||||
/**
|
||||
* Create a wrapped PreparedStatement that can be cached.
|
||||
*/
|
||||
public ExtendedPreparedStatement(PooledConnection pooledConnection, PreparedStatement pstmt,
|
||||
String sql, String cacheKey) {
|
||||
super(pooledConnection, pstmt);
|
||||
this.sql = sql;
|
||||
this.cacheKey = cacheKey;
|
||||
}
|
||||
|
||||
public PreparedStatement getDelegate() {
|
||||
return pstmt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the key used to cache this on the Connection.
|
||||
*/
|
||||
public String getCacheKey() {
|
||||
return cacheKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the SQL used to create this PreparedStatement.
|
||||
*/
|
||||
public String getSql() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fully close the underlying PreparedStatement. After this we can no longer
|
||||
* reuse the PreparedStatement.
|
||||
*/
|
||||
public void closeDestroy() throws SQLException {
|
||||
pstmt.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the PreparedStatement back into the cache. This doesn't fully
|
||||
* close the underlying PreparedStatement.
|
||||
*/
|
||||
public void close() throws SQLException {
|
||||
// return the connection back into the cache.
|
||||
pooledConnection.returnPreparedStatement(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the last binding for batch execution.
|
||||
*/
|
||||
public void addBatch() throws SQLException {
|
||||
try {
|
||||
pstmt.addBatch();
|
||||
} catch (SQLException e) {
|
||||
// we got an error... need to check this
|
||||
// connection before returning it
|
||||
pooledConnection.addError(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear parameters.
|
||||
*/
|
||||
public void clearParameters() throws SQLException {
|
||||
try {
|
||||
pstmt.clearParameters();
|
||||
} catch (SQLException e) {
|
||||
// we got an error... need to check
|
||||
// this connection before returning it
|
||||
pooledConnection.addError(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* execute the statement.
|
||||
*/
|
||||
public boolean execute() throws SQLException {
|
||||
try {
|
||||
return pstmt.execute();
|
||||
} catch (SQLException e) {
|
||||
// we got an error... need to check
|
||||
// this connection before returning it
|
||||
pooledConnection.addError(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute teh query.
|
||||
*/
|
||||
public ResultSet executeQuery() throws SQLException {
|
||||
try {
|
||||
return pstmt.executeQuery();
|
||||
} catch (SQLException e) {
|
||||
// we got an error... need to check
|
||||
// this connection before returning it
|
||||
pooledConnection.addError(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the dml statement.
|
||||
*/
|
||||
public int executeUpdate() throws SQLException {
|
||||
try {
|
||||
return pstmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
// we got an error... need to check
|
||||
// this connection before returning it
|
||||
pooledConnection.addError(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the MetaData for the query.
|
||||
*/
|
||||
public ResultSetMetaData getMetaData() throws SQLException {
|
||||
try {
|
||||
return pstmt.getMetaData();
|
||||
} catch (SQLException e) {
|
||||
// we got an error... need to check
|
||||
// this connection before returning it
|
||||
pooledConnection.addError(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public ParameterMetaData getParameterMetaData() throws SQLException {
|
||||
return pstmt.getParameterMetaData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setArray(int i, Array x) throws SQLException {
|
||||
pstmt.setArray(i, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
|
||||
pstmt.setAsciiStream(parameterIndex, x, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
|
||||
pstmt.setBigDecimal(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
|
||||
pstmt.setBinaryStream(parameterIndex, x, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setBlob(int i, Blob x) throws SQLException {
|
||||
pstmt.setBlob(i, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
|
||||
pstmt.setBoolean(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setByte(int parameterIndex, byte x) throws SQLException {
|
||||
pstmt.setByte(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
|
||||
pstmt.setBytes(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setCharacterStream(int parameterIndex, Reader reader, int length)
|
||||
throws SQLException {
|
||||
pstmt.setCharacterStream(parameterIndex, reader, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setClob(int i, Clob x) throws SQLException {
|
||||
pstmt.setClob(i, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setDate(int parameterIndex, Date x) throws SQLException {
|
||||
pstmt.setDate(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
|
||||
pstmt.setDate(parameterIndex, x, cal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setDouble(int parameterIndex, double x) throws SQLException {
|
||||
pstmt.setDouble(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setFloat(int parameterIndex, float x) throws SQLException {
|
||||
pstmt.setFloat(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setInt(int parameterIndex, int x) throws SQLException {
|
||||
pstmt.setInt(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setLong(int parameterIndex, long x) throws SQLException {
|
||||
pstmt.setLong(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setNull(int parameterIndex, int sqlType) throws SQLException {
|
||||
pstmt.setNull(parameterIndex, sqlType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException {
|
||||
pstmt.setNull(paramIndex, sqlType, typeName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setObject(int parameterIndex, Object x) throws SQLException {
|
||||
pstmt.setObject(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
|
||||
pstmt.setObject(parameterIndex, x, targetSqlType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setObject(int parameterIndex, Object x, int targetSqlType, int scale)
|
||||
throws SQLException {
|
||||
pstmt.setObject(parameterIndex, x, targetSqlType, scale);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setRef(int i, Ref x) throws SQLException {
|
||||
pstmt.setRef(i, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setShort(int parameterIndex, short x) throws SQLException {
|
||||
pstmt.setShort(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setString(int parameterIndex, String x) throws SQLException {
|
||||
pstmt.setString(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setTime(int parameterIndex, Time x) throws SQLException {
|
||||
pstmt.setTime(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
|
||||
pstmt.setTime(parameterIndex, x, cal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
|
||||
pstmt.setTimestamp(parameterIndex, x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
|
||||
pstmt.setTimestamp(parameterIndex, x, cal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
* @deprecated
|
||||
*/
|
||||
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
|
||||
pstmt.setUnicodeStream(parameterIndex, x, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard PreparedStatement method execution.
|
||||
*/
|
||||
public void setURL(int parameterIndex, URL x) throws SQLException {
|
||||
pstmt.setURL(parameterIndex, x);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import com.avaje.ebeaninternal.jdbc.PreparedStatementDelegator;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.SQLWarning;
|
||||
|
||||
/**
|
||||
* Implements the Statement methods for ExtendedPreparedStatement.
|
||||
* <p>
|
||||
* PreparedStatements should always be used and the intention is that there
|
||||
* should be no use of Statement at all. The implementation here is generally
|
||||
* for the case where someone uses the Statement api on an ExtendedPreparedStatement.
|
||||
* </p>
|
||||
*/
|
||||
public abstract class ExtendedStatement extends PreparedStatementDelegator
|
||||
{
|
||||
|
||||
/**
|
||||
* The pooled connection this Statement belongs to.
|
||||
*/
|
||||
protected final PooledConnection pooledConnection;
|
||||
|
||||
/**
|
||||
* The underlying Statement that this object wraps.
|
||||
*/
|
||||
protected final PreparedStatement pstmt;
|
||||
|
||||
/**
|
||||
* Create the ExtendedStatement for a given pooledConnection.
|
||||
*/
|
||||
public ExtendedStatement(PooledConnection pooledConnection, PreparedStatement pstmt) {
|
||||
super(pstmt);
|
||||
|
||||
this.pooledConnection = pooledConnection;
|
||||
this.pstmt = pstmt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the statement back into the statement cache.
|
||||
*/
|
||||
public abstract void close() throws SQLException;
|
||||
|
||||
/**
|
||||
* Return the underlying connection.
|
||||
*/
|
||||
public Connection getConnection() throws SQLException {
|
||||
try {
|
||||
return pstmt.getConnection();
|
||||
} catch (SQLException e) {
|
||||
pooledConnection.addError(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the sql for batch execution.
|
||||
*/
|
||||
public void addBatch(String sql) throws SQLException {
|
||||
try {
|
||||
pooledConnection.setLastStatement(sql);
|
||||
pstmt.addBatch(sql);
|
||||
} catch (SQLException e) {
|
||||
pooledConnection.addError(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the sql.
|
||||
*/
|
||||
public boolean execute(String sql) throws SQLException {
|
||||
try {
|
||||
pooledConnection.setLastStatement(sql);
|
||||
return pstmt.execute(sql);
|
||||
} catch (SQLException e) {
|
||||
pooledConnection.addError(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the query.
|
||||
*/
|
||||
public ResultSet executeQuery(String sql) throws SQLException {
|
||||
try {
|
||||
pooledConnection.setLastStatement(sql);
|
||||
return pstmt.executeQuery(sql);
|
||||
} catch (SQLException e) {
|
||||
pooledConnection.addError(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the dml sql.
|
||||
*/
|
||||
public int executeUpdate(String sql) throws SQLException {
|
||||
try {
|
||||
pooledConnection.setLastStatement(sql);
|
||||
return pstmt.executeUpdate(sql);
|
||||
} catch (SQLException e) {
|
||||
pooledConnection.addError(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int[] executeBatch() throws SQLException {
|
||||
return pstmt.executeBatch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public void cancel() throws SQLException {
|
||||
pstmt.cancel();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public void clearBatch() throws SQLException {
|
||||
pstmt.clearBatch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public void clearWarnings() throws SQLException {
|
||||
pstmt.clearWarnings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int getFetchDirection() throws SQLException {
|
||||
return pstmt.getFetchDirection();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int getFetchSize() throws SQLException {
|
||||
return pstmt.getFetchSize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int getMaxFieldSize() throws SQLException {
|
||||
return pstmt.getMaxFieldSize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int getMaxRows() throws SQLException {
|
||||
return pstmt.getMaxRows();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public boolean getMoreResults() throws SQLException {
|
||||
return pstmt.getMoreResults();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int getQueryTimeout() throws SQLException {
|
||||
return pstmt.getQueryTimeout();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public ResultSet getResultSet() throws SQLException {
|
||||
return pstmt.getResultSet();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int getResultSetConcurrency() throws SQLException {
|
||||
return pstmt.getResultSetConcurrency();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int getResultSetType() throws SQLException {
|
||||
return pstmt.getResultSetType();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int getUpdateCount() throws SQLException {
|
||||
return pstmt.getUpdateCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public SQLWarning getWarnings() throws SQLException {
|
||||
return pstmt.getWarnings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public void setCursorName(String name) throws SQLException {
|
||||
pstmt.setCursorName(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public void setEscapeProcessing(boolean enable) throws SQLException {
|
||||
pstmt.setEscapeProcessing(enable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public void setFetchDirection(int direction) throws SQLException {
|
||||
pstmt.setFetchDirection(direction);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public void setFetchSize(int rows) throws SQLException {
|
||||
pstmt.setFetchSize(rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public void setMaxFieldSize(int max) throws SQLException {
|
||||
pstmt.setMaxFieldSize(max);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public void setMaxRows(int max) throws SQLException {
|
||||
pstmt.setMaxRows(max);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public void setQueryTimeout(int seconds) throws SQLException {
|
||||
pstmt.setQueryTimeout(seconds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public boolean getMoreResults(int i) throws SQLException {
|
||||
return pstmt.getMoreResults(i);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public ResultSet getGeneratedKeys() throws SQLException {
|
||||
return pstmt.getGeneratedKeys();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int executeUpdate(String s, int i) throws SQLException {
|
||||
return pstmt.executeUpdate(s, i);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int executeUpdate(String s, int[] i) throws SQLException {
|
||||
return pstmt.executeUpdate(s, i);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int executeUpdate(String s, String[] i) throws SQLException {
|
||||
return pstmt.executeUpdate(s, i);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public boolean execute(String s, int i) throws SQLException {
|
||||
return pstmt.execute(s, i);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public boolean execute(String s, int[] i) throws SQLException {
|
||||
return pstmt.execute(s, i);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public boolean execute(String s, String[] i) throws SQLException {
|
||||
return pstmt.execute(s, i);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Statement method call.
|
||||
*/
|
||||
public int getResultSetHoldability() throws SQLException {
|
||||
return pstmt.getResultSetHoldability();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A buffer designed especially to hold free pooled connections.
|
||||
* <p>
|
||||
* It is circular in nature.
|
||||
* </p>
|
||||
* <p>
|
||||
* All thread safety controlled externally (by PooledConnectionQueue).
|
||||
* </p>
|
||||
*
|
||||
* @author rbygrave
|
||||
*
|
||||
*/
|
||||
class FreeConnectionBuffer {
|
||||
|
||||
private PooledConnection[] conns;
|
||||
|
||||
private int removeIndex;
|
||||
|
||||
private int addIndex;
|
||||
|
||||
/**
|
||||
* The current number of connections in the buffer
|
||||
*/
|
||||
private int size;
|
||||
|
||||
protected FreeConnectionBuffer(int capacity) {
|
||||
this.conns = new PooledConnection[capacity];
|
||||
}
|
||||
|
||||
protected int getCapacity() {
|
||||
return conns.length;
|
||||
}
|
||||
|
||||
protected int size() {
|
||||
return size;
|
||||
}
|
||||
|
||||
protected boolean isEmpty() {
|
||||
return size == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add at connection.
|
||||
*/
|
||||
protected void add(PooledConnection pc) {
|
||||
conns[addIndex] = pc;
|
||||
addIndex = inc(addIndex);
|
||||
++size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a connection at current remove position.
|
||||
*/
|
||||
protected PooledConnection remove() {
|
||||
final PooledConnection[] items = this.conns;
|
||||
PooledConnection pc = items[removeIndex];
|
||||
items[removeIndex] = null;
|
||||
removeIndex = inc(removeIndex);
|
||||
--size;
|
||||
return pc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a shallow copy of the free connections.
|
||||
*/
|
||||
protected List<PooledConnection> getShallowCopy() {
|
||||
|
||||
List<PooledConnection> copy = new ArrayList<PooledConnection>(conns.length);
|
||||
for (int i = 0; i < conns.length; i++) {
|
||||
if (conns[i] != null){
|
||||
copy.add(conns[i]);
|
||||
}
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the free list to be the connections in this copy. This is done after
|
||||
* unused connections have been trimmed.
|
||||
* <p>
|
||||
* Not a particularly performant approach but this should not be called very
|
||||
* often
|
||||
* </p>
|
||||
*/
|
||||
protected void setShallowCopy(List<PooledConnection> copy) {
|
||||
|
||||
// reset to empty state
|
||||
this.removeIndex = 0;
|
||||
this.addIndex = 0;
|
||||
this.size = 0;
|
||||
|
||||
// null all the current connections
|
||||
for (int i = 0; i < conns.length; i++) {
|
||||
conns[i] = null;
|
||||
}
|
||||
|
||||
// add connections from the copy
|
||||
for (int i = 0; i < copy.size(); i++) {
|
||||
add(copy.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Increase the capacity of the buffer. This is a relatively expensive
|
||||
* operation but should occur very infrequently.
|
||||
*/
|
||||
protected void setCapacity(int newCapacity) {
|
||||
if (newCapacity > conns.length){
|
||||
|
||||
List<PooledConnection> copy = getShallowCopy();
|
||||
|
||||
// reset to empty state
|
||||
this.removeIndex = 0;
|
||||
this.addIndex = 0;
|
||||
this.size = 0;
|
||||
|
||||
this.conns = new PooledConnection[newCapacity];
|
||||
|
||||
// add the connections back from the copy
|
||||
for (int i = 0; i < copy.size(); i++) {
|
||||
add(copy.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Circularly increment i.
|
||||
*/
|
||||
private final int inc(int i) {
|
||||
return (++i == conns.length)? 0 : i;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,961 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import com.avaje.ebeaninternal.jdbc.ConnectionDelegator;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.SQLWarning;
|
||||
import java.sql.Savepoint;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Is a connection that belongs to a DataSourcePool.
|
||||
*
|
||||
* <p>
|
||||
* It is designed to be part of DataSourcePool. Closing the connection puts it
|
||||
* back into the pool.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* It defaults autoCommit and Transaction Isolation to the defaults of the
|
||||
* DataSourcePool.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* It has caching of Statements and PreparedStatements. Remembers the last
|
||||
* statement that was executed. Keeps statistics on how long it is in use.
|
||||
* </p>
|
||||
*/
|
||||
public class PooledConnection extends ConnectionDelegator
|
||||
{
|
||||
|
||||
private static final Logger logger = Logger.getLogger(PooledConnection.class.getName());
|
||||
|
||||
private static String IDLE_CONNECTION_ACCESSED_ERROR = "Pooled Connection has been accessed whilst idle in the pool, via method: ";
|
||||
|
||||
/**
|
||||
* Set when connection is idle in the pool. In general when in the pool the
|
||||
* connection should not be modified.
|
||||
*/
|
||||
static final int STATUS_IDLE = 88;
|
||||
|
||||
/**
|
||||
* Set when connection given to client.
|
||||
*/
|
||||
static final int STATUS_ACTIVE = 89;
|
||||
|
||||
/**
|
||||
* Set when commit() or rollback() called.
|
||||
*/
|
||||
static final int STATUS_ENDED = 87;
|
||||
|
||||
/**
|
||||
* Name used to identify the PooledConnection for logging.
|
||||
*/
|
||||
final String name;
|
||||
|
||||
/**
|
||||
* The pool this connection belongs to.
|
||||
*/
|
||||
final DataSourcePool pool;
|
||||
|
||||
/**
|
||||
* The underlying connection.
|
||||
*/
|
||||
final Connection connection;
|
||||
|
||||
/**
|
||||
* The time this connection was created.
|
||||
*/
|
||||
final long creationTime;
|
||||
|
||||
/**
|
||||
* Cache of the PreparedStatements
|
||||
*/
|
||||
final PstmtCache pstmtCache;
|
||||
|
||||
final Object pstmtMonitor = new Object();
|
||||
|
||||
/**
|
||||
* The status of the connection. IDLE, ACTIVE or ENDED.
|
||||
*/
|
||||
int status = STATUS_IDLE;
|
||||
|
||||
/**
|
||||
* Set this to true if the connection will be busy for a long time.
|
||||
* <p>
|
||||
* This means it should skip the suspected connection pool leak checking.
|
||||
* </p>
|
||||
*/
|
||||
boolean longRunning;
|
||||
|
||||
/**
|
||||
* Flag to indicate that this connection had errors and should be checked to
|
||||
* make sure it is okay.
|
||||
*/
|
||||
boolean hadErrors;
|
||||
|
||||
/**
|
||||
* The last start time. When the connection was given to a thread.
|
||||
*/
|
||||
long startUseTime;
|
||||
|
||||
/**
|
||||
* The last end time of this connection. This is to calculate the usage
|
||||
* time.
|
||||
*/
|
||||
long lastUseTime;
|
||||
|
||||
/**
|
||||
* The last statement executed by this connection.
|
||||
*/
|
||||
String lastStatement;
|
||||
|
||||
/**
|
||||
* The number of hits against the preparedStatement cache.
|
||||
*/
|
||||
int pstmtHitCounter;
|
||||
|
||||
/**
|
||||
* The number of misses against the preparedStatement cache.
|
||||
*/
|
||||
int pstmtMissCounter;
|
||||
|
||||
/**
|
||||
* The non avaje method that created the connection.
|
||||
*/
|
||||
String createdByMethod;
|
||||
|
||||
/**
|
||||
* Used to find connection pool leaks.
|
||||
*/
|
||||
StackTraceElement[] stackTrace;
|
||||
|
||||
int maxStackTrace;
|
||||
|
||||
/**
|
||||
* Slot position in the BusyConnectionBuffer.
|
||||
*/
|
||||
int slotId;
|
||||
|
||||
/**
|
||||
* Construct the connection that can refer back to the pool it belongs to.
|
||||
* <p>
|
||||
* close() will return the connection back to the pool , while
|
||||
* closeDestroy() will close() the underlining connection properly.
|
||||
* </p>
|
||||
*/
|
||||
public PooledConnection(DataSourcePool pool, int uniqueId, Connection connection) throws SQLException {
|
||||
super(connection);
|
||||
|
||||
this.pool = pool;
|
||||
this.connection = connection;
|
||||
this.name = pool.getName() + "." + uniqueId;
|
||||
this.pstmtCache = new PstmtCache(name, pool.getPstmtCacheSize());
|
||||
this.maxStackTrace = pool.getMaxStackTraceSize();
|
||||
this.creationTime = System.currentTimeMillis();
|
||||
this.lastUseTime = creationTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* For testing the pool without real connections.
|
||||
*/
|
||||
protected PooledConnection(String name) {
|
||||
super(null);
|
||||
this.name = name;
|
||||
this.pool = null;
|
||||
this.connection = null;
|
||||
this.pstmtCache = null;
|
||||
this.maxStackTrace = 0;
|
||||
this.creationTime = System.currentTimeMillis();
|
||||
this.lastUseTime = creationTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the slot position in the busy buffer.
|
||||
*/
|
||||
public int getSlotId() {
|
||||
return slotId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the slot position in the busy buffer.
|
||||
*/
|
||||
public void setSlotId(int slotId) {
|
||||
this.slotId = slotId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the DataSourcePool that this connection belongs to.
|
||||
*/
|
||||
public DataSourcePool getDataSourcePool() {
|
||||
return pool;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the time the connection was created.
|
||||
*/
|
||||
public long getCreationTime() {
|
||||
return creationTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a string to identify the connection.
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return "name["+name+"] startTime["+getStartUseTime()+"] stmt["+getLastStatement()+"] createdBy["+getCreatedByMethod()+"]";
|
||||
}
|
||||
|
||||
public String getStatistics() {
|
||||
return "name["+name+"] startTime["+getStartUseTime()+"] pstmtHits["+pstmtHitCounter+"] pstmtMiss["+pstmtMissCounter+"] "+pstmtCache.getDescription();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the connection should be treated as long running (skip connection pool leak check).
|
||||
*/
|
||||
public boolean isLongRunning() {
|
||||
return longRunning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set this to true if the connection is a long running connection and should skip the
|
||||
* 'suspected connection pool leak' checking.
|
||||
*/
|
||||
public void setLongRunning(boolean longRunning) {
|
||||
this.longRunning = longRunning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the connection fully NOT putting in back into the pool.
|
||||
* <p>
|
||||
* The logErrors parameter exists so that expected errors are not logged
|
||||
* such as when the database is known to be down.
|
||||
* </p>
|
||||
*
|
||||
* @param logErrors
|
||||
* if false then don't log errors when closing
|
||||
*/
|
||||
public void closeConnectionFully(boolean logErrors) {
|
||||
|
||||
//pool.removeConnection(this);
|
||||
|
||||
String msg = "Closing Connection[" + getName() + "]" + " psReuse[" + pstmtHitCounter
|
||||
+ "] psCreate[" + pstmtMissCounter + "] psSize[" + pstmtCache.size() + "]";
|
||||
|
||||
logger.info(msg);
|
||||
|
||||
try {
|
||||
if (connection.isClosed()) {
|
||||
msg = "Closing Connection[" + getName() + "] that is already closed?";
|
||||
logger.log(Level.SEVERE, msg);
|
||||
return;
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
if (logErrors) {
|
||||
msg = "Error when fully closing connection [" + getName() + "]";
|
||||
logger.log(Level.SEVERE, msg, ex);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Iterator<ExtendedPreparedStatement> psi = pstmtCache.values().iterator();
|
||||
while (psi.hasNext()) {
|
||||
ExtendedPreparedStatement ps = (ExtendedPreparedStatement) psi.next();
|
||||
ps.closeDestroy();
|
||||
}
|
||||
|
||||
} catch (SQLException ex) {
|
||||
if (logErrors) {
|
||||
logger.log(Level.WARNING, "Error when closing connection Statements", ex);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
connection.close();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
if (logErrors) {
|
||||
msg = "Error when fully closing connection [" + getName() + "]";
|
||||
logger.log(Level.SEVERE, msg, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A Least Recently used cache of PreparedStatements.
|
||||
*/
|
||||
public PstmtCache getPstmtCache() {
|
||||
return pstmtCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a wrapper ExtendedStatement so that I can get the executed sql. I
|
||||
* want to do this so that I can get the slowest query statments etc, and
|
||||
* log that information.
|
||||
*/
|
||||
public Statement createStatement() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "createStatement()");
|
||||
}
|
||||
try {
|
||||
return connection.createStatement();
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public Statement createStatement(int resultSetType, int resultSetConcurreny)
|
||||
throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "createStatement()");
|
||||
}
|
||||
try {
|
||||
return connection.createStatement(resultSetType, resultSetConcurreny);
|
||||
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a PreparedStatement back into the cache.
|
||||
*/
|
||||
protected void returnPreparedStatement(ExtendedPreparedStatement pstmt) {
|
||||
|
||||
synchronized (pstmtMonitor) {
|
||||
ExtendedPreparedStatement alreadyInCache = pstmtCache.get(pstmt.getCacheKey());
|
||||
|
||||
if (alreadyInCache == null) {
|
||||
// add the returning prepared statement to the cache.
|
||||
// Note that the LRUCache will automatically close fully old unused
|
||||
// PStmts when the cache has hit its maximum size.
|
||||
pstmtCache.put(pstmt.getCacheKey(), pstmt);
|
||||
|
||||
} else {
|
||||
try {
|
||||
// if a entry in the cache exists for the exact same SQL...
|
||||
// then remove it from the cache and close it fully.
|
||||
// Only having one PreparedStatement per unique SQL
|
||||
// statement
|
||||
pstmt.closeDestroy();
|
||||
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Error closing Pstmt", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This will try to use a cache of PreparedStatements.
|
||||
*/
|
||||
public PreparedStatement prepareStatement(String sql, int returnKeysFlag) throws SQLException {
|
||||
String cacheKey = sql + returnKeysFlag;
|
||||
return prepareStatement(sql, true, returnKeysFlag, cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* This will try to use a cache of PreparedStatements.
|
||||
*/
|
||||
public PreparedStatement prepareStatement(String sql) throws SQLException {
|
||||
return prepareStatement(sql, false, 0, sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* This will try to use a cache of PreparedStatements.
|
||||
*/
|
||||
private PreparedStatement prepareStatement(String sql, boolean useFlag, int flag, String cacheKey) throws SQLException {
|
||||
|
||||
if (status == STATUS_IDLE) {
|
||||
String m = IDLE_CONNECTION_ACCESSED_ERROR + "prepareStatement()";
|
||||
throw new SQLException(m);
|
||||
}
|
||||
try {
|
||||
synchronized (pstmtMonitor) {
|
||||
lastStatement = sql;
|
||||
|
||||
// try to get a matching cached PStmt from the cache.
|
||||
ExtendedPreparedStatement pstmt = pstmtCache.remove(cacheKey);
|
||||
|
||||
if (pstmt != null) {
|
||||
pstmtHitCounter++;
|
||||
return pstmt;
|
||||
}
|
||||
|
||||
// create a new PreparedStatement
|
||||
pstmtMissCounter++;
|
||||
PreparedStatement actualPstmt;
|
||||
if (useFlag) {
|
||||
actualPstmt = connection.prepareStatement(sql, flag);
|
||||
} else {
|
||||
actualPstmt = connection.prepareStatement(sql);
|
||||
}
|
||||
return new ExtendedPreparedStatement(this, actualPstmt, sql, cacheKey);
|
||||
}
|
||||
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurreny)
|
||||
throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "prepareStatement()");
|
||||
}
|
||||
try {
|
||||
// no caching when creating PreparedStatements this way
|
||||
pstmtMissCounter++;
|
||||
lastStatement = sql;
|
||||
return connection.prepareStatement(sql, resultSetType, resultSetConcurreny);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the connection for returning to the client. Resets the status,
|
||||
* startUseTime and hadErrors.
|
||||
*/
|
||||
protected void resetForUse() {
|
||||
this.status = STATUS_ACTIVE;
|
||||
this.startUseTime = System.currentTimeMillis();
|
||||
this.createdByMethod = null;
|
||||
this.lastStatement = null;
|
||||
this.hadErrors = false;
|
||||
this.longRunning = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* When an error occurs during use add it the connection.
|
||||
* <p>
|
||||
* Any PooledConnection that has an error is checked to make sure it works
|
||||
* before it is placed back into the connection pool.
|
||||
* </p>
|
||||
*/
|
||||
public void addError(Throwable e) {
|
||||
hadErrors = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the connect threw any errors during use.
|
||||
* <p>
|
||||
* Connections with errors are testing to make sure they are still good
|
||||
* before putting them back into the pool.
|
||||
* </p>
|
||||
*/
|
||||
public boolean hadErrors() {
|
||||
return hadErrors;
|
||||
}
|
||||
|
||||
/**
|
||||
* close the connection putting it back into the connection pool.
|
||||
* <p>
|
||||
* Note that to ensure that the next transaction starts at the correct time
|
||||
* a commit() or rollback() should be called. If neither has occured at this
|
||||
* time then a rollback() is used (to end the transaction).
|
||||
* </p>
|
||||
* <p>
|
||||
* To close the connection fully use closeConnectionFully().
|
||||
* </p>
|
||||
*/
|
||||
public void close() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "close()");
|
||||
}
|
||||
|
||||
if (hadErrors) {
|
||||
if (!pool.validateConnection(this)) {
|
||||
// the connection is BAD, close it and test the pool
|
||||
closeConnectionFully(false);
|
||||
pool.checkDataSource();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// reset the autoCommit back if client code changed it
|
||||
if (connection.getAutoCommit() != pool.getAutoCommit()) {
|
||||
connection.setAutoCommit(pool.getAutoCommit());
|
||||
}
|
||||
// Generally resetting Isolation level seems expensive.
|
||||
// Hence using resetIsolationReadOnlyRequired flag
|
||||
// performance reasons.
|
||||
if (resetIsolationReadOnlyRequired) {
|
||||
resetIsolationReadOnly();
|
||||
resetIsolationReadOnlyRequired = false;
|
||||
}
|
||||
|
||||
// the connection is assumed GOOD so put it back in the pool
|
||||
lastUseTime = System.currentTimeMillis();
|
||||
// connection.clearWarnings();
|
||||
status = STATUS_IDLE;
|
||||
pool.returnConnection(this);
|
||||
|
||||
} catch (Exception ex) {
|
||||
// the connection is BAD, close it and test the pool
|
||||
closeConnectionFully(false);
|
||||
pool.checkDataSource();
|
||||
}
|
||||
}
|
||||
|
||||
private void resetIsolationReadOnly() throws SQLException {
|
||||
// reset the transaction isolation if the client code changed it
|
||||
if (connection.getTransactionIsolation() != pool.getTransactionIsolation()) {
|
||||
connection.setTransactionIsolation(pool.getTransactionIsolation());
|
||||
}
|
||||
// reset readonly to false
|
||||
if (connection.isReadOnly()) {
|
||||
connection.setReadOnly(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected void finalize() throws Throwable {
|
||||
try {
|
||||
if (connection != null && !connection.isClosed()) {
|
||||
// connect leak?
|
||||
String msg = "Closing Connection[" + getName() + "] on finalize().";
|
||||
logger.warning(msg);
|
||||
closeConnectionFully(false);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
super.finalize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the time the connection was passed to the client code.
|
||||
* <p>
|
||||
* Used to detect busy connections that could be leaks.
|
||||
* </p>
|
||||
*/
|
||||
public long getStartUseTime() {
|
||||
return startUseTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the time the connection was last used.
|
||||
* <p>
|
||||
* Used to close connections that have been idle for some time. Typically 5
|
||||
* minutes.
|
||||
* </p>
|
||||
*/
|
||||
public long getLastUsedTime() {
|
||||
return lastUseTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last sql statement executed.
|
||||
*/
|
||||
public String getLastStatement() {
|
||||
return lastStatement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by ExtendedStatement to trace the sql being executed.
|
||||
* <p>
|
||||
* Note with addBatch() this will not really work.
|
||||
* </p>
|
||||
*/
|
||||
protected void setLastStatement(String lastStatement) {
|
||||
this.lastStatement = lastStatement;
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.finer(".setLastStatement[" + lastStatement + "]");
|
||||
}
|
||||
}
|
||||
|
||||
boolean resetIsolationReadOnlyRequired = false;
|
||||
|
||||
/**
|
||||
* Also note the read only status needs to be reset when put back into the
|
||||
* pool.
|
||||
*/
|
||||
public void setReadOnly(boolean readOnly) throws SQLException {
|
||||
// A bit loose not checking for STATUS_IDLE
|
||||
// if (status == STATUS_IDLE) {
|
||||
// throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR +
|
||||
// "setReadOnly()");
|
||||
// }
|
||||
resetIsolationReadOnlyRequired = true;
|
||||
connection.setReadOnly(readOnly);
|
||||
}
|
||||
|
||||
/**
|
||||
* Also note the Isolation level needs to be reset when put back into the
|
||||
* pool.
|
||||
*/
|
||||
public void setTransactionIsolation(int level) throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "setTransactionIsolation()");
|
||||
}
|
||||
try {
|
||||
resetIsolationReadOnlyRequired = true;
|
||||
connection.setTransactionIsolation(level);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
//
|
||||
// Simple wrapper methods which pass a method call onto the acutal
|
||||
// connection object. These methods are safe-guarded to prevent use of
|
||||
// the methods whilst the connection is in the connection pool.
|
||||
//
|
||||
//
|
||||
public void clearWarnings() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "clearWarnings()");
|
||||
}
|
||||
connection.clearWarnings();
|
||||
}
|
||||
|
||||
public void commit() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "commit()");
|
||||
}
|
||||
try {
|
||||
status = STATUS_ENDED;
|
||||
connection.commit();
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean getAutoCommit() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "getAutoCommit()");
|
||||
}
|
||||
return connection.getAutoCommit();
|
||||
}
|
||||
|
||||
public String getCatalog() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "getCatalog()");
|
||||
}
|
||||
return connection.getCatalog();
|
||||
}
|
||||
|
||||
public DatabaseMetaData getMetaData() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "getMetaData()");
|
||||
}
|
||||
return connection.getMetaData();
|
||||
}
|
||||
|
||||
public int getTransactionIsolation() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "getTransactionIsolation()");
|
||||
}
|
||||
return connection.getTransactionIsolation();
|
||||
}
|
||||
|
||||
public Map<String,Class<?>> getTypeMap() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "getTypeMap()");
|
||||
}
|
||||
return connection.getTypeMap();
|
||||
}
|
||||
|
||||
public SQLWarning getWarnings() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "getWarnings()");
|
||||
}
|
||||
return connection.getWarnings();
|
||||
}
|
||||
|
||||
public boolean isClosed() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "isClosed()");
|
||||
}
|
||||
return connection.isClosed();
|
||||
}
|
||||
|
||||
public boolean isReadOnly() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "isReadOnly()");
|
||||
}
|
||||
return connection.isReadOnly();
|
||||
}
|
||||
|
||||
public String nativeSQL(String sql) throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "nativeSQL()");
|
||||
}
|
||||
lastStatement = sql;
|
||||
return connection.nativeSQL(sql);
|
||||
}
|
||||
|
||||
public CallableStatement prepareCall(String sql) throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "prepareCall()");
|
||||
}
|
||||
lastStatement = sql;
|
||||
return connection.prepareCall(sql);
|
||||
}
|
||||
|
||||
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurreny)
|
||||
throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "prepareCall()");
|
||||
}
|
||||
lastStatement = sql;
|
||||
return connection.prepareCall(sql, resultSetType, resultSetConcurreny);
|
||||
}
|
||||
|
||||
public void rollback() throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "rollback()");
|
||||
}
|
||||
try {
|
||||
status = STATUS_ENDED;
|
||||
connection.rollback();
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public void setAutoCommit(boolean autoCommit) throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "setAutoCommit()");
|
||||
}
|
||||
try {
|
||||
connection.setAutoCommit(autoCommit);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public void setCatalog(String catalog) throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "setCatalog()");
|
||||
}
|
||||
connection.setCatalog(catalog);
|
||||
}
|
||||
|
||||
public void setTypeMap(Map<String,Class<?>> map) throws SQLException {
|
||||
if (status == STATUS_IDLE) {
|
||||
throw new SQLException(IDLE_CONNECTION_ACCESSED_ERROR + "setTypeMap()");
|
||||
}
|
||||
connection.setTypeMap(map);
|
||||
}
|
||||
|
||||
public Savepoint setSavepoint() throws SQLException {
|
||||
try {
|
||||
return connection.setSavepoint();
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public Savepoint setSavepoint(String savepointName) throws SQLException {
|
||||
try {
|
||||
return connection.setSavepoint(savepointName);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public void rollback(Savepoint sp) throws SQLException {
|
||||
try {
|
||||
connection.rollback(sp);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public void releaseSavepoint(Savepoint sp) throws SQLException {
|
||||
try {
|
||||
connection.releaseSavepoint(sp);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public void setHoldability(int i) throws SQLException {
|
||||
try {
|
||||
connection.setHoldability(i);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public int getHoldability() throws SQLException {
|
||||
try {
|
||||
return connection.getHoldability();
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public Statement createStatement(int i, int x, int y) throws SQLException {
|
||||
try {
|
||||
return connection.createStatement(i, x, y);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public PreparedStatement prepareStatement(String s, int i, int x, int y) throws SQLException {
|
||||
try {
|
||||
return connection.prepareStatement(s, i, x, y);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public PreparedStatement prepareStatement(String s, int[] i) throws SQLException {
|
||||
try {
|
||||
return connection.prepareStatement(s, i);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public PreparedStatement prepareStatement(String s, String[] s2) throws SQLException {
|
||||
try {
|
||||
return connection.prepareStatement(s, s2);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public CallableStatement prepareCall(String s, int i, int x, int y) throws SQLException {
|
||||
try {
|
||||
return connection.prepareCall(s, i, x, y);
|
||||
} catch (SQLException ex) {
|
||||
addError(ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the method that created the connection.
|
||||
* <p>
|
||||
* Used to help finding connection pool leaks.
|
||||
* </p>
|
||||
*/
|
||||
public String getCreatedByMethod() {
|
||||
if (createdByMethod != null) {
|
||||
return createdByMethod;
|
||||
}
|
||||
if (stackTrace == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (int j = 0; j < stackTrace.length; j++) {
|
||||
String methodLine = stackTrace[j].toString();
|
||||
if (skipElement(methodLine)) {
|
||||
// ignore these methods...
|
||||
} else {
|
||||
createdByMethod = methodLine;
|
||||
return createdByMethod;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean skipElement(String methodLine) {
|
||||
if (methodLine.startsWith("java.lang.")) {
|
||||
return true;
|
||||
} else if (methodLine.startsWith("java.util.")) {
|
||||
return true;
|
||||
} else if (methodLine.startsWith("com.avaje.ebeaninternal.server.query.CallableQuery.<init>")) {
|
||||
// creating connection on future...
|
||||
return true;
|
||||
} else if (methodLine.startsWith("com.avaje.ebeaninternal.server.query.Callable")) {
|
||||
// it is a future task being executed...
|
||||
return false;
|
||||
} else if (methodLine.startsWith("com.avaje.ebeaninternal")) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the stack trace to help find connection pool leaks.
|
||||
*/
|
||||
protected void setStackTrace(StackTraceElement[] stackTrace) {
|
||||
this.stackTrace = stackTrace;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the full stack trace that got the connection from the pool. You
|
||||
* could use this if getCreatedByMethod() doesn't work for you.
|
||||
*/
|
||||
public StackTraceElement[] getStackTrace() {
|
||||
|
||||
if (stackTrace == null){
|
||||
return null;
|
||||
}
|
||||
|
||||
// filter off the top of the stack that we are not interested in
|
||||
ArrayList<StackTraceElement> filteredList = new ArrayList<StackTraceElement>();
|
||||
boolean include = false;
|
||||
for (int i = 0; i < stackTrace.length; i++) {
|
||||
if (!include && !skipElement(stackTrace[i].toString())){
|
||||
include = true;
|
||||
}
|
||||
if (include && filteredList.size() < maxStackTrace){
|
||||
filteredList.add(stackTrace[i]);
|
||||
}
|
||||
}
|
||||
return filteredList.toArray(new StackTraceElement[filteredList.size()]);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebeaninternal.server.lib.sql.DataSourcePool.Status;
|
||||
|
||||
public class PooledConnectionQueue {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(PooledConnectionQueue.class.getName());
|
||||
|
||||
private static final TimeUnit MILLIS_TIME_UNIT = TimeUnit.MILLISECONDS;
|
||||
|
||||
private final String name;
|
||||
|
||||
private final DataSourcePool pool;
|
||||
|
||||
/**
|
||||
* A 'circular' buffer designed specifically for free connections.
|
||||
*/
|
||||
private final FreeConnectionBuffer freeList;
|
||||
|
||||
/**
|
||||
* A 'slots' buffer designed specifically for busy connections.
|
||||
* Fast add remove based on slot id.
|
||||
*/
|
||||
private final BusyConnectionBuffer busyList;
|
||||
|
||||
/**
|
||||
* Main lock guarding all access
|
||||
*/
|
||||
private final ReentrantLock lock;
|
||||
|
||||
/**
|
||||
* Condition for threads waiting to take a connection
|
||||
*/
|
||||
private final Condition notEmpty;
|
||||
|
||||
private int connectionId;
|
||||
|
||||
private long waitTimeoutMillis;
|
||||
|
||||
private long leakTimeMinutes;
|
||||
|
||||
private int warningSize;
|
||||
|
||||
private int maxSize;
|
||||
|
||||
private int minSize;
|
||||
|
||||
/**
|
||||
* Number of threads in the wait queue.
|
||||
*/
|
||||
private int waitingThreads;
|
||||
|
||||
/**
|
||||
* Number of times a thread had to wait.
|
||||
*/
|
||||
private int waitCount;
|
||||
|
||||
/**
|
||||
* Number of times a connection was got from this queue.
|
||||
*/
|
||||
private int hitCount;
|
||||
|
||||
/**
|
||||
* The high water mark for the queue size.
|
||||
*/
|
||||
private int highWaterMark;
|
||||
|
||||
/**
|
||||
* Last time the pool was reset. Used to close busy connections as they are
|
||||
* returned to the pool that where created prior to the lastResetTime.
|
||||
*/
|
||||
private long lastResetTime;
|
||||
|
||||
private boolean doingShutdown;
|
||||
|
||||
public PooledConnectionQueue(DataSourcePool pool) {
|
||||
|
||||
this.pool = pool;
|
||||
this.name = pool.getName();
|
||||
this.minSize = pool.getMinSize();
|
||||
this.maxSize = pool.getMaxSize();
|
||||
|
||||
this.warningSize = pool.getWarningSize();
|
||||
this.waitTimeoutMillis = pool.getWaitTimeoutMillis();
|
||||
this.leakTimeMinutes = pool.getLeakTimeMinutes();
|
||||
|
||||
this.busyList = new BusyConnectionBuffer(50,20);
|
||||
this.freeList = new FreeConnectionBuffer(maxSize);
|
||||
|
||||
this.lock = new ReentrantLock(true);
|
||||
this.notEmpty = lock.newCondition();
|
||||
}
|
||||
|
||||
private Status createStatus() {
|
||||
return new Status(name, minSize, maxSize, freeList.size(), busyList.size(), waitingThreads, highWaterMark, waitCount, hitCount);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
return createStatus().toString();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public Status getStatus(boolean reset) {
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
Status s = createStatus();
|
||||
if (reset){
|
||||
highWaterMark = busyList.size();
|
||||
hitCount = 0;
|
||||
waitCount = 0;
|
||||
}
|
||||
return s;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void setMinSize(int minSize) {
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
if (minSize > this.maxSize){
|
||||
throw new IllegalArgumentException("minSize "+minSize+" > maxSize "+this.maxSize);
|
||||
}
|
||||
this.minSize = minSize;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void setMaxSize(int maxSize) {
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
if (maxSize < this.minSize){
|
||||
throw new IllegalArgumentException("maxSize "+maxSize+" < minSize "+this.minSize);
|
||||
}
|
||||
freeList.setCapacity(maxSize);
|
||||
this.maxSize = maxSize;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void setWarningSize(int warningSize) {
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
if (warningSize > this.maxSize){
|
||||
throw new IllegalArgumentException("warningSize "+warningSize+" > maxSize "+this.maxSize);
|
||||
}
|
||||
this.warningSize = warningSize;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private int totalConnections() {
|
||||
return freeList.size() + busyList.size();
|
||||
}
|
||||
|
||||
public void ensureMinimumConnections() throws SQLException {
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
int add = minSize - totalConnections();
|
||||
if (add > 0){
|
||||
for (int i = 0; i < add; i++) {
|
||||
PooledConnection c = pool.createConnectionForQueue(connectionId++);
|
||||
freeList.add(c);
|
||||
}
|
||||
notEmpty.signal();
|
||||
}
|
||||
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a PooledConnection.
|
||||
*/
|
||||
protected void returnPooledConnection(PooledConnection c) {
|
||||
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
if (!busyList.remove(c)) {
|
||||
logger.log(Level.SEVERE, "Connection [" + c + "] not found in BusyList? ");
|
||||
}
|
||||
if (c.getCreationTime() <= lastResetTime) {
|
||||
c.closeConnectionFully(false);
|
||||
} else {
|
||||
freeList.add(c);
|
||||
notEmpty.signal();
|
||||
}
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private PooledConnection extractFromFreeList() {
|
||||
PooledConnection c = freeList.remove();
|
||||
registerBusyConnection(c);
|
||||
return c;
|
||||
}
|
||||
|
||||
public PooledConnection getPooledConnection() throws SQLException {
|
||||
|
||||
try {
|
||||
PooledConnection pc = _getPooledConnection();
|
||||
pc.resetForUse();
|
||||
return pc;
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
String msg = "Interrupted getting connection from pool "+e;
|
||||
throw new SQLException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the PooledConnection with the busyList.
|
||||
*/
|
||||
private int registerBusyConnection(PooledConnection c) {
|
||||
int busySize = busyList.add(c);
|
||||
if (busySize > highWaterMark){
|
||||
highWaterMark = busySize;
|
||||
}
|
||||
return busySize;
|
||||
}
|
||||
|
||||
private PooledConnection _getPooledConnection() throws InterruptedException, SQLException {
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lockInterruptibly();
|
||||
try {
|
||||
if (doingShutdown) {
|
||||
throw new SQLException("Trying to access the Connection Pool when it is shutting down");
|
||||
}
|
||||
|
||||
// this includes attempts that fail with InterruptedException
|
||||
// or SQLException but that is ok as its only an indicator
|
||||
hitCount++;
|
||||
|
||||
// are other threads already waiting? (they get priority)
|
||||
if (waitingThreads == 0){
|
||||
|
||||
int freeSize = freeList.size();
|
||||
if (freeSize > 0){
|
||||
// we have a free connection to return
|
||||
return extractFromFreeList();
|
||||
}
|
||||
|
||||
if (busyList.size() < maxSize){
|
||||
// grow the connection pool
|
||||
PooledConnection c = pool.createConnectionForQueue(connectionId++);
|
||||
int busySize = registerBusyConnection(c);
|
||||
|
||||
String msg = "DataSourcePool [" + name + "] grow; id["+c.getName()+"] busy["+busySize+"] max["+maxSize+"]";
|
||||
logger.info(msg);
|
||||
|
||||
checkForWarningSize();
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// The pool is at maximum size. We are going to go into
|
||||
// a wait loop until connections are returned into the pool.
|
||||
waitCount++;
|
||||
waitingThreads++;
|
||||
return _getPooledConnectionWaitLoop();
|
||||
} finally {
|
||||
waitingThreads--;
|
||||
}
|
||||
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Got into a loop waiting for connections to be returned to the pool.
|
||||
*/
|
||||
private PooledConnection _getPooledConnectionWaitLoop() throws SQLException, InterruptedException {
|
||||
|
||||
long nanos = MILLIS_TIME_UNIT.toNanos(waitTimeoutMillis);
|
||||
for (;;) {
|
||||
|
||||
if (nanos <= 0) {
|
||||
String msg = "Unsuccessfully waited ["+waitTimeoutMillis+"] millis for a connection to be returned."
|
||||
+ " No connections are free. You need to Increase the max connections of ["+maxSize+"]"
|
||||
+ " or look for a connection pool leak using datasource.xxx.capturestacktrace=true";
|
||||
if (pool.isCaptureStackTrace()) {
|
||||
dumpBusyConnectionInformation();
|
||||
}
|
||||
|
||||
throw new SQLException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
nanos = notEmpty.awaitNanos(nanos);
|
||||
if (!freeList.isEmpty()) {
|
||||
// successfully waited
|
||||
return extractFromFreeList();
|
||||
}
|
||||
} catch (InterruptedException ie) {
|
||||
notEmpty.signal(); // propagate to non-interrupted thread
|
||||
throw ie;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
doingShutdown = true;
|
||||
Status status = createStatus();
|
||||
logger.info("DataSourcePool [" + name + "] shutdown: "+status);
|
||||
|
||||
closeFreeConnections(true);
|
||||
|
||||
if (!busyList.isEmpty()) {
|
||||
String msg = "A potential connection leak was detected. Busy connections: "+ busyList.size();
|
||||
logger.warning(msg);
|
||||
|
||||
dumpBusyConnectionInformation();
|
||||
closeBusyConnections(0);
|
||||
}
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close all the connections in the pool and any current busy connections
|
||||
* when they are returned. New connections will be then created on demand.
|
||||
* <p>
|
||||
* This is typically done when a database down event occurs.
|
||||
* </p>
|
||||
*/
|
||||
public void reset(long leakTimeMinutes) {
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
Status status = createStatus();
|
||||
logger.info("Reseting DataSourcePool [" + name + "] "+status);
|
||||
lastResetTime = System.currentTimeMillis();
|
||||
|
||||
closeFreeConnections(false);
|
||||
closeBusyConnections(leakTimeMinutes);
|
||||
|
||||
String busyMsg = "Busy Connections:\r\n" + getBusyConnectionInformation();
|
||||
logger.info(busyMsg);
|
||||
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void trim(int maxInactiveTimeSecs) throws SQLException {
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
trimInactiveConnections(maxInactiveTimeSecs);
|
||||
ensureMinimumConnections();
|
||||
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Trim connections that have been not used for some time.
|
||||
*/
|
||||
private int trimInactiveConnections(int maxInactiveTimeSecs) {
|
||||
|
||||
int maxTrim = freeList.size() - minSize;
|
||||
if (maxTrim <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int trimedCount = 0;
|
||||
long usedSince = System.currentTimeMillis() - (maxInactiveTimeSecs * 1000);
|
||||
|
||||
// get a shallow copy to manipulate
|
||||
List<PooledConnection> freeListCopy = freeList.getShallowCopy();
|
||||
|
||||
Iterator<PooledConnection> it = freeListCopy.iterator();
|
||||
while (it.hasNext()) {
|
||||
PooledConnection pc = it.next();
|
||||
if (pc.getLastUsedTime() < usedSince) {
|
||||
// trim this connection as it hasn't been used in a while
|
||||
trimedCount++;
|
||||
it.remove();
|
||||
pc.closeConnectionFully(true);
|
||||
if (trimedCount >= maxTrim) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (trimedCount > 0) {
|
||||
|
||||
// rebuild the free list from the trimmed copy
|
||||
freeList.setShallowCopy(freeListCopy);
|
||||
|
||||
String msg = "DataSourcePool [" + name + "] trimmed [" + trimedCount + "] inactive connections. New size[" + totalConnections() + "]";
|
||||
logger.info(msg);
|
||||
}
|
||||
return trimedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close all the connections that are in the free list.
|
||||
*/
|
||||
public void closeFreeConnections(boolean logErrors) {
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
while (!freeList.isEmpty()) {
|
||||
PooledConnection c = freeList.remove();
|
||||
logger.info("PSTMT Statistics: "+c.getStatistics());
|
||||
c.closeConnectionFully(logErrors);
|
||||
}
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close any busy connections that have not been used for some time.
|
||||
* <p>
|
||||
* These connections are considered to have leaked from the connection pool.
|
||||
* </p>
|
||||
* <p>
|
||||
* Connection leaks occur when code doesn't ensure that connections are
|
||||
* closed() after they have been finished with. There should be an
|
||||
* appropriate try catch finally block to ensure connections are always
|
||||
* closed and put back into the pool.
|
||||
* </p>
|
||||
*/
|
||||
public void closeBusyConnections(long leakTimeMinutes) {
|
||||
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
|
||||
long olderThanTime = System.currentTimeMillis() - (leakTimeMinutes*60000);
|
||||
|
||||
List<PooledConnection> copy = busyList.getShallowCopy();
|
||||
for (int i = 0; i < copy.size(); i++) {
|
||||
PooledConnection pc = copy.get(i);
|
||||
if (pc.isLongRunning() || pc.getLastUsedTime() > olderThanTime) {
|
||||
// PooledConnection has been used recently or
|
||||
// expected to be longRunning so not closing...
|
||||
} else {
|
||||
busyList.remove(pc);
|
||||
closeBusyConnection(pc);
|
||||
}
|
||||
}
|
||||
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void closeBusyConnection(PooledConnection pc) {
|
||||
try {
|
||||
String methodLine = pc.getCreatedByMethod();
|
||||
|
||||
Date luDate = new Date();
|
||||
luDate.setTime(pc.getLastUsedTime());
|
||||
|
||||
String msg = "DataSourcePool closing leaked connection? " + " name["
|
||||
+ pc.getName() + "] lastUsed[" + luDate + "] createdBy[" + methodLine
|
||||
+ "] lastStmt[" + pc.getLastStatement() + "]";
|
||||
|
||||
logger.warning(msg);
|
||||
logStackElement(pc, "Possible Leaked Connection: ");
|
||||
|
||||
System.out.println("CLOSING BUSY CONNECTION ??? "+pc);
|
||||
pc.close();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
// this should never actually happen
|
||||
logger.log(Level.SEVERE, null, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void logStackElement(PooledConnection pc, String prefix) {
|
||||
StackTraceElement[] stackTrace = pc.getStackTrace();
|
||||
if (stackTrace != null){
|
||||
String s = Arrays.toString(stackTrace);
|
||||
String msg = prefix+" name["+pc.getName()+"] stackTrace: "+s;
|
||||
logger.warning(msg);
|
||||
// also send to syserr ... as the loggers get turned
|
||||
// off early in JVM shutdown
|
||||
System.err.println(msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* As the pool grows it gets closer to the maxConnections limit. We can send
|
||||
* an Alert (or warning) as we get close to this limit and hence an
|
||||
* Administrator could increase the pool size if desired.
|
||||
* <p>
|
||||
* This is called whenever the pool grows in size (towards the max limit).
|
||||
* </p>
|
||||
*/
|
||||
private void checkForWarningSize() {
|
||||
|
||||
// the the total number of connections that we can add
|
||||
// to the pool before it hits the maximum
|
||||
int availableGrowth = (maxSize - totalConnections());
|
||||
|
||||
if (availableGrowth < warningSize) {
|
||||
|
||||
closeBusyConnections(leakTimeMinutes);
|
||||
|
||||
String msg = "DataSourcePool [" + name + "] is [" + availableGrowth+ "] connections from its maximum size.";
|
||||
pool.notifyWarning(msg);
|
||||
}
|
||||
}
|
||||
|
||||
public String getBusyConnectionInformation() {
|
||||
return getBusyConnectionInformation(false);
|
||||
}
|
||||
|
||||
public void dumpBusyConnectionInformation() {
|
||||
getBusyConnectionInformation(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns information describing connections that are currently being used.
|
||||
*/
|
||||
private String getBusyConnectionInformation(boolean toLogger) {
|
||||
|
||||
final ReentrantLock lock = this.lock;
|
||||
lock.lock();
|
||||
try {
|
||||
|
||||
if (toLogger) {
|
||||
logger.info("Dumping busy connections: (Use datasource.xxx.capturestacktrace=true ... to get stackTraces)");
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
List<PooledConnection> copy = busyList.getShallowCopy();
|
||||
for (int i = 0; i < copy.size(); i++) {
|
||||
PooledConnection pc = copy.get(i);
|
||||
if (toLogger) {
|
||||
logger.info(pc.getDescription());
|
||||
logStackElement(pc, "Busy Connection: ");
|
||||
|
||||
} else {
|
||||
sb.append(pc.getDescription()).append("\r\n");
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Security mechanisim.
|
||||
*/
|
||||
public class Prefix {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(Prefix.class.getName());
|
||||
|
||||
private static final int[] oa = { 50, 12, 4, 6, 8, 10, 7, 23, 45, 23, 6, 9, 12, 2, 8, 34 };
|
||||
|
||||
public static String getProp(String prop) {
|
||||
String v = dec(prop);
|
||||
int p = v.indexOf(":");
|
||||
String r = v.substring(1, p);
|
||||
return r;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String m = e(args[0]);
|
||||
logger.info("[" + m + "]");
|
||||
String o = getProp(m);
|
||||
logger.info("[" + o + "]");
|
||||
}
|
||||
|
||||
public static String e(String msg) {
|
||||
msg = elen(msg, 40);
|
||||
return enc(msg);
|
||||
}
|
||||
|
||||
public static byte az(byte c, int offset) {
|
||||
|
||||
int z = c + offset;
|
||||
if (z > 122) {
|
||||
// dp("z> "+z);
|
||||
z = z - 122 + 48 - 1;
|
||||
}
|
||||
// dp("z="+z+" c:"+(int)c);
|
||||
return (byte) z;
|
||||
}
|
||||
|
||||
public static byte bz(byte c, int offset) {
|
||||
int z = c - offset;
|
||||
if (z < (48)) {
|
||||
// dp("z< "+z);
|
||||
z = z + 122 - 48 + 1;
|
||||
}
|
||||
return (byte) z;
|
||||
}
|
||||
|
||||
public static String enc(String msg) {
|
||||
byte[] msgbytes = msg.getBytes();
|
||||
byte[] encbytes = new byte[msgbytes.length + 1];
|
||||
Random r = new Random();
|
||||
int key = r.nextInt(70);
|
||||
|
||||
char k = (char) (key + 48);
|
||||
|
||||
encbytes[0] = az((byte) k, oa[0]);
|
||||
// dp("key:"+key+" encbytes[0]:"+(byte)encbytes[0]);
|
||||
int ios = key;
|
||||
for (int i = 1; i < (msgbytes.length + 1); i++) {
|
||||
encbytes[i] = az(msgbytes[i - 1], (oa[(i + ios) % oa.length]));
|
||||
}
|
||||
return new String(encbytes);
|
||||
}
|
||||
|
||||
public static String dec(String msg) {
|
||||
byte[] msgbytes = msg.getBytes();
|
||||
byte[] encbytes = new byte[msgbytes.length];
|
||||
|
||||
encbytes[0] = bz(msgbytes[0], oa[0]);
|
||||
byte key = encbytes[0];
|
||||
int ios = (key - 48);
|
||||
for (int i = 1; i < msgbytes.length; i++) {
|
||||
encbytes[i] = bz(msgbytes[i], oa[(i + ios) % oa.length]);
|
||||
}
|
||||
return new String(encbytes);
|
||||
}
|
||||
|
||||
public static String elen(String msg, int len) {
|
||||
Random r = new Random();
|
||||
if (msg.length() < len) {
|
||||
int max = len - msg.length();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(msg).append(":");
|
||||
for (int i = 1; i < max; i++) {
|
||||
int bc = r.nextInt(122 - 48);
|
||||
sb.append(Character.toString((char) (bc + 48)));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* A LRU based cache for PreparedStatements.
|
||||
*/
|
||||
public class PstmtCache extends LinkedHashMap<String, ExtendedPreparedStatement> {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(PstmtCache.class.getName());
|
||||
|
||||
static final long serialVersionUID = -3096406924865550697L;
|
||||
|
||||
/**
|
||||
* The name of the cache, for tracing purposes.
|
||||
*/
|
||||
final String cacheName;
|
||||
|
||||
/**
|
||||
* The maximum size of the cache. When this is exceeded the oldest entry is removed.
|
||||
*/
|
||||
final int maxSize;
|
||||
|
||||
/**
|
||||
* The total number of entries removed from this cache.
|
||||
*/
|
||||
int removeCounter;
|
||||
|
||||
/**
|
||||
* The number of get hits.
|
||||
*/
|
||||
int hitCounter;
|
||||
|
||||
/**
|
||||
* The number of get() misses.
|
||||
*/
|
||||
int missCounter;
|
||||
|
||||
/**
|
||||
* The number of puts into this cache.
|
||||
*/
|
||||
int putCounter;
|
||||
|
||||
public PstmtCache(String cacheName, int maxCacheSize) {
|
||||
|
||||
// note = access ordered list. This is what gives it the LRU order
|
||||
super(maxCacheSize*3, 0.75f, true);
|
||||
this.cacheName = cacheName;
|
||||
this.maxSize = maxCacheSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a summary description of this cache.
|
||||
*/
|
||||
public String getDescription() {
|
||||
return cacheName+" size:"+size()+" max:"+maxSize+" totalHits:"+hitCounter+" hitRatio:"+getHitRatio()+" removes:"+removeCounter;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the current maximum size of the cache.
|
||||
*/
|
||||
public int getMaxSize() {
|
||||
return maxSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the hit ratio. A number between 0 and 100 indicating the number of
|
||||
* hits to misses. A number approaching 100 is desirable.
|
||||
*/
|
||||
public int getHitRatio() {
|
||||
if (hitCounter == 0) {
|
||||
return 0;
|
||||
} else {
|
||||
return hitCounter*100/(hitCounter+missCounter);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The total number of hits against this cache.
|
||||
*/
|
||||
public int getHitCounter() {
|
||||
return hitCounter;
|
||||
}
|
||||
|
||||
/**
|
||||
* The total number of misses against this cache.
|
||||
*/
|
||||
public int getMissCounter() {
|
||||
return missCounter;
|
||||
}
|
||||
|
||||
/**
|
||||
* The total number of puts against this cache.
|
||||
*/
|
||||
public int getPutCounter() {
|
||||
return putCounter;
|
||||
}
|
||||
|
||||
/**
|
||||
* additionally maintains hit and miss statistics.
|
||||
*/
|
||||
public ExtendedPreparedStatement get(Object key) {
|
||||
|
||||
ExtendedPreparedStatement o = super.get(key);
|
||||
if (o == null) {
|
||||
missCounter++;
|
||||
} else {
|
||||
hitCounter++;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/**
|
||||
* additionally maintains hit and miss statistics.
|
||||
*/
|
||||
public ExtendedPreparedStatement remove(Object key) {
|
||||
|
||||
ExtendedPreparedStatement o = super.remove(key);
|
||||
if (o == null) {
|
||||
missCounter++;
|
||||
} else {
|
||||
hitCounter++;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/**
|
||||
* additionally maintains put counter statistics.
|
||||
*/
|
||||
public ExtendedPreparedStatement put(String key, ExtendedPreparedStatement value) {
|
||||
|
||||
putCounter++;
|
||||
return super.put(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* will check to see if we need to remove entries and
|
||||
* if so call the cacheCleanup.cleanupEldestLRUCacheEntry() if
|
||||
* one has been set.
|
||||
*/
|
||||
protected boolean removeEldestEntry(Map.Entry<String,ExtendedPreparedStatement> eldest) {
|
||||
|
||||
if (size() < maxSize) {
|
||||
return false;
|
||||
}
|
||||
|
||||
removeCounter++;
|
||||
|
||||
try {
|
||||
ExtendedPreparedStatement pstmt = eldest.getValue();
|
||||
pstmt.closeDestroy();
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Error closing ExtendedPreparedStatement", e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebean.config.GlobalProperties;
|
||||
import com.avaje.ebeaninternal.server.lib.util.MailEvent;
|
||||
import com.avaje.ebeaninternal.server.lib.util.MailListener;
|
||||
import com.avaje.ebeaninternal.server.lib.util.MailMessage;
|
||||
import com.avaje.ebeaninternal.server.lib.util.MailSender;
|
||||
|
||||
/**
|
||||
* A simple smtp email alert that sends a email message
|
||||
* on dataSourceDown and dataSourceUp etc.
|
||||
* <ul>
|
||||
* <li>alert.fromuser = the from user name
|
||||
* <li>alert.fromemail = the from email account
|
||||
* <li>alert.toemail = comma delimited list of email accounts to email
|
||||
* <li>alert.mailserver = the smpt server name
|
||||
* </ul>
|
||||
*/
|
||||
public class SimpleAlerter implements DataSourceAlertListener, MailListener {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(SimpleAlerter.class.getName());
|
||||
|
||||
//boolean sendInBackGround = true;
|
||||
|
||||
/**
|
||||
* Create a SimpleAlerter.
|
||||
*/
|
||||
public SimpleAlerter() {
|
||||
}
|
||||
|
||||
/**
|
||||
* If the email failed then log the error.
|
||||
*/
|
||||
public void handleEvent(MailEvent event) {
|
||||
Throwable e = event.getError();
|
||||
if (e != null){
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the dataSource down alert.
|
||||
*/
|
||||
public void dataSourceDown(String dataSourceName) {
|
||||
String msg = getSubject(true, dataSourceName);
|
||||
sendMessage(msg, msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the dataSource up alert.
|
||||
*/
|
||||
public void dataSourceUp(String dataSourceName) {
|
||||
String msg = getSubject(false, dataSourceName);
|
||||
sendMessage(msg, msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the warning message.
|
||||
*/
|
||||
public void warning(String subject, String msg) {
|
||||
sendMessage(subject, msg);
|
||||
}
|
||||
|
||||
private String getSubject(boolean isDown, String dsName) {
|
||||
String msg = "The DataSource "+dsName;
|
||||
if (isDown){
|
||||
msg += " is DOWN!!";
|
||||
} else {
|
||||
msg += " is UP.";
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
private void sendMessage(String subject, String msg){
|
||||
|
||||
String fromUser = GlobalProperties.get("alert.fromuser", null);
|
||||
String fromEmail = GlobalProperties.get("alert.fromemail", null);
|
||||
String mailServerName = GlobalProperties.get("alert.mailserver", null);
|
||||
String toEmail = GlobalProperties.get("alert.toemail", null);
|
||||
|
||||
if (mailServerName == null){
|
||||
//throw new RuntimeException("alert.mailserver not set...");
|
||||
return;
|
||||
}
|
||||
|
||||
MailMessage data = new MailMessage();
|
||||
data.setSender(fromUser, fromEmail);
|
||||
data.addBodyLine(msg);
|
||||
data.setSubject(subject);
|
||||
|
||||
String[] toList = toEmail.split(",");
|
||||
if (toList.length==0) {
|
||||
throw new RuntimeException("alert.toemail has not been set?");
|
||||
}
|
||||
for (int i = 0; i < toList.length; i++) {
|
||||
data.addRecipient(null, toList[i].trim());
|
||||
}
|
||||
|
||||
MailSender sender = new MailSender(mailServerName);
|
||||
sender.setMailListener(this);
|
||||
sender.sendInBackground(data);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.lib.sql;
|
||||
|
||||
import java.sql.Connection;
|
||||
|
||||
/**
|
||||
* Helper object that can convert between transaction isolation descriptions and values.
|
||||
*
|
||||
*/
|
||||
public class TransactionIsolation {
|
||||
|
||||
|
||||
/**
|
||||
* return the isolation level for a given string description.
|
||||
*/
|
||||
public static int getLevel(String level) {
|
||||
level = level.toUpperCase();
|
||||
if (level.startsWith("TRANSACTION")){
|
||||
level = level.substring("TRANSACTION".length());
|
||||
}
|
||||
level = level.replace("_", "");
|
||||
if ("NONE".equalsIgnoreCase(level)){
|
||||
return Connection.TRANSACTION_NONE;
|
||||
}
|
||||
if ("READCOMMITTED".equalsIgnoreCase(level)){
|
||||
return Connection.TRANSACTION_READ_COMMITTED;
|
||||
}
|
||||
if ("READUNCOMMITTED".equalsIgnoreCase(level)){
|
||||
return Connection.TRANSACTION_READ_UNCOMMITTED;
|
||||
}
|
||||
if ("REPEATABLEREAD".equalsIgnoreCase(level)){
|
||||
return Connection.TRANSACTION_REPEATABLE_READ;
|
||||
}
|
||||
if ("SERIALIZABLE".equalsIgnoreCase(level)){
|
||||
return Connection.TRANSACTION_SERIALIZABLE;
|
||||
}
|
||||
|
||||
throw new RuntimeException("Transaction Isolaction level [" + level + "] is not known.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the string description of the transaction isolation level specified.
|
||||
* <p>Returned value is one of NONE, READ_COMMITTED,READ_UNCOMMITTED,
|
||||
* REPEATABLE_READ or SERIALIZABLE.</p>
|
||||
*
|
||||
* @param level the transaction isolation level as per java.sql.Connection
|
||||
* @return the level description as a string.
|
||||
*/
|
||||
public static String getLevelDescription(int level) {
|
||||
switch (level) {
|
||||
case Connection.TRANSACTION_NONE :
|
||||
return "NONE";
|
||||
case Connection.TRANSACTION_READ_COMMITTED :
|
||||
return "READ_COMMITTED";
|
||||
case Connection.TRANSACTION_READ_UNCOMMITTED :
|
||||
return "READ_UNCOMMITTED";
|
||||
case Connection.TRANSACTION_REPEATABLE_READ :
|
||||
return "REPEATABLE_READ";
|
||||
case Connection.TRANSACTION_SERIALIZABLE :
|
||||
return "SERIALIZABLE";
|
||||
case -1 :
|
||||
return "NotSet";
|
||||
default :
|
||||
throw new RuntimeException("Transaction Isolaction level [" + level + "] is not defined.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
FATAL_ERROR=ERROR: A fatal error has occured. Check the error log. {0}
|
||||
DATASOURCE_OK=DataSource {0} working ok.
|
||||
SHUTTING_DOWN=DataSource shutdown all datasources in [{0}]
|
||||
SHUT_DOWN_FINISHED=DataSource shutdown has finished.
|
||||
CANT_FIND_PROPS=ERROR: Can't find the datasource props file.
|
||||
ERROR_CREATING_FACTORY=ERROR: An error occured when creating the DataSourceFactory {0}.
|
||||
CANT_SHUTDOWN_TYPE=WARN: Can't shutdown DataSource objects of this type {0}.
|
||||
|
||||
DB_DRIVER_NOTFOUND=ERROR: The JDBC Driver {0} can't be found.
|
||||
POOL_IN_SHUTDOWN=ERROR: Trying to use the pool while it is shutting down.
|
||||
WAIT_TIME_EXCEEDED=ERROR: Wait time {0} for connection exceeded. {1}.
|
||||
SHUTDOWN_START=DataSource [{0}] Shutting down.
|
||||
SHUTDOWN_LEAK=A Connection leak has been detected on shutdown {0}.
|
||||
SHUTDOWN_END=DataSource [{0}] Shutdown ended.
|
||||
METHOD_NOT_SUPPORTED=ERROR: this method is not supported.
|
||||
SET_ALERT=WARN: Alert {0} has been set.
|
||||
MISSING_PARAMETER=ERROR: A parameter {0} is missing from the props file.
|
||||
IDLE_CONNECTION_ACCESSED=Pooled Connection has been accessed whilst idle in the pool, via method:
|
||||
|
||||
DEFAULT_DS_NOT_SPECIFIED=ERROR: No default dataSource has been specified.
|
||||
@@ -0,0 +1,12 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
|
||||
<TITLE>AvajeLib</TITLE>
|
||||
</HEAD>
|
||||
<Body BGCOLOR="#ffffff">
|
||||
Enhanced JDBC objects and connection pool.
|
||||
|
||||
<P>Provides Database meta data objects, Robust connection pooling, PreparedStatement Caching.
|
||||
</P>
|
||||
</Body>
|
||||
</HTML>
|
||||
Reference in new issue
Block a user