initial add of EbeanORM server based on v2.8.1

This commit is contained in:
rbygrave committed 2012-09-14 00:40:39 +12:00
1 parent 2b74d0f9d9
commit 96ce4c0ddf
1188 files changed
+135034

No files matched your search

@@ -0,0 +1,164 @@
/**
* 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;
/**
* Wraps a Runnable that is registed with BackgroundThread.
* @see BackgroundThread
*/
public class BackgroundRunnable {
/**
* The task to run.
*/
Runnable runnable;
/**
* The frequency to run the task.
*/
int freqInSecs;
/**
* The number of times the task has run.
*/
int runCount = 0;
/**
* The total time taken to run the task.
*/
long totalRunTime = 0;
/**
* The start time the task was started.
*/
long startTimeTemp;
long startAfter;
/**
* Used to disable/enable a task.
*/
boolean isActive = true;
public BackgroundRunnable(Runnable runnable, int freqInSecs){
this(runnable, freqInSecs, System.currentTimeMillis()+1000*(freqInSecs+10));
}
public BackgroundRunnable(Runnable runnable, int freqInSecs, long startAfter){
this.runnable = runnable;
this.freqInSecs = freqInSecs;
this.startAfter = startAfter;
}
/**
* Return true if this can be run now.
* <p>
* This is used to stop jobs firing immediately.
* </p>
*/
public boolean runNow(long now){
return now > startAfter;
}
/**
* Returns true if the task is currently enabled.
*/
public boolean isActive() {
return isActive;
}
/**
* Set this to false to stop this task from running.
* Useful to temporarily disable a particular task.
*/
public void setActive(boolean isActive) {
this.isActive = isActive;
}
/**
* Mark the start time of a task run.
*/
protected void runStart() {
startTimeTemp = System.currentTimeMillis();
}
/**
* Mark the end time of a task run.
*/
protected void runEnd(){
runCount++;
long exeTime = System.currentTimeMillis() - startTimeTemp;
totalRunTime = totalRunTime + exeTime;
}
/**
* Return the number of times this task was run.
*/
public int getRunCount() {
return runCount;
}
/**
* Return the average time this task takes to run.
*/
public long getAverageRunTime() {
if (runCount == 0){
return 0;
}
return totalRunTime/runCount;
}
/**
* Return the frequency in seconds that this task runs.
*/
public int getFreqInSecs() {
return freqInSecs;
}
/**
* Set the frequency in seconds that this task runs.
*/
public void setFreqInSecs(int freqInSecs) {
this.freqInSecs = freqInSecs;
}
/**
* Return the underlying runnable.
*/
public Runnable getRunnable() {
return runnable;
}
/**
* Set the underlying runnable.
*/
public void setRunnable(Runnable runnable) {
this.runnable = runnable;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[");
sb.append(runnable.getClass().getName());
sb.append(" freq:").append(freqInSecs);
sb.append(" count:").append(getRunCount());
sb.append(" avgTime:").append(getAverageRunTime());
sb.append("]");
return sb.toString();
}
}
@@ -0,0 +1,236 @@
/**
* 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;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A general background thread that runs registered tasks periodically.
* <p>
* Several features such as CacheManager, DataSourceManager, ThreadPoolManager
* require tasks to be undertaken periodically. Instead of each having their own
* background thread they register runnables with this one.
* </p>
* <p>
* SystemProperties:<br>
*
* <pre><code>
* ## initially sleep for 5 seconds before starting
* backgroundthread.initialsleep=5
* </code></pre>
*
* </p>
*
* @see BackgroundRunnable
*/
public final class BackgroundThread {
private static final Logger logger = Logger.getLogger(BackgroundThread.class.getName());
private static final BackgroundThread me = new BackgroundThread();
/**
* The list of Runnable tasks.
*/
private Vector<BackgroundRunnable> list = new Vector<BackgroundRunnable>();
/**
* Used to synchronize the list.
*/
private final Object monitor = new Object();
/**
* The underlying background thread.
*/
private final Thread thread;
/**
* Wakes every second to look for tasks to run.
*/
private long sleepTime = 1000;
/**
* The number of times a task is run.
*/
private long count;
/**
* The time it takes to run the tasks.
*/
private long exeTime;
/**
* Set when shutting down.
*/
private boolean stopped;
/**
* Used to shutdown nicely.
*/
private Object threadMonitor = new Object();
private BackgroundThread() {
thread = new Thread(new Runner(), "EbeanBackgroundThread");
thread.setDaemon(true);
thread.start();
}
/**
* Register a Runnable to execute every freqInSecs seconds.
*/
public static void add(int freqInSecs, Runnable runnable) {
add(new BackgroundRunnable(runnable, freqInSecs));
}
/**
* Register a Runnable to execute every freqInSecs seconds.
*/
public static void add(BackgroundRunnable backgroundRunnable) {
me.addTask(backgroundRunnable);
}
/**
* Stop the service.
*/
public static void shutdown() {
me.stop();
}
/**
* Return the registered BackgroundRunnable objects.
*/
public static Iterator<BackgroundRunnable> runnables() {
synchronized (me.monitor) {
return me.list.iterator();
}
}
private void addTask(BackgroundRunnable backgroundRunnable) {
synchronized (monitor) {
list.add(backgroundRunnable);
}
}
/**
* Stop the thread nicely. This will wait a maximum of 10 seconds for
* current work to be finished.
*/
private void stop() {
stopped = true;
synchronized (threadMonitor) {
try {
threadMonitor.wait(10000);
} catch (InterruptedException e) {
;
}
}
// thread = null;
}
private class Runner implements Runnable {
/**
* Run the registered tasks periodically.
*/
public void run() {
if (ShutdownManager.isStopping()) {
return;
}
while (!stopped) {
try {
long actualSleep = sleepTime - exeTime;
if (actualSleep < 0) {
actualSleep = sleepTime;
}
Thread.sleep(actualSleep);
synchronized (monitor) {
runJobs();
}
} catch (InterruptedException e) {
logger.log(Level.SEVERE, null, e);
}
}
// Tell Stop() we have shut ourselves down successfully
synchronized (threadMonitor) {
threadMonitor.notifyAll();
}
}
private void runJobs() {
long startTime = System.currentTimeMillis();
// call trim on each cache
Iterator<BackgroundRunnable> it = list.iterator();
while (it.hasNext()) {
BackgroundRunnable bgr = (BackgroundRunnable) it.next();
if (bgr.isActive()) {
int freqInSecs = bgr.getFreqInSecs();
if (count % freqInSecs == 0) {
Runnable runable = bgr.getRunnable();
if (bgr.runNow(startTime)){
bgr.runStart();
if (logger.isLoggable(Level.FINER)) {
String msg = count + " BGRunnable running ["
+ runable.getClass().getName() + "]";
logger.finer(msg);
}
runable.run();
bgr.runEnd();
}
}
}
}
exeTime = System.currentTimeMillis() - startTime;
count++;
if (count == 86400) {
// reset count back to zero every day
count = 0;
}
}
}
public String toString() {
synchronized (monitor) {
StringBuffer sb = new StringBuffer();
Iterator<BackgroundRunnable> it = runnables();
while (it.hasNext()) {
BackgroundRunnable bgr = it.next();
sb.append(bgr);
}
return sb.toString();
}
}
}
@@ -0,0 +1,97 @@
/**
* 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;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.avaje.ebeaninternal.api.Monitor;
/**
* Daemon based ScheduleThreadPool.
* <p>
* Uses Daemon threads and hooks into shutdown event.
* </p>
*
* @author rbygrave
*/
public final class DaemonScheduleThreadPool extends ScheduledThreadPoolExecutor {
private static final Logger logger = Logger.getLogger(DaemonScheduleThreadPool.class.getName());
private final Monitor monitor = new Monitor();
private int shutdownWaitSeconds;
/**
* Construct the DaemonScheduleThreadPool.
*/
public DaemonScheduleThreadPool(int coreSize, int shutdownWaitSeconds, String namePrefix) {
super(coreSize, new DaemonThreadFactory(namePrefix));
this.shutdownWaitSeconds = shutdownWaitSeconds;
// we want to shutdown nicely when either the web application stops.
// Adding the JVM shutdown hook as a safety (and when not run in tomcat)
Runtime.getRuntime().addShutdownHook(new ShutdownHook());
}
/**
* Shutdown this thread pool nicely if possible.
* <p>
* This will wait a maximum of 20 seconds before terminating any threads
* still working.
* </p>
*/
public void shutdown() {
synchronized (monitor) {
if (super.isShutdown()) {
logger.fine("... DaemonScheduleThreadPool already shut down");
return;
}
try {
logger.fine("DaemonScheduleThreadPool shutting down...");
super.shutdown();
if (!super.awaitTermination(shutdownWaitSeconds, TimeUnit.SECONDS)) {
logger.info("ScheduleService shut down timeout exceeded. Terminating running threads.");
super.shutdownNow();
}
} catch (Exception e) {
String msg = "Error during shutdown";
logger.log(Level.SEVERE, msg, e);
e.printStackTrace();
}
}
}
/**
* Fired by the JVM Runtime shutdown.
*/
private class ShutdownHook extends Thread {
@Override
public void run() {
shutdown();
}
};
}
@@ -0,0 +1,68 @@
/**
* 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;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* ThreadFactory for Daemon threads.
* <p>
* Daemon threads do not stop a JVM stopping. If an application only has Daemon
* threads left it will shutdown.
* </p>
* <p>
* In using Daemon threads you need to either not care about being interrupted
* on shutdown or register with the JVM shutdown hook to perform a nice shutdown
* of the daemon threads etc.
* </p>
*
* @author rbygrave
*/
public class DaemonThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
public DaemonThreadFactory(String namePrefix) {
SecurityManager s = System.getSecurityManager();
this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
this.namePrefix = namePrefix != null ? namePrefix : "pool-" + poolNumber.getAndIncrement() + "-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
t.setDaemon(true);
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
@@ -0,0 +1,105 @@
/**
* 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;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.avaje.ebeaninternal.api.Monitor;
/**
* The Thread Pool based on Daemon threads.
*
* @author rbygrave
*/
public final class DaemonThreadPool extends ThreadPoolExecutor {
private static final Logger logger = Logger.getLogger(DaemonThreadPool.class.getName());
private final Monitor monitor = new Monitor();
private final String namePrefix;
private int shutdownWaitSeconds;
/**
* Construct the DaemonThreadPool.
*
* @param coreSize
* the core size of the thread pool.
* @param keepAliveSecs
* the time in seconds idle threads are keep alive
* @param shutdownWaitSeconds
* the time in seconds allowed for the pool to shutdown nicely.
* After this the pool is forced to shutdown.
*/
public DaemonThreadPool(int coreSize, long keepAliveSecs, int shutdownWaitSeconds, String namePrefix) {
super(coreSize, coreSize, keepAliveSecs, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory(namePrefix));
this.shutdownWaitSeconds = shutdownWaitSeconds;
this.namePrefix = namePrefix;
// we want to shutdown nicely when either the web application stops.
// Adding the JVM shutdown hook as a safety (and when not run in tomcat)
Runtime.getRuntime().addShutdownHook(new ShutdownHook());
}
/**
* Shutdown this thread pool nicely if possible.
* <p>
* This will wait a maximum of 20 seconds before terminating any threads
* still working.
* </p>
*/
public void shutdown() {
synchronized (monitor) {
if (super.isShutdown()) {
logger.fine("... DaemonThreadPool["+namePrefix+"] already shut down");
return;
}
try {
logger.fine("DaemonThreadPool["+namePrefix+"] shutting down...");
super.shutdown();
if (!super.awaitTermination(shutdownWaitSeconds, TimeUnit.SECONDS)) {
logger.info("DaemonThreadPool["+namePrefix+"] shut down timeout exceeded. Terminating running threads.");
super.shutdownNow();
}
} catch (Exception e) {
String msg = "Error during shutdown of DaemonThreadPool["+namePrefix+"]";
logger.log(Level.SEVERE, msg, e);
e.printStackTrace();
}
}
}
/**
* Fired by the JVM Runtime shutdown.
*/
private class ShutdownHook extends Thread {
@Override
public void run() {
shutdown();
}
};
}
@@ -0,0 +1,50 @@
/**
* 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;
/**
* This is the ShutdownHook that gets added to Runtime.
* It will try to shutdown the system cleanly when the JVM exits.
* It is best to add your own shutdown hooks to StartStop.
*
*/
class ShutdownHook extends Thread {
ShutdownHook() {
}
// /**
// * Register this as a Shutdown hook with the Runtime.
// */
// public static void registerWithRuntime() {
//
// ShutdownHook hook = new ShutdownHook();
// Runtime.getRuntime().addShutdownHook(hook);
// }
/**
* Fired by the JVM Runtime on shutdown.
*/
public void run() {
ShutdownManager.shutdown();
}
};
@@ -0,0 +1,232 @@
/**
* 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;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.avaje.ebean.common.BootupEbeanManager;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebeaninternal.api.ClassUtil;
import com.avaje.ebeaninternal.server.lib.sql.DataSourceGlobalManager;
import com.avaje.ebeaninternal.server.lib.thread.ThreadPoolManager;
/**
* Manages the shutdown of the Runtime.
* <p>
* Makes sure all the resources are shutdown properly and in order.
* </p>
*/
public final class ShutdownManager {
private static final Logger logger = Logger.getLogger(BackgroundThread.class.getName());
static final Vector<Runnable> runnables = new Vector<Runnable>();
static boolean stopping;
static BootupEbeanManager serverFactory;
static final ShutdownHook shutdownHook = new ShutdownHook();
static boolean whyShutdown;
static {
// Register the Shutdown hook
register();
whyShutdown = GlobalProperties.getBoolean("debug.shutdown.why",false);
}
/**
* Disallow construction.
*/
private ShutdownManager() {
}
public static void registerServerFactory(BootupEbeanManager factory){
serverFactory = factory;
}
/**
* Make sure the ShutdownManager is activated.
*/
public static void touch() {
}
/**
* Return true if the system is in the process of stopping.
*/
public static boolean isStopping() {
synchronized (runnables) {
return stopping;
}
}
/**
* Deregister the Shutdown hook.
* <p>
* For running in a Servlet Container a redeploy will cause a shutdown, and
* for that case we need to make sure the shutdown hook is deregistered.
* </p>
*/
private static void deregister() {
synchronized (runnables) {
try {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
} catch (IllegalStateException ex) {
if (!ex.getMessage().equals("Shutdown in progress")) {
throw ex;
}
}
}
}
/**
* Register the shutdown hook with the Runtime.
*/
private static void register() {
synchronized (runnables) {
try {
Runtime.getRuntime().addShutdownHook(shutdownHook);
} catch (IllegalStateException ex) {
if (!ex.getMessage().equals("Shutdown in progress")) {
throw ex;
}
}
}
}
/**
* cleanup any resources as Runtime is stopping.
* <p>
* <ul>
* <li>Run the application specific shutdown runnable
* <li>Run any other registered shutdown runnable
* <li>Deregister from the cluster if required
* <li>Shutdown Thread pools
* <li>Shutdown any database connection pools
* </ul>
* </p>
*/
public static void shutdown() {
synchronized (runnables) {
if (stopping) {
// Already run shutdown...
return;
}
if (whyShutdown){
try {
throw new RuntimeException("debug.shutdown.why=true ...");
} catch(Throwable e){
logger.log(Level.WARNING, "Stacktrace showing why shutdown was fired", e);
}
}
stopping = true;
//logger.info("Stopping [" + SystemProperties.getContextName() + "]");
deregister();
// stop the BackgroundThread
BackgroundThread.shutdown();
String shutdownRunner = GlobalProperties.get("system.shutdown.runnable", null);
if (shutdownRunner != null) {
try {
Runnable r = (Runnable)ClassUtil.newInstance(shutdownRunner);
r.run();
} catch (Exception e) {
logger.log(Level.SEVERE, null, e);
}
}
// shutdown any registered runnable
Enumeration<Runnable> e = runnables.elements();
while (e.hasMoreElements()) {
try {
Runnable r = (Runnable) e.nextElement();
r.run();
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
try {
// shutdown order is important!
// CronManager is ok
if (serverFactory != null){
serverFactory.shutdown();
}
ThreadPoolManager.shutdown();
DataSourceGlobalManager.shutdown();
boolean dereg = GlobalProperties.getBoolean("datasource.deregisterAllDrivers", false);
if (dereg){
deregisterAllJdbcDrivers();
}
} catch (Exception ex) {
String msg = "Shutdown Exception: "+ ex.getMessage();
System.err.println(msg);
ex.printStackTrace();
try {
logger.log(Level.SEVERE, null, ex);
} catch (Exception exc) {
String ms = "Error Logging error to the Log. It may be shutting down.";
System.err.println(ms);
exc.printStackTrace();
}
}
}
}
private static void deregisterAllJdbcDrivers() {
// This manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory leaks wrto this class
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
try {
DriverManager.deregisterDriver(driver);
logger.log(Level.INFO, String.format("Deregistering jdbc driver: %s", driver));
} catch (SQLException e) {
logger.log(Level.SEVERE, String.format("Error deregistering driver %s", driver), e);
}
}
}
/**
* Register a runnable to be executed when the system is shutdown. Note that
* runnables registered here are shutdown before any thread pools or
* DataSource pools are shutdown.
*/
public static void register(Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
}
}
}
@@ -0,0 +1,13 @@
<HTML>
<HEAD>
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
<TITLE>AvajeLib</TITLE>
</HEAD>
<Body BGCOLOR="#ffffff">
Core services for an application.
<P>
Core services including Logging, Deployment properties and Background thread for
running frequent tasks.
</P>
</Body>
</HTML>
@@ -0,0 +1,56 @@
package com.avaje.ebeaninternal.server.lib.resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
public abstract class AbstractResourceSource {
/**
* Helper method to read String content.
*/
public String readString(ResourceContent content, int bufSize) throws IOException {
if (content == null) {
throw new NullPointerException("content is null?");
}
StringWriter writer = new StringWriter();
InputStream is = content.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
char[] buf = new char[bufSize];
int len;
while ((len = reader.read(buf, 0, buf.length)) != -1) {
writer.write(buf, 0, len);
}
reader.close();
return writer.toString();
}
/**
* Helper method to read byte[] content.
*/
public byte[] readBytes(ResourceContent content, int bufSize) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
InputStream is = content.getInputStream();
byte[] buf = new byte[bufSize];
int len;
while ((len = is.read(buf, 0, buf.length)) != -1) {
bytes.write(buf, 0, len);
}
is.close();
return bytes.toByteArray();
}
}
@@ -0,0 +1,124 @@
/**
* 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.resource;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Helper object used to find directories typically from the current working
* directory.
*/
public class DirectoryFinder {
private static final Logger logger = Logger.getLogger(DirectoryFinder.class.getName());
/**
* Find a directory by search through subdirectories.
* <p>
* For example, used to find the WEB-INF directory starting from the current
* working directory.
* </p>
*
* <pre class="code">
*
* // search to a depth of 3 from the current working directory
* // looking for a directory WEB-INF that contains the subdirectory
* // data
*
* File dir = DirectoryFinder.find(null, &quot;WEB-INF/data&quot;, 3);
* if (dir != null) {
* //found the directory
* }
* </pre>
*/
public static File find(File startDir, String match, int maxDepth) {
String matchSub = null;
int slashPos = match.indexOf('/');
if (slashPos > -1) {
// match has sub directories
matchSub = match.substring(slashPos + 1);
match = match.substring(0, slashPos);
}
// search for the directory
File found = find(startDir, match, matchSub, 0, maxDepth);
if (found != null && matchSub != null) {
// match has sub directories
return new File(found, matchSub);
}
return found;
}
private static File find(File dir, String match, String matchSub, int depth, int maxDepth) {
if (dir == null) {
String curDir = System.getProperty("user.dir");
dir = new File(curDir);
}
if (dir.exists()) {
File[] list = dir.listFiles();
if (list != null){
for (int i = 0; i < list.length; i++) {
if (isMatch(list[i], match, matchSub)) {
return list[i];
}
}
// go through the directories again
// Aka *NOT* a depth first search
if (depth < maxDepth) {
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
File found = find(list[i], match, matchSub, depth + 1, maxDepth);
if (found != null) {
return found;
}
}
}
}
}
}
return null;
}
private static boolean isMatch(File f, String match, String matchSub) {
if (f == null) {
return false;
}
if (!f.isDirectory()) {
return false;
}
if (!f.getName().equalsIgnoreCase(match)) {
return false;
}
if (matchSub == null) {
return true;
}
File sub = new File(f, matchSub);
if (logger.isLoggable(Level.FINEST)){
logger.finest("search; " + f.getPath());
}
return sub.exists();
}
}
@@ -0,0 +1,88 @@
/**
* 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.resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
/**
* Content from a file system file.
*/
public class FileResourceContent implements ResourceContent {
/**
* The underlying file.
*/
File file;
String entryName;
/**
* Create with a File and the entryName.
*/
public FileResourceContent(File file, String entryName) {
this.file = file;
this.entryName = entryName;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[").append(getName());
sb.append("] size[").append(size());
sb.append("] lastModified[").append(new Date(lastModified()));
sb.append("]");
return sb.toString();
}
/**
* Returns the entry name which contains the path from the base directory.
* <p>
* This does not return the full path of the file, but the path relative to
* the FileIoSource directory.
* </p>
*/
public String getName() {
return entryName;
}
/**
* Return the time the file was last modified.
*/
public long lastModified() {
return file.lastModified();
}
/**
* Return the size of the file.
*/
public long size() {
return file.length();
}
/**
* Return the input stream for this file.
*/
public InputStream getInputStream() throws IOException {
FileInputStream is = new FileInputStream(file);
return is;
}
}
@@ -0,0 +1,68 @@
/**
* 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.resource;
import java.io.File;
/**
* A file system directory represented as a FileSource.
*/
public class FileResourceSource extends AbstractResourceSource implements ResourceSource {
/**
* The directory name.
*/
String directory;
String baseDir;
/**
* Create the source based on a directory name.
*/
public FileResourceSource(String directory){
this.directory = directory;
this.baseDir = directory+File.separator;
}
/**
* Create the source based on a directory file.
*/
public FileResourceSource(File dir){
this(dir.getPath());
}
public String getRealPath() {
return directory;
}
/**
* Search for the given file and return as IoContent.
*/
public ResourceContent getContent(String entry) {
String fullPath = baseDir+entry;
File f = new File(fullPath);
if (f.exists()){
FileResourceContent content = new FileResourceContent(f, entry);
return content;
}
return null;
}
}
@@ -0,0 +1,51 @@
/**
* 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.resource;
import java.io.IOException;
import java.io.InputStream;
/**
* Represents content that can be read via the ResourceManager.
* <p>
* Typically either content from a File or a URL.
* </p>
*/
public interface ResourceContent {
/**
* The name of the content.
*/
public String getName();
/**
* The size of the content in bytes.
*/
public long size();
/**
* The last modified timestamp of the content.
*/
public long lastModified();
/**
* The content itself.
*/
public InputStream getInputStream() throws IOException;
}
@@ -0,0 +1,54 @@
/**
* 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.resource;
import java.io.IOException;
/**
* A Source for ResourceManager.
* <p>
* Typically a File System Directory based source or a ServletContext URL
* resource based source (for Servlet WAR files).
* </p>
*/
public interface ResourceSource {
/**
* Return the File System path of the root of the ResourceSource.
* <p>
* This will return null IF the ResourceSource is an unpacked WAR file.
* </p>
*/
public String getRealPath();
/**
* Find the content with a given entry name. This will return null if no
* matching content was found.
*/
public ResourceContent getContent(String entry);
/**
* Return the content as a String.
*/
public String readString(ResourceContent content, int bufSize) throws IOException;
/**
* Return the content as a byte[].
*/
public byte[] readBytes(ResourceContent content, int bufSize) throws IOException;
}
@@ -0,0 +1,94 @@
/**
* 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.resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
/**
* Content from a URL Resource.
*/
public class UrlResourceContent implements ResourceContent {
/**
* The underlying resource.
*/
//URL url;
String entryName;
URLConnection con;
/**
* Create with a File and the entryName.
*/
public UrlResourceContent(URL url, String entryName) {
//this.url = url;
this.entryName = entryName;
try {
con = url.openConnection();
} catch (IOException ex){
throw new RuntimeException(ex);
}
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[").append(getName());
sb.append("] size[").append(size());
sb.append("] lastModified[").append(new Date(lastModified()));
sb.append("]");
return sb.toString();
}
/**
* Returns the entry name which contains the path from the base directory.
* <p>
* This does not return the full path of the file, but the path relative to
* the FileIoSource directory.
* </p>
*/
public String getName() {
return entryName;
}
/**
* Return the time the file was last modified.
*/
public long lastModified() {
return con.getLastModified();
}
/**
* Return the size of the file.
*/
public long size() {
return con.getContentLength();
}
/**
* Return the input stream for this file.
*/
public InputStream getInputStream() throws IOException {
return con.getInputStream();
}
}
@@ -0,0 +1,81 @@
/**
* 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.resource;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.ServletContext;
import com.avaje.ebeaninternal.server.lib.util.GeneralException;
/**
* A file system directory represented as a FileSource.
*/
public class UrlResourceSource extends AbstractResourceSource implements ResourceSource {
ServletContext sc;
String basePath;
String realPath;
/**
* Create the source based on a directory name.
*/
public UrlResourceSource(ServletContext sc, String basePath){
this.sc = sc;
if (basePath == null){
this.basePath = "/";
} else {
this.basePath = "/"+basePath+"/";
}
this.realPath = sc.getRealPath(basePath);
}
/**
* Returns the "real path" from the ServletContext root.
* <p>
* This can be null for unpacked WAR deployment.
* </p>
*/
public String getRealPath() {
return realPath;
}
/**
* Search for the given URL resource and return as ResourceContent.
* <p>
* Returns null if the resource is not found.
* </p>
*/
public ResourceContent getContent(String entry) {
try {
URL url = sc.getResource(basePath+entry);
if (url != null){
return new UrlResourceContent(url, entry);
}
return null;
} catch (MalformedURLException ex){
throw new GeneralException(ex);
}
}
}
@@ -0,0 +1,13 @@
<html>
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=iso-8859-1">
<title>AvajeLib</title>
</head>
<body BGCOLOR="#ffffff">
Service for reading content from either the file system or servlet context.
<p>
A service used to read deployment content such as xml files, images etc
taking into account the environment (servlet war file or file system).
</p>
</body>
</html>
@@ -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>
@@ -0,0 +1,276 @@
/**
* 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.thread;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A thread that belongs to a ThreadPool. It will return to the Threadpool when
* it has finished its assigned task.
*/
public class PooledThread implements Runnable {
private static final Logger logger = Logger.getLogger(PooledThread.class.getName());
/**
* Create the PooledThread.
*/
protected PooledThread(ThreadPool threadPool, String name, boolean isDaemon,
Integer threadPriority) {
this.name = name;
this.threadPool = threadPool;
this.lastUsedTime = System.currentTimeMillis();
thread = new Thread(this, name);
thread.setDaemon(isDaemon);
if (threadPriority != null) {
thread.setPriority(threadPriority.intValue());
}
//thread.start();
}
protected void start() {
thread.start();
}
/**
* Assign work to this thread. The thread will notify the listener when it
* has finished the work.
*/
public boolean assignWork(Work work) {
synchronized (workMonitor) {
this.work = work;
workMonitor.notifyAll();
}
return true;
}
/**
* process any assigned work until stopped or interrupted.
*/
public void run() {
// process assigned work until we receive a shutdown signal
synchronized (workMonitor) {
while (!isStopping) {
try {
if (work == null) {
workMonitor.wait();
}
} catch (InterruptedException e) {
}
doTheWork();
}
}
// Tell stop() we have shut ourselves down successfully
synchronized (threadMonitor) {
threadMonitor.notifyAll();
}
//Log.debug("PooledThread [" + getName() + "] finished ");
isStopped = true;
}
/**
* Actually do the work and gather the appropriate measures.
*/
private void doTheWork() {
if (isStopping){
return;
}
long startTime = System.currentTimeMillis();
if (work == null) {
// probably shutting down the thread
} else {
try {
work.setStartTime(startTime);
work.getRunnable().run();
} catch (Throwable ex) {
logger.log(Level.SEVERE, null, ex);
if (wasInterrupted) {
this.isStopping = true;
threadPool.removeThread(this);
logger.info("PooledThread [" + name + "] removed due to interrupt");
try {
thread.interrupt();
} catch (Exception e){
String msg = "Error interrupting PooledThead["+name+"]";
logger.log(Level.SEVERE, msg, e);
}
return;
}
}
}
lastUsedTime = System.currentTimeMillis();
totalWorkCount++;
totalWorkExecutionTime = totalWorkExecutionTime + lastUsedTime - startTime;
this.work = null;
threadPool.returnThread(this);
}
/**
* Try to interrupt the thread.
* <p>
* If the Thread was interrupted then it will be removed from the pool.
* </p>
*/
public void interrupt() {
// set a flag so doTheWork knows that it was interrupted
// and removes rather than returns
wasInterrupted = true;
try {
thread.interrupt();
} catch (SecurityException ex) {
wasInterrupted = false;
throw ex;
}
}
/**
* Returns true if the thread has finished.
*/
public boolean isStopped() {
return isStopped;
}
/**
* Stop the thread relatively nicely. It will wait a maximum of 10 seconds
* for it to complete any existing work.
*/
protected void stop() {
isStopping = true;
synchronized (threadMonitor) {
assignWork(null);
//trace("stop assigned null work...");
try {
threadMonitor.wait(10000);
} catch (InterruptedException e) {
;
}
}
thread = null;
threadPool.removeThread(this);
}
/**
* return the name of the thread.
*/
public String getName() {
return name;
}
/**
* Returns the currently executing work, otherwise null.
*/
public Work getWork() {
return work;
}
/**
* The total number of jobs this thread has run.
*/
public int getTotalWorkCount() {
return totalWorkCount;
}
/**
* The total time for performing all assigned work.
*/
public long getTotalWorkExecutionTime() {
return totalWorkExecutionTime;
}
/**
* Returns the time this thread was last used.
*/
public long getLastUsedTime() {
return lastUsedTime;
}
/**
* Flag to indicate that the thread was interrupted.
*/
private boolean wasInterrupted = false;
/**
* The time the thread was last used.
*/
private long lastUsedTime;
/**
* The work to run
*/
private Work work = null;
/**
* Set to indicate the thread is stopping.
*/
private boolean isStopping = false;
/**
* Set when the thread has stopped.
*/
private boolean isStopped = false;
/**
* The background thread.
*/
private Thread thread = null;
/**
* The pool this worker belongs to.
*/
private ThreadPool threadPool;
/**
* The name of the Thread
*/
private String name = null;
/**
* The thread synchronization object.
*/
private Object threadMonitor = new Object();
/**
* The monitor for work notification.
*/
private Object workMonitor = new Object();
/**
* Total number of work performed.
*/
private int totalWorkCount = 0;
/**
* Total work execution time.
*/
private long totalWorkExecutionTime = 0;
}
@@ -0,0 +1,489 @@
/**
* 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.thread;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This is a pool of threads which can be assigned work.
* <p>
* The Pool will automatically grow as required up to its maximum pool size. The
* Pool will be automatically shrink by trimming threads that have been idle for
* some time.
* </p>
*/
public class ThreadPool {
private static final Logger logger = Logger.getLogger(ThreadPool.class.getName());
/**
* The max idle time used to trim idle threads from the pool.
*/
private long maxIdleTime;
/**
* The name of the pool
*/
private String poolName;
/**
* The initial pool size.
*/
private int minSize;
/**
* Whether or not the threads are going to be Daemon threads.
*/
private boolean isDaemon;
/**
* Flag to indicate that the pool is being shutdown.
*/
private boolean isStopping = false;
/**
* The priority or the threads. Can be null, in which case the threads have
* the default priority.
*/
private Integer threadPriority;
/**
* Incrementing int for thread name. NB: currentThreadCount will go up and
* down as the pool grows and shrinks.
*/
private int uniqueThreadID;
/**
* List of PooledThread that are free for work.
*/
private Vector<PooledThread> freeList = new Vector<PooledThread>();
/**
* List of PooledThread that are busy.
*/
private Vector<PooledThread> busyList = new Vector<PooledThread>();
/**
* List holding queued work.
*/
private Vector<Work> workOverflowQueue = new Vector<Work>();
/**
* The maximum number of threads to grow to. Hitting this limit will have
* performance ramifications.
*/
private int maxSize = 100;
/**
* Flag that the pool should terminate all the threads and stop.
*/
private boolean stopThePool;
/**
* Create the ThreadPool.
*/
public ThreadPool(String poolName, boolean isDaemon, Integer threadPriority) {
this.poolName = poolName;
this.stopThePool = false;
this.isDaemon = isDaemon;
this.threadPriority = threadPriority;
}
/**
* Return true if the pool is shutting down.
*/
public boolean isStopping() {
return isStopping;
}
/**
* Return the name of the thread pool.
*/
public String getName() {
return poolName;
}
/**
* Set the minimum size the pool should try to maintain.
*/
public void setMinSize(int minSize) {
if (minSize > 0) {
if (minSize > maxSize) {
this.maxSize = minSize;
}
this.minSize = minSize;
maintainPoolSize();
}
}
/**
* Return the minimum size the pool should maintain.
*/
public int getMinSize() {
return minSize;
}
/**
* Set the maximum size the pool should grow to.
*/
public void setMaxSize(int maxSize) {
if (maxSize > 0) {
if (minSize > maxSize) {
minSize = maxSize;
}
this.maxSize = maxSize;
maintainPoolSize();
}
}
/**
* Return the maximum size this pool can grow to.
*/
public int getMaxSize() {
return maxSize;
}
/**
* Return the total number of busy and free threads in the pool.
*/
public int size() {
return busyList.size() + freeList.size();
}
/**
* Return the number of currently busy threads.
*/
public int getBusyCount() {
return busyList.size();
}
/**
* Assign a task to the thread pool, specifing the options to wait or queue
* the task if the pool is fully busy and can't grow.
* <p>
* When the pool is fully busy...
* </p>
* <p>
* addToQueue=true -> work is added to queue, returns false<br>
* addToQueue=false -> work is not done or queued, returns false<br>
* </p>
*
* @param work the runnable work to do.
* @param addToQueueIfFull If the pool is maxed out and this is true then it
* queues the Runnable.
*/
public boolean assign(Runnable work, boolean addToQueueIfFull) {
if (stopThePool) {
throw new RuntimeException("Pool is stopping... no more work please.");
}
Work runWork = new Work(work);
// get the next available thread in the pool (block)
PooledThread thread = getNextAvailableThread();
if (thread != null) {
// assign the work to that thread
busyList.add(thread);
thread.assignWork(runWork);
return true;
} else {
if (addToQueueIfFull) {
runWork.setEnterQueueTime(System.currentTimeMillis());
workOverflowQueue.add(runWork);
}
return false;
}
}
/**
* Remove the thread from the pool. The thread should be stopped before it
* is removed.
*/
protected void removeThread(PooledThread thread) {
synchronized (freeList) {
busyList.remove(thread);
freeList.remove(thread);
freeList.notify();
// if (ThreadPoolManager.getDebugLevel()>0){
//Log.debug("PooledThread stopped [" + getName() + "]");
// }
}
}
/**
* fired when a Thread from the pool has finished, and can be put back into
* the pool.
*/
protected void returnThread(PooledThread thread) {
synchronized (freeList) {
// deregister from the busyList
busyList.remove(thread);
if (!workOverflowQueue.isEmpty()) {
// get the first bit of work off the queue
Work queuedWork = (Work) workOverflowQueue.remove(0);
// work out the queue time and counts etc
queuedWork.setExitQueueTime(System.currentTimeMillis());
busyList.add(thread);
thread.assignWork(queuedWork);
} else {
// put the thread back onto the available list
freeList.add(thread);
// tell shutdown() one has returned
freeList.notify();
}
}
}
/**
* Get the next available thread. Block until thread is available. NB: The
* dispatcher is blocked but work can still be assigned to the dispatcher in
* a non-blocking way
*/
private PooledThread getNextAvailableThread() {
synchronized (freeList) {
if (!freeList.isEmpty()) {
return (PooledThread) freeList.remove(0);
}
if (size() < maxSize) {
return growPool(true);
}
return null;
}
}
/**
* Return an Iterator of PooledThread that are currently running. You should
* only use this for display. Use the getPooledThread() or interrupt()
* methods to interrupt a particular thread.
*
* @return an Iterator of busy PooledThread's.
*/
public Iterator<PooledThread> getBusyThreads() {
synchronized (freeList) {
return busyList.iterator();
}
}
/**
* Shutdown the threadpool stopping all the threads. This will
* wait until any busy threads have finished their assigned work.
*/
protected void shutdown() {
synchronized (freeList) {
isStopping = true;
int size = size();
if (size > 0){
String msg = null;
msg = "ThreadPool [" + poolName + "] Shutting down; threadCount[" + size()
+ "] busyCount[" + getBusyCount() + "]";
logger.info(msg);
}
stopThePool = true;
while (!freeList.isEmpty()) {
PooledThread thread = (PooledThread) freeList.remove(0);
thread.stop();
}
try {
while (getBusyCount() > 0) {
// synchronized (freeList) {
String msg = "ThreadPool [" + poolName + "] has [" + getBusyCount()
+ "] busy threads, waiting for those to finish.";
logger.info(msg);
Iterator<PooledThread> busyThreads = getBusyThreads();
while (busyThreads.hasNext()) {
PooledThread busyThread = (PooledThread) busyThreads.next();
String threadName = busyThread.getName();
Work work = busyThread.getWork();
String busymsg = "Busy thread [" + threadName + "] work[" + work + "]";
logger.info(busymsg);
}
// trace("wait for a busy thread to be put back into
// freeList");
freeList.wait();
PooledThread thread = (PooledThread) freeList.remove(0);
// trace("wait finished...now shut it down [" +
// thread.getName() + "]");
if (thread != null) {
thread.stop();
}
}
} catch (InterruptedException e) {
logger.log(Level.SEVERE, null, e);
}
}
}
/**
* Trim or grow the pool leaving at least min free.
*/
protected void maintainPoolSize() {
synchronized (freeList) {
if (isStopping) {
// don't bother as the pool is shutting down
return;
}
int numToStop = size() - minSize;
if (numToStop > 0) {
// should trim idle threads as we are over the minSize
long usedAfter = System.currentTimeMillis() - maxIdleTime;
ArrayList<PooledThread> stopList = new ArrayList<PooledThread>();
Iterator<PooledThread> it = freeList.iterator();
while (it.hasNext() && numToStop > 0) {
PooledThread thread = (PooledThread) it.next();
if (thread.getLastUsedTime() < usedAfter) {
stopList.add(thread);
numToStop--;
}
}
Iterator<PooledThread> stopIt = stopList.iterator();
while (stopIt.hasNext()) {
PooledThread thread = (PooledThread) stopIt.next();
thread.stop();
}
}
int numToAdd = minSize - size();
if (numToAdd > 0) {
// should add some more to the pool
for (int i = 0; i < numToAdd; i++) {
growPool(false);
}
}
}
}
/**
* Interrupt a named thread that is currently busy.
* <p>
* Returns the thread that was interrupted or null if the thread
* was not found. If the thread was interrupted then it will
* automatically be stopped and removed from the pool.
* </p>
* <p>
* Note that it may take some time to actually interrupt the thread so
* an immediate test to see if the thread stopped will probably be wrong.
* <pre><code>
* ThreadPool test = ThreadPoolManager.getThreadPool("test");
* PooledThread pt = test.interrupt("test.1");
* if (pt == null) {
* // the thread was not found, perhaps finished?
* } else {
* // give interrupt a little time to execute
* Thread.sleep(1000);
* boolean hasStopped = pt.isStopped();
* //..
* }
* </code></pre>
* </p>
* @return the thread that was interrupted
*/
public PooledThread interrupt(String threadName) {
PooledThread thread = getBusyThread(threadName);
if (thread != null) {
thread.interrupt();
return thread;
}
return null;
}
/**
* Find a thread using its name from the busy list. Returns null if the
* thread is not found in the busy list.
*/
public PooledThread getBusyThread(String threadName) {
synchronized (freeList) {
Iterator<PooledThread> it = getBusyThreads();
while (it.hasNext()) {
PooledThread pt = (PooledThread) it.next();
if (pt.getName().equals(threadName)) {
return pt;
}
}
return null;
}
}
/**
* Grow the pool with the option of either putting it on the available list,
* or returning it.
*/
private PooledThread growPool(boolean andReturn) {
synchronized (freeList) {
String threadName = poolName + "." + uniqueThreadID++;
PooledThread bgw = new PooledThread(this, threadName, isDaemon, threadPriority);
bgw.start();
if (logger.isLoggable(Level.FINE)) {
logger.fine("ThreadPool grow created [" + threadName + "] size[" + size() + "]");
}
if (andReturn) {
return bgw;
} else {
freeList.add(bgw);
return null;
}
}
}
/**
* Return the maximum amount of time in millis that Threads can be idle
* before they are trimmed.
*/
public long getMaxIdleTime() {
return maxIdleTime;
}
/**
* Set the maxiumium amount of time in millis that Threads can be idle
* before they are trimed.
*/
public void setMaxIdleTime(long maxIdleTime) {
this.maxIdleTime = maxIdleTime;
}
}
@@ -0,0 +1,194 @@
/**
* 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.thread;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebeaninternal.server.lib.BackgroundThread;
/**
* Singleton that manages a list of named ThreadPools.
*/
public class ThreadPoolManager implements Runnable {
private static final class Single {
private static final ThreadPoolManager me = new ThreadPoolManager();
}
private static int debugLevel = 0;
/**
* set when the pools are being shutdown.
*/
private boolean isShuttingDown = false;
/**
* Holds all the thread pools.
*/
private ConcurrentHashMap<String,ThreadPool> threadPoolCache = new ConcurrentHashMap<String, ThreadPool>();
/**
* The default time threads are idle before they are stopped and removed.
* This can occur when the pool grows larger than the min size and then goes idle
* for some time.
*/
private long defaultIdleTime;
private ThreadPoolManager() {
initialise();
}
private void initialise() {
debugLevel = GlobalProperties.getInt("threadpool.debugLevel", 0);
defaultIdleTime = 1000 * GlobalProperties.getInt("threadpool.idletime", 60);
int freqIsSecs = GlobalProperties.getInt("threadpool.sleeptime", 30);
BackgroundThread.add(freqIsSecs, this);
}
/**
* Set the debug level.
*/
public static void setDebugLevel(int level) {
debugLevel = level;
}
/**
* Return the debug level.
*/
public static int getDebugLevel() {
return debugLevel;
}
/**
* Periodically maintains the pool size. Stops threads that have
* been idle for too long and ensures the minimum number of threads.
* <p>
* To change this you can set the threadpool.idletime property:<br>
* <br>
* <b><code>## set threadpool idletime to 120 seconds</code></b><br>
* <b><code>threadpool.idletime=120</code></b><br>
* </p>
*/
public void run() {
if (!isShuttingDown) {
maintainPoolSize();
}
}
/**
* Return the named thread pool.
*/
public static ThreadPool getThreadPool(String poolName) {
return Single.me.getPool(poolName);
}
/**
* Return the named ThreadPool. If the ThreadPool doesn't exist it will be
* created.
*/
private ThreadPool getPool(String poolName) {
synchronized (this) {
ThreadPool threadPool = (ThreadPool) threadPoolCache.get(poolName);
if (threadPool == null) {
threadPool = createThreadPool(poolName);
threadPoolCache.put(poolName, threadPool);
}
return threadPool;
}
}
/**
* Returns an iterator of ThreadPools.
* <p>
* Note that the ThreadPools should not be removed by the iterator.
* </p>
*/
public static Iterator<ThreadPool> pools() {
return Single.me.threadPoolCache.values().iterator();
}
/**
* Maintain the size of all the thread pools.
* Trims down to minimum size threads that have been idle for a while.
* Adds threads if it is short of the minimum size.
*/
private void maintainPoolSize() {
if (isShuttingDown){
return;
}
synchronized (this) {
Iterator<ThreadPool> e = pools();
while (e.hasNext()) {
ThreadPool pool = (ThreadPool) e.next();
pool.maintainPoolSize();
}
}
}
/**
* Shutdown all the ThreadPools nicely.
* This will wait for all currently runnable and queued work to finish.
*/
public static void shutdown() {
Single.me.shutdownPools();
}
private void shutdownPools() {
synchronized (this) {
isShuttingDown = true;
Iterator<ThreadPool> i = pools();
while (i.hasNext()) {
ThreadPool pool = (ThreadPool) i.next();
pool.shutdown();
}
}
}
private ThreadPool createThreadPool(String poolName) {
int min = GlobalProperties.getInt("threadpool." + poolName + ".min", 0);
int max = GlobalProperties.getInt("threadpool." + poolName + ".max", 100);
long idle = 1000 * GlobalProperties.getInt("threadpool." + poolName + ".idletime", -1);
if (idle < 0) {
idle = defaultIdleTime;
}
boolean isDaemon = true;
Integer priority = null;
String threadPriority = GlobalProperties.get("threadpool." + poolName + ".priority", null);
if (threadPriority != null) {
priority = new Integer(threadPriority);
}
ThreadPool newPool = new ThreadPool(poolName, isDaemon, priority);
newPool.setMaxSize(max);
newPool.setMinSize(min);
newPool.setMaxIdleTime(idle);
return newPool;
}
};
@@ -0,0 +1,113 @@
/**
* 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.thread;
/**
* Used internally by the ThreadPool to wrap a Runnable that is
* going to be run.
*
* <p>Used to maintains some useful times about the Runnable in terms of when
* it was queued and then eventually run.</p>
*/
public class Work {
/**
* Create a Runnable Work.
*/
public Work(Runnable runnable) {
this.runnable = runnable;
}
/**
* Return the associated Runnable object.
*/
public Runnable getRunnable() {
return runnable;
}
/**
* Return the time this work actually started.
*/
public long getStartTime() {
return startTime;
}
/**
* Sets the time this work actually started.
*/
public void setStartTime(long startTime) {
this.startTime = startTime;
}
/**
* Return the time this entered the queue.
*/
public long getEnterQueueTime() {
return enterQueueTime;
}
/**
* Set the time this entered the queue.
*/
public void setEnterQueueTime(long enterQueueTime) {
this.enterQueueTime = enterQueueTime;
}
/**
* Return the time this left the queue.
*/
public long getExitQueueTime() {
return exitQueueTime;
}
/**
* Set the time this work left the queue.
*/
public void setExitQueueTime(long exitQueueTime) {
this.exitQueueTime = exitQueueTime;
}
/**
* The same as getDescription().
*/
public String toString() {
return getDescription();
}
/**
* Return a description of this work.
*/
public String getDescription() {
StringBuffer sb = new StringBuffer();
sb.append("Work[");
if (runnable != null){
sb.append(runnable.toString());
}
sb.append("]");
return sb.toString();
}
private Runnable runnable;
private long exitQueueTime;
private long enterQueueTime;
private long startTime;
};
@@ -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">
ThreadPool service.
<P>
Service providing thread pooling for executing background tasks.
</P>
</Body>
</HTML>
@@ -0,0 +1,40 @@
/**
* 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.util;
/**
* A general exception when creating an Object.
*/
public class CreateObjectException extends RuntimeException
{
static final long serialVersionUID = 7061559938704539736L;
public CreateObjectException(Exception cause) {
super(cause);
}
public CreateObjectException(String s, Exception cause) {
super(s, cause);
}
public CreateObjectException(String s) {
super(s);
}
}
@@ -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.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
/**
* A lightweight tree structure for simple XML handling.
* <p>
* It removes support for nodes being mixed with content. That is, a node can
* only contain content or a list of one or more child nodes. It does not
* support mixing bits of content between the child nodes.
* </p>
* <p>
* Although designed to simplify XML in supported cases it can be used as a
* general tree structure with attributes of java Objects.
* </p>
*/
public class Dnode {
int level;
String nodeName;
String nodeContent;
ArrayList<Dnode> children;
LinkedHashMap<String, String> attrList = new LinkedHashMap<String, String>();
/**
* Create a node.
*/
public Dnode() {
}
/**
* Parse the raw XML string.
*/
public static Dnode parse(String s){
DnodeReader r = new DnodeReader();
return r.parseXml(s);
}
/**
* Return the node as XML.
*/
public String toXml() {
StringBuilder sb = new StringBuilder();
generate(sb);
return sb.toString();
}
/**
* Generate this node as xml to the buffer.
*/
public StringBuilder generate(StringBuilder sb) {
if (sb == null) {
sb = new StringBuilder();
}
sb.append("<").append(nodeName);
Iterator<String> it = attributeNames();
while (it.hasNext()) {
String attr = it.next();
Object attrValue = getAttribute(attr);
sb.append(" ").append(attr).append("=\"");
if (attrValue != null) {
sb.append(attrValue);
}
sb.append("\"");
}
if (nodeContent == null && !hasChildren()) {
sb.append(" />");
} else {
sb.append(">");
if (children != null && children.size() > 0) {
for (int i = 0; i < children.size(); i++) {
Dnode child = children.get(i);
child.generate(sb);
}
}
if (nodeContent != null) {
sb.append(nodeContent);
}
sb.append("</").append(nodeName).append(">");
}
return sb;
}
/**
* Return the node name.
*/
public String getNodeName() {
return nodeName;
}
/**
* Set the node name.
*/
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
/**
* Return the node content.
*/
public String getNodeContent() {
return nodeContent;
}
/**
* Set the node content.
*/
public void setNodeContent(String nodeContent) {
this.nodeContent = nodeContent;
}
/**
* Return true if this node has children.
*/
public boolean hasChildren() {
return getChildrenCount() > 0;
}
/**
* Return the number of children this node has.
*/
public int getChildrenCount() {
if (children == null) {
return 0;
}
return children.size();
}
/**
* Remove a ancestor node.
*/
public boolean remove(Dnode node) {
if (children == null) {
return false;
}
if (children.remove(node)) {
return true;
}
Iterator<Dnode> it = children.iterator();
while (it.hasNext()) {
Dnode child = it.next();
if (child.remove(node)) {
return true;
}
}
return false;
}
/**
* List of children nodes.
*/
public List<Dnode> children() {
if (children == null) {
return null;
}
return children;
}
/**
* Add a child.
*/
public void addChild(Dnode child) {
if (children == null) {
children = new ArrayList<Dnode>();
}
children.add(child);
child.setLevel(level + 1);
}
/**
* Return the level or depth of the node from the root.
*/
public int getLevel() {
return level;
}
/**
* Set the level or depth of this node from the root.
*/
public void setLevel(int level) {
this.level = level;
if (children != null) {
for (int i = 0; i < children.size(); i++) {
Dnode child = children.get(i);
child.setLevel(level + 1);
}
}
}
/**
* Find the first matching node using nodeName. This is a depth first tree
* search.
*/
public Dnode find(String nodeName) {
return find(nodeName, null, null);
}
/**
* Find the first node matching nodeName and attribute value. This is a
* depth first tree search.
*/
public Dnode find(String nodeName, String attrName, Object value) {
return find(nodeName, attrName, value, -1);
}
/**
* Search for a single node with control over maxLevel. Find the first node
* matching nodeName and attribute value. If attrName and value are null
* then this will just search using the nodeName. This is a depth first tree
* search. Once a matching node is found the search will stop.
*/
public Dnode find(String nodeName, String attrName, Object value, int maxLevel) {
ArrayList<Dnode> list = new ArrayList<Dnode>();
findByNode(list, nodeName, true, attrName, value, maxLevel);
if (list.size() >= 1) {
return list.get(0);
}
return null;
}
/**
* Find all the nodes that match the nodeName.
*
*/
public List<Dnode> findAll(String nodeName, int maxLevel) {
int level = -1;
if (maxLevel > 0) {
level = this.level + maxLevel;
}
return findAll(nodeName, null, null, level);
}
/**
* Find all the nodes that match the nodeName and attribute value.
*/
public List<Dnode> findAll(String nodeName, String attrName, Object value, int maxLevel) {
if (nodeName == null && attrName == null) {
throw new RuntimeException("You can not have both nodeName and attrName null");
}
ArrayList<Dnode> list = new ArrayList<Dnode>();
findByNode(list, nodeName, false, attrName, value, maxLevel);
return list;
}
/**
* Used for recursive calling.
*/
private void findByNode(List<Dnode> list, String node, boolean findOne,String attrName, Object value, int maxLevel) {
if (findOne && list.size() == 1) {
return;
}
if (node == null || node.equals(nodeName)) {
if (attrName == null || value.equals(getAttribute(attrName))) {
list.add(this);
if (findOne) {
return;
}
}
}
if (maxLevel > 0 && level >= maxLevel) {
// hit max level
} else if (children != null) {
// recursively search the children
for (int i = 0; i < children.size(); i++) {
Dnode child = children.get(i);
child.findByNode(list, node, findOne, attrName, value,maxLevel);
}
}
}
/**
* The attribute names as strings.
*/
public Iterator<String> attributeNames() {
return attrList.keySet().iterator();
}
/**
* Return the attribute for a given name.
*/
public String getAttribute(String name) {
return attrList.get(name);
}
/**
* Returns an Attribute as a String.
* <p>
* Will throw a ClassCastException if the attribute is not a String.
* </p>
*/
public String getStringAttr(String name, String defaultValue) {
Object o = attrList.get(name);
if (o == null){
return defaultValue;
} else {
return o.toString();
}
}
/**
* Set an attribute.
*/
public void setAttribute(String name, String value) {
attrList.put(name, value);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[").append(getNodeName()).append(" ").append(attrList).append("]");
return sb.toString();
}
}
@@ -0,0 +1,219 @@
/**
* 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.util;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
/**
* Parse an xml document into a Dnode tree.
*/
public class DnodeParser extends DefaultHandler {
/**
* The root of the DContent tree.
*/
Dnode root;
/**
* The current node being parsed.
*/
Dnode currentNode;
/**
* The nodeContent buffer.
*/
StringBuilder buffer;
/**
* Used to stack the nodes.
*/
Stack<Dnode> stack = new Stack<Dnode>();
/**
* The class used to construct new nodes. Should be Dnode or a subtype of
* Dnode.
*/
Class<?> nodeClass = Dnode.class;
int depth = 0;
/**
* Trim whitespace from the content.
*/
boolean trimWhitespace = true;
/**
* The name of the tag that contains html content
*/
String contentName;
/**
* The depth of the tag that contains the html content
*/
int contentDepth;
/**
* If true then trim the whitespace from the content.
*/
public boolean isTrimWhitespace() {
return trimWhitespace;
}
/**
* Set whether to trim whitespace from the content.
*/
public void setTrimWhitespace(boolean trimWhitespace) {
this.trimWhitespace = trimWhitespace;
}
/**
* Return the root node of the DContent tree.
*/
public Dnode getRoot() {
return root;
}
/**
* Set the type class of node to be created.
*/
public void setNodeClass(Class<?> nodeClass) {
this.nodeClass = nodeClass;
}
/**
* Create a new Dnode using the nodeClass.
*/
private Dnode createNewNode() {
try {
return (Dnode) nodeClass.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* process a startElement.
*/
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
super.startElement(uri, localName, qName, attributes);
depth++;
boolean isContent = (contentName != null);
if (isContent){
// must be html content... add the begin tag as content
buffer.append("<").append(localName);
for (int i = 0; i < attributes.getLength(); i++) {
String key = attributes.getLocalName(i);
String val = attributes.getValue(i);
buffer.append(" ").append(key).append("='").append(val).append("'");
}
buffer.append(">");
return;
}
buffer = new StringBuilder();
Dnode node = createNewNode();
node.setNodeName(localName);
for (int i = 0; i < attributes.getLength(); i++) {
String key = attributes.getLocalName(i);
String val = attributes.getValue(i);
node.setAttribute(key, val);
if ("type".equalsIgnoreCase(key) && "content".equalsIgnoreCase(val)) {
// this tag contains html content
// no more nodes until end tag is found
contentName = localName;
contentDepth = depth-1;
}
}
if (root == null) {
root = node;
}
if (currentNode != null) {
currentNode.addChild(node);
}
stack.push(node);
currentNode = node;
}
/**
* append the node content.
*/
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
String s = new String(ch, start, length);
int p = s.indexOf('\r');
int p2 = s.indexOf('\n');
if (p == -1 && p2 > -1) {
// This is probably not an issue but tidys up content
// in my text editor
s = StringHelper.replaceString(s, "\n", "\r\n");
}
buffer.append(s);
}
/**
* process the endElement.
*/
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
depth--;
if (contentName != null){
// is this the end of the content?
if (contentName.equals(localName) && contentDepth == depth){
contentName = null;
} else {
// the html content end tag
buffer.append("</").append(localName).append(">");
}
return;
}
String content = buffer.toString();
buffer.setLength(0);
if (content.length() > 0) {
if (trimWhitespace) {
content = content.trim();
}
if (content.length() > 0) {
currentNode.setNodeContent(content);
}
}
stack.pop();
if (!stack.isEmpty()) {
// get the new currentNode
currentNode = (Dnode) stack.pop();
stack.push(currentNode);
}
}
}
@@ -0,0 +1,87 @@
/**
* 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.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* Parses an XML inputstream returning a Dnode tree.
*/
public class DnodeReader {
public Dnode parseXml(String str) {
try {
ByteArrayOutputStream bao = new ByteArrayOutputStream(str.length());
OutputStreamWriter osw = new OutputStreamWriter(bao);
StringReader sr = new StringReader(str);
int charBufferSize = 1024;
char[] buf = new char[charBufferSize];
int len;
while ((len = sr.read(buf, 0, buf.length)) != -1) {
osw.write(buf, 0, len);
}
sr.close();
osw.flush();
osw.close();
bao.flush();
bao.close();
InputStream is = new ByteArrayInputStream(bao.toByteArray());
return parseXml(is);
} catch (IOException ex){
throw new RuntimeException(ex);
}
}
/**
* Parse the XML inputstream returning the Dnode tree.
*/
public Dnode parseXml(InputStream in) {
try {
InputSource inSource = new InputSource(in);
DnodeParser parser = new DnodeParser();
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(parser);
myReader.parse(inSource);
return parser.getRoot();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,39 @@
/**
* 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.util;
/**
* A general exception that can be used for multiple purposes.
*/
public class GeneralException extends RuntimeException {
private static final long serialVersionUID = 5783084420007103280L;
public GeneralException(Exception cause) {
super(cause);
}
public GeneralException(String s, Exception cause) {
super(s, cause);
}
public GeneralException(String s) {
super(s);
}
}
@@ -0,0 +1,40 @@
/**
* 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.util;
/**
* A general exception for invalid data.
*/
public class InvalidDataException extends RuntimeException
{
static final long serialVersionUID = 7061559938704539846L;
public InvalidDataException(Exception cause) {
super(cause);
}
public InvalidDataException(String s, Exception cause) {
super(s, cause);
}
public InvalidDataException(String s) {
super(s);
}
}
@@ -0,0 +1,62 @@
/**
* 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.util;
/**
* An Email address with an associated alias.
*/
public class MailAddress {
String alias;
String emailAddress;
/**
* Create an address with an optional alias.
*/
public MailAddress(String alias, String emailAddress){
this.alias = alias;
this.emailAddress = emailAddress;
}
/**
* Return the alias.
* If the alias is null this returns an empty string.
*/
public String getAlias() {
if (alias == null){
return "";
}
return alias;
}
/**
* Return the email address.
*/
public String getEmailAddress(){
return emailAddress;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(getAlias()).append(" ").append("<").append(getEmailAddress()).append(">");
return sb.toString();
}
}
@@ -0,0 +1,66 @@
/**
* 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.util;
/**
* Represents the success or failure of a mail send.
*/
public class MailEvent {
/**
* The error indicating a send failure.
*/
Throwable error;
/**
* The message that was sent.
*/
MailMessage message;
/**
* The message send failed with an error.
*/
public MailEvent(MailMessage message, Throwable error){
this.message = message;
this.error = error;
}
/**
* The message that we attempted to send.
*/
public MailMessage getMailMessage() {
return message;
}
/**
* Returns true if the message was sent successfully.
*/
public boolean wasSuccessful() {
return (error == null);
}
/**
* The error indicating the send failed.
*/
public Throwable getError() {
return error;
}
}
@@ -0,0 +1,30 @@
/**
* 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.util;
/**
* Listens to see if the message was successfully sent.
*/
public interface MailListener {
/**
* Handle the message event.
*/
public void handleEvent(MailEvent event);
}
@@ -0,0 +1,176 @@
/**
* 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.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
/**
* A simple test message that can be sent via smtp.
*/
public class MailMessage {
// /**
// * The subject text.
// */
// String subject;
/**
* The body content.
*/
ArrayList<String> bodylines;
/**
* The sender email address.
*/
MailAddress senderAddress;
/**
* The headers.
*/
HashMap<String,String> header = new HashMap<String, String>();
/**
* the recipient of the email.
*/
MailAddress currentRecipient;
/**
* The list of recipients.
*/
ArrayList<MailAddress> recipientList = new ArrayList<MailAddress>();
/**
* Create the message.
*/
public MailMessage() {
bodylines = new ArrayList<String>();
}
/**
* Set the current recipient.
*/
public void setCurrentRecipient(MailAddress currentRecipient){
this.currentRecipient = currentRecipient;
}
/**
* Return the current recipient.
*/
public MailAddress getCurrentRecipient() {
return currentRecipient;
}
/**
* Add a recipient.
*/
public void addRecipient(String alias, String emailAddress){
recipientList.add(new MailAddress(alias, emailAddress));
}
/**
* Set the sender details.
*/
public void setSender(String alias, String senderEmail){
this.senderAddress = new MailAddress(alias, senderEmail);
}
/**
* Return the sender address.
*/
public MailAddress getSender() {
return senderAddress;
}
/**
* Return the recipient list.
*/
public Iterator<MailAddress> getRecipientList() {
return recipientList.iterator();
}
/**
* add a header to the message.
*/
public void addHeader(String key, String val) {
header.put(key, val);
}
/**
* Set the subject text.
*/
public void setSubject(String subject){
addHeader("Subject", subject);
}
/**
* Return the subject text.
*/
public String getSubject() {
return getHeader("Subject");
}
/**
* Add text to the body.
*/
public void addBodyLine(String line) {
bodylines.add(line);
}
/**
* Return the body text.
*/
public Iterator<String> getBodyLines() {
return bodylines.iterator();
}
/**
* Return the headers.
*/
public Iterator<String> getHeaderFields() {
return header.keySet().iterator();
}
/**
* Return a given header.
*/
public String getHeader(String key) {
return header.get(key);
}
public String toString() {
StringBuilder sb = new StringBuilder(100);
sb.append("Sender: " + senderAddress + "\tRecipient: " + recipientList + "\n");
Iterator<String> hi = header.keySet().iterator();
while (hi.hasNext()) {
String key = hi.next();
String hline = key + ": " + header.get(key) + "\n";
sb.append(hline);
}
sb.append("\n");
Iterator<String> e = bodylines.iterator();
while (e.hasNext()) {
sb.append(e.next()).append("\n");
}
return sb.toString();
}
}
@@ -0,0 +1,231 @@
/**
* 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.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Sends simple MailMessages via smtp.
*/
public class MailSender implements Runnable {
private static final Logger logger = Logger.getLogger(MailSender.class.getName());
int traceLevel = 0;
Socket sserver;
String server;
BufferedReader in;
OutputStreamWriter out;
MailMessage message;
MailListener listener = null;
private static final int SMTP_PORT = 25;
/**
* Create for a given mail server.
*/
public MailSender(String server) {
this.server = server;
}
/**
* Set the listener to handle MessageEvents.
*/
public void setMailListener(MailListener listener){
this.listener = listener;
}
/**
* Send the message.
*/
public void run() {
send(message);
}
/**
* Send the message in a background thread.
*/
public void sendInBackground(MailMessage message){
this.message = message;
Thread thread = new Thread(this);
thread.start();
}
/**
* Send the message in the current thread.
*/
public void send(MailMessage message){
try {
Iterator<MailAddress> i = message.getRecipientList();
while (i.hasNext()) {
MailAddress recipientAddress = (MailAddress) i.next();
sserver = new Socket(server, SMTP_PORT);
send(message, sserver, recipientAddress);
sserver.close();
if (listener != null){
MailEvent event = new MailEvent(message, null);
listener.handleEvent(event);
}
}
} catch (Exception ex) {
if (listener != null){
MailEvent event = new MailEvent(message, ex);
listener.handleEvent(event);
} else {
logger.log(Level.SEVERE, null, ex);
}
}
}
private void send(MailMessage message, Socket sserver, MailAddress recipientAddress) throws IOException {
// A bit convoluted, but doesn't depend on DNS in any way...
InetAddress localhost = sserver.getLocalAddress();
String localaddress = localhost.getHostAddress();
MailAddress sender = message.getSender();
message.setCurrentRecipient(recipientAddress);
// Mandatory header fields, Date and From
if (message.getHeader("Date") == null){
message.addHeader("Date", new java.util.Date().toString());
}
if (message.getHeader("From") == null){
message.addHeader("From", sender.getAlias() + " <" + sender.getEmailAddress() + ">");
}
//if (message.getHeader("From") == null){
message.addHeader("To", recipientAddress.getAlias() + " <" + recipientAddress.getEmailAddress() + ">");
//}
out = new OutputStreamWriter(sserver.getOutputStream());
in = new BufferedReader(new InputStreamReader(sserver.getInputStream()));
String sintro = readln();
if (!sintro.startsWith("220")) { // 220
logger.fine("SmtpSender: intro==" + sintro);
return;
}
writeln("EHLO " + localaddress);
if (!expect250()) {
return;
}
writeln("MAIL FROM:<" + sender.getEmailAddress() + ">");
if (!expect250()) {
return;
}
writeln("RCPT TO:<" + recipientAddress.getEmailAddress() + ">");
if (!expect250()){
return;
}
writeln("DATA");
while (true) { // may be multiple 250 replies pending from server
String line = readln();
if (line.startsWith("3"))
break; // ready to send
if (!line.startsWith("2")) {
logger.fine("SmtpSender.send reponse to DATA: " + line);
return;
}
}
Iterator<String> hi = message.getHeaderFields();
while (hi.hasNext()) {
String key = (String) hi.next();
writeln(key + ": " + message.getHeader(key));
}
writeln(""); // end of header;
Iterator<String> e = message.getBodyLines();
while (e.hasNext()) {
String bline = (String) e.next();
if (bline.startsWith(".")) {
bline = "." + bline;
}
writeln(bline);
}
writeln(".");
expect250();
writeln("QUIT");
}
private boolean expect250() throws IOException {
String line = readln();
if (!line.startsWith("2")) {
logger.info("SmtpSender.expect250: " + line);
return false;
}
return true;
}
private void writeln(String s) throws IOException {
if (traceLevel > 2){
logger.fine("From client: " + s);
}
out.write(s + "\r\n");
out.flush();
}
private String readln() throws IOException {
String line = in.readLine();
if (traceLevel > 1){
logger.fine("From server: " + line);
}
return line;
}
/**
* Set the trace level.
*/
public void setTraceLevel(int traceLevel){
this.traceLevel = traceLevel;
}
/**
* Return the hostname of the local machine.
*/
public String getLocalHostName() {
try {
InetAddress ipaddress = InetAddress.getLocalHost();
String localHost = ipaddress.getHostName();
if (localHost == null) {
return "localhost";
} else {
return localHost;
}
} catch (UnknownHostException e) {
return "localhost";
}
}
}
@@ -0,0 +1,80 @@
/**
* 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.util;
import java.util.LinkedHashMap;
/**
* Utility String class that supports String manipulation functions.
*/
public class MapFromString {
LinkedHashMap<String,String> map = new LinkedHashMap<String,String>();
String mapToString;
int stringLength;
int keyStart = 0;
int eqPos = 0;
int valEnd = 0;
public static LinkedHashMap<String,String> parse(String mapToString) {
MapFromString c = new MapFromString(mapToString);
return c.parse();
}
private MapFromString(String mapToString) {
if (mapToString.charAt(0) == '{'){
mapToString = mapToString.substring(1);
}
if (mapToString.charAt(mapToString.length()-1) == '}'){
mapToString = mapToString.substring(0, mapToString.length()-1);
}
this.mapToString = mapToString;
this.stringLength = mapToString.length();
}
private LinkedHashMap<String,String> parse() {
while(findNext()){
}
return map;
}
private boolean findNext() {
if (keyStart > stringLength){
return false;
}
eqPos = mapToString.indexOf("=",keyStart);
if (eqPos == -1){
throw new RuntimeException("No = after "+keyStart);
}
valEnd = mapToString.indexOf(", ",eqPos);
if (valEnd == -1){
valEnd = mapToString.length();
}
// check that the next valEnd occurs after the next eqPos
String keyValue = mapToString.substring(keyStart,eqPos);
String valValue = mapToString.substring(eqPos+1,valEnd);
map.put(keyValue, valValue);
keyStart = valEnd + 2;
return true;
}
}
@@ -0,0 +1,57 @@
/**
* 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.util;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* Helper methods to determine the mime type based on a file name.
*/
public class MimeTypeHelper {
/**
* Return the mimeType for a given file path.
* This will extract the file extension, and then use that
* to look up an appropriate mime type (from the mimetypes.props file).
*
* To add a new mime type, add it to the mimetype.props file.
*/
public static String getMimeType(String filePath) {
int lastPeriod = filePath.lastIndexOf(".");
if (lastPeriod > -1) {
filePath = filePath.substring(lastPeriod+1);
}
try {
return resources.getString(filePath.toLowerCase());
} catch (MissingResourceException e) {
return null;
//String m = "Unable to locate mimetype for ["+filePath.toLowerCase()+"] in mimetypes.properties";
//throw new NotFoundException(m);
}
}
private static ResourceBundle resources = ResourceBundle.getBundle("com.avaje.lib.util.mimetypes");
};
@@ -0,0 +1,40 @@
/**
* 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.util;
/**
* A general exception where data is not found.
*/
public class NotFoundException extends RuntimeException
{
static final long serialVersionUID = 7061559938704539845L;
public NotFoundException(Exception cause) {
super(cause);
}
public NotFoundException(String s, Exception cause) {
super(s, cause);
}
public NotFoundException(String s) {
super(s);
}
}
@@ -0,0 +1,616 @@
/**
* 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.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Utility String class that supports String manipulation functions.
*/
public class StringHelper {
private static final char SINGLE_QUOTE = '\'';
private static final char DOUBLE_QUOTE = '"';
/**
* parses a String of the form name1='value1' name2='value2'. Note that you
* can use either single or double quotes for any particular name value pair
* and the end quote must match the begin quote.
*/
public static HashMap<String, String> parseNameQuotedValue(String tag) throws RuntimeException {
if (tag == null || tag.length() < 1) {
return null;
}
// make sure that the quotes are matched...
// int remainer = countOccurances(tag, ""+quote) % 2;
// if (remainer == 1) {
// dp("remainder = "+remainer);
// throw new StringParsingException("Unmatched quote in "+tag);
// }
// make sure that th last character is not an equals...
// (check now so I don't need to check this every time..)
if (tag.charAt(tag.length() - 1) == '=') {
throw new RuntimeException("missing quoted value at the end of " + tag);
}
HashMap<String, String> map = new HashMap<String, String>();
// recursively parse out the name value pairs...
return parseNameQuotedValue(map, tag, 0);
}
/**
* recursively parse out name value pairs (where the value is quoted, with
* either single or double quotes).
*/
private static HashMap<String, String> parseNameQuotedValue(HashMap<String, String> map,
String tag, int pos) throws RuntimeException {
int equalsPos = tag.indexOf("=", pos);
if (equalsPos > -1) {
// check for begin quote...
char firstQuote = tag.charAt(equalsPos + 1);
if (firstQuote != SINGLE_QUOTE && firstQuote != DOUBLE_QUOTE) {
throw new RuntimeException("missing begin quote at " + (equalsPos) + "["
+ tag.charAt(equalsPos + 1) + "] in [" + tag + "]");
}
// check for end quote...
int endQuotePos = tag.indexOf(firstQuote, equalsPos + 2);
if (endQuotePos == -1) {
throw new RuntimeException("missing end quote [" + firstQuote + "] after " + pos
+ " in [" + tag + "]");
}
// we have a valid name and value...
// dp("pos="+pos+" equalsPos="+equalsPos+"
// endQuotePos="+endQuotePos);
String name = tag.substring(pos, equalsPos);
String value = tag.substring(equalsPos + 2, endQuotePos);
// dp("name="+name+"; value="+value+";");
// trim off any whitespace from the front of name...
name = trimFront(name, " ");
if ((name.indexOf(SINGLE_QUOTE) > -1) || (name.indexOf(DOUBLE_QUOTE) > -1)) {
throw new RuntimeException("attribute name contains a quote [" + name + "]");
}
map.put(name, value);
return parseNameQuotedValue(map, tag, endQuotePos + 1);
} else {
// no more equals... stop parsing...
return map;
}
}
/**
* Returns the number of times a particular String occurs in another String.
* e.g. count the number of single quotes.
*/
public static int countOccurances(String content, String occurs) {
return countOccurances(content, occurs, 0, 0);
}
private static int countOccurances(String content, String occurs, int pos, int countSoFar) {
int equalsPos = content.indexOf(occurs, pos);
if (equalsPos > -1) {
countSoFar = countSoFar + 1;
pos = equalsPos + occurs.length();
// dp("countSoFar="+countSoFar+" pos="+pos);
return countOccurances(content, occurs, pos, countSoFar);
} else {
return countSoFar;
}
}
/**
* Parses out a list of Name Value pairs that are delimited together. Will
* always return a StringMap. If allNameValuePairs is null, or no name
* values can be parsed out an empty StringMap is returned.
*
* @param allNameValuePairs
* the entire string to be parsed.
* @param listDelimiter
* (typically ';') the delimited between the list
* @param nameValueSeparator
* (typically '=') the separator between the name and value
*/
public static Map<String, String> delimitedToMap(String allNameValuePairs,
String listDelimiter, String nameValueSeparator) {
HashMap<String, String> params = new HashMap<String, String>();
if ((allNameValuePairs == null) || (allNameValuePairs.length() == 0)) {
return params;
}
// trim off any leading listDelimiter...
allNameValuePairs = trimFront(allNameValuePairs, listDelimiter);
return getKeyValue(params, 0, allNameValuePairs, listDelimiter, nameValueSeparator);
}
/**
* Trims off recurring strings from the front of a string.
*
* @param source
* the source string
* @param trim
* the string to trim off the front
*/
public static String trimFront(String source, String trim) {
if (source == null) {
return null;
}
if (source.indexOf(trim) == 0) {
// dp("trim ...");
return trimFront(source.substring(trim.length()), trim);
} else {
return source;
}
}
/**
* Return true if the value is null or an empty string.
*/
public static boolean isNull(String value) {
if (value == null || value.trim().length() == 0) {
return true;
}
return false;
}
/**
* Recursively pulls out the key value pairs from a raw string.
*/
private static HashMap<String, String> getKeyValue(HashMap<String, String> map, int pos,
String allNameValuePairs, String listDelimiter, String nameValueSeparator) {
if (pos >= allNameValuePairs.length()) {
// dp("end as "+pos+" >= "+allNameValuePairs.length() );
return map;
}
int equalsPos = allNameValuePairs.indexOf(nameValueSeparator, pos);
int delimPos = allNameValuePairs.indexOf(listDelimiter, pos);
if (delimPos == -1) {
delimPos = allNameValuePairs.length();
}
if (equalsPos == -1) {
// dp("no more equals...");
return map;
}
if (delimPos == (equalsPos + 1)) {
// dp("Ignoring as nothing between delim and equals...
// delim:"+delimPos+" eq:"+equalsPos);
return getKeyValue(map, delimPos + 1, allNameValuePairs, listDelimiter,
nameValueSeparator);
}
if (equalsPos > delimPos) {
// there is a key without a value?
String key = allNameValuePairs.substring(pos, delimPos);
key = key.trim();
if (key.length() > 0) {
map.put(key, null);
}
return getKeyValue(map, delimPos + 1, allNameValuePairs, listDelimiter,
nameValueSeparator);
}
String key = allNameValuePairs.substring(pos, equalsPos);
if (delimPos > -1) {
String value = allNameValuePairs.substring(equalsPos + 1, delimPos);
// dp("cont "+key+","+value+" pos:"+pos+"
// len:"+allNameValuePairs.length());
key = key.trim();
map.put(key, value);
pos = delimPos + 1;
// recurse the rest of the values...
return getKeyValue(map, pos, allNameValuePairs, listDelimiter, nameValueSeparator);
} else {
// dp("ERROR: delimPos < 0 ???");
return map;
}
}
/**
* Convert a string that has delimited values (say comma delimited) in a
* String[]. You must explicitly choose whether or not to include empty
* values (say two commas that a right beside each other.
*
* <P>
* e.g. "alpha,beta,,theta"<br>
* With keepEmpties true, this results in a String[] of size 4 with the
* third one having a String of 0 length. With keepEmpties false, this
* results in a String[] of size 3.
* </P>
* <P>
* </P>
* <P>
* e.g. ",alpha,beta,,theta,"<br>
* With keepEmpties true, this results in a String[] of size 6 with the
* 1st,4th and 6th one having a String of 0 length. With keepEmpties false,
* this results in a String[] of size 3.
* </P>
*/
public static String[] delimitedToArray(String str, String delimiter, boolean keepEmpties) {
ArrayList<String> list = new ArrayList<String>();
int startPos = 0;
delimiter(str, delimiter, keepEmpties, startPos, list);
String[] result = new String[list.size()];
return (String[]) list.toArray(result);
}
private static void delimiter(String str, String delimiter, boolean keepEmpties, int startPos,
ArrayList<String> list) {
int endPos = str.indexOf(delimiter, startPos);
if (endPos == -1) {
if (startPos <= str.length()) {
String lastValue = str.substring(startPos, str.length());
// dp("lastValue="+lastValue);
if (!keepEmpties && lastValue.length() == 0) {
// dp("not keeping...");
} else {
list.add(lastValue);
}
}
// we have finished parsing the string...
return;
} else {
// get the delimited value... add it..
String value = str.substring(startPos, endPos);
// dp(startPos+","+endPos+" value="+value);
if (!keepEmpties && value.length() == 0) {
// dp("not keeping...");
} else {
list.add(value);
}
// recursively search as we are not at the end yet...
delimiter(str, delimiter, keepEmpties, endPos + 1, list);
}
}
/**
* This returns the FIRST string in str that is bounded on the left by
* leftBound, and bounded on the right by rightBound. This will return null
* if the leftBound is not found within str.
*
* <P>
* If leftBound can't be found this returns null.
* </P>
* <P>
* This rightBound can't be found then this throws a
* StringIndexOutOfBoundsException.
* </P>
*
* @param str
* the base string that we will search for the bounded string.
* @param leftBound
* the left bound of the string.
* @param rightBound
* the right bound of the string.
*/
public static String getBoundedString(String str, String leftBound, String rightBound)
throws RuntimeException {
if (str == null) {
throw new RuntimeException("string to parse is null?");
}
int startPos = str.indexOf(leftBound);
if (startPos > -1) {
startPos = startPos + leftBound.length();
int endPos = str.indexOf(rightBound, startPos);
// dp(str+" start:"+startPos+" end:"+endPos);
if (endPos == -1) {
throw new RuntimeException("Can't find rightBound: " + rightBound);
}
return str.substring(startPos, endPos);
} else {
// if no leftBound can be found.. return null... could be in a
// search n parse type loop?
// this keeps "no tag"==null different from "tag not formed
// properly"==StringParsingException
return null;
}
}
/**
* Takes the String bounded by leftBound & rightBound, and replaces it with
* replaceString. Actually removes the left and right bound strings aswell.
*/
public static String setBoundedString(String str, String leftBound, String rightBound,
String replaceString) {
int startPos = str.indexOf(leftBound);
if (startPos > -1) {
// startPos = startPos;
int endPos = str.indexOf(rightBound, startPos + leftBound.length());
if (endPos > -1) {
String toReplace = str.substring(startPos, endPos + 1);
return replaceString(str, toReplace, replaceString);
} else {
return str;
}
} else {
return str;
}
}
// public static String replaceString(String str, String oldSub, String
// newSub) {
//
// if (str == null) {
// return null;
// }
// StringBuilder newSB = new StringBuilder(str.length()+20);
// int iPos = 0;
// int iPrevPos = 0;
//
// while (true) {
// iPos = str.indexOf(oldSub, iPrevPos);
// if (iPos > -1) {
// // found
// newSB.append(str.substring(iPrevPos, iPos));
// newSB.append(newSub);
// iPrevPos = iPos + oldSub.length();
// } else {
// // not found
// newSB.append(str.substring(iPrevPos));
// break;
// }
// }
//
// return newSB.toString();
// }
/**
* This method takes a String and will replace all occurrences of the match
* String with that of the replace String.
*
* @param source
* the source string
* @param match
* the string used to find a match
* @param replace
* the string used to replace match with
* @return the source string after the search and replace
*/
public static String replaceString(String source, String match, String replace) {
if (source == null){
return null;
}
if (replace == null){
return source;
}
if (match == null){
throw new NullPointerException("match is null?");
}
if (match.equals(replace)){
return source;
}
return replaceString(source, match, replace, 30, 0, source.length());
}
/**
* Additionally specify the additionalSize to add to the buffer. This will
* make the buffer bigger so that it doesn't have to grow when replacement
* occurs.
*/
public static String replaceString(String source, String match, String replace,
int additionalSize, int startPos, int endPos) {
if (source == null){
return source;
}
char match0 = match.charAt(0);
int matchLength = match.length();
if (matchLength == 1 && replace.length() == 1) {
char replace0 = replace.charAt(0);
return source.replace(match0, replace0);
}
if (matchLength >= replace.length()) {
additionalSize = 0;
}
int sourceLength = source.length();
int lastMatch = endPos - matchLength;
StringBuilder sb = new StringBuilder(sourceLength + additionalSize);
if (startPos > 0) {
sb.append(source.substring(0, startPos));
}
char sourceChar;
boolean isMatch;
int sourceMatchPos;
for (int i = startPos; i < sourceLength; i++) {
sourceChar = source.charAt(i);
if (i > lastMatch || sourceChar != match0) {
sb.append(sourceChar);
} else {
// check to see if this is a match
isMatch = true;
sourceMatchPos = i;
// check each following character...
for (int j = 1; j < matchLength; j++) {
sourceMatchPos++;
if (source.charAt(sourceMatchPos) != match.charAt(j)) {
isMatch = false;
break;
}
}
if (isMatch) {
i = i + matchLength - 1;
sb.append(replace);
} else {
// was not a match
sb.append(sourceChar);
}
}
}
return sb.toString();
}
/**
* A search and replace with multiple matching strings.
* <p>
* Useful when converting CRNL CR and NL all to a BR tag for example.
* </p>
*
* <pre><code>
* String[] multi = { &quot;\r\n&quot;, &quot;\r&quot;, &quot;\n&quot; };
* content = StringHelper.replaceStringMulti(content, multi, &quot;&lt;br/&gt;&quot;);
* </code></pre>
*/
public static String replaceStringMulti(String source, String[] match, String replace) {
return replaceStringMulti(source, match, replace, 30, 0, source.length());
}
/**
* Additionally specify an additional size estimate for the buffer plus
* start and end positions.
* <p>
* The start and end positions can limit the search and replace. Otherwise
* these default to startPos = 0 and endPos = source.length().
* </p>
*/
public static String replaceStringMulti(String source, String[] match, String replace,
int additionalSize, int startPos, int endPos) {
int shortestMatch = match[0].length();
char[] match0 = new char[match.length];
for (int i = 0; i < match0.length; i++) {
match0[i] = match[i].charAt(0);
if (match[i].length() < shortestMatch) {
shortestMatch = match[i].length();
}
}
StringBuilder sb = new StringBuilder(source.length() + additionalSize);
char sourceChar;
int len = source.length();
int lastMatch = endPos - shortestMatch;
if (startPos > 0) {
sb.append(source.substring(0, startPos));
}
int matchCount = 0;
for (int i = startPos; i < len; i++) {
sourceChar = source.charAt(i);
if (i > lastMatch) {
sb.append(sourceChar);
} else {
matchCount = 0;
for (int k = 0; k < match0.length; k++) {
if (matchCount == 0 && sourceChar == match0[k]) {
if (match[k].length() + i <= len) {
++matchCount;
int j = 1;
for (; j < match[k].length(); j++) {
if (source.charAt(i + j) != match[k].charAt(j)) {
--matchCount;
break;
}
}
if (matchCount > 0) {
i = i + j - 1;
sb.append(replace);
break;
}
}
}
}
if (matchCount == 0) {
sb.append(sourceChar);
}
}
}
return sb.toString();
}
/**
* This method takes a String as an argument and removes all occurrences of
* the supplied Char. It returns the resulting String.
*/
public static String removeChar(String s, char chr) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c != chr){
sb.append(c);
}
}
return sb.toString();
}
/**
* This method takes a String as an argument and removes all occurrences of
* the supplied Chars. It returns the resulting String.
*/
public static String removeChars(String s, char[] chr) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!charMatch(c, chr)){
sb.append(c);
}
}
return sb.toString();
}
private static boolean charMatch(int iChr, char[] chr) {
for (int i = 0; i < chr.length; i++) {
if (iChr == chr[i]) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,32 @@
/**
* 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.util;
/**
* A general string parsing exception.
*/
public class StringParsingException extends RuntimeException {
static final long serialVersionUID = -3070423471260426402L;
public StringParsingException(String message) {
super(message);
}
};
@@ -0,0 +1,108 @@
/**
* 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.util;
/**
* Builds a string from a stack trace.
* <p>
* Generally used to flatten a stack trace into a single string
* removing \r\n and limiting the size of any given stack.
* </p>
*/
public class ThrowablePrinter {
private static final String atString = " at ";
private String newLineChar = "\\r\\n";
private int maxStackTraceLines = 3;
/**
* Set the maximum number of lines in any one part of
* the stack trace. This is not the total maximum.
*/
public void setMaxStackTraceLines(int maxStackTraceLines) {
this.maxStackTraceLines = maxStackTraceLines;
}
/**
* Set the new line character used to replace \r\n with.
* This is useful so that the stack is placed on a single line
* in a log file.
*/
public void setNewLineChar(String newLineChar) {
this.newLineChar = newLineChar;
}
/**
* Convert the error into a string representation.
* <p>
* Replaces the \r\n and limits the stack lines.
* </p>
*/
public String print(Throwable e) {
StringBuffer sb = new StringBuffer();
printThrowable(sb, e, false);
String line = sb.toString();
line = StringHelper.replaceString(line, "\r", "\\r");
line = StringHelper.replaceString(line, "\n", "\\n");
return line;
}
/**
* Recursively output the Throwable stack trace to the log.
*
* @param sb the buffer to write the stack trace to
* @param e the source throwable
* @param isCause flag to indicate if this is the top level throwable or a
* cause
*/
protected void printThrowable(StringBuffer sb, Throwable e, boolean isCause) {
if (e != null) {
if (isCause) {
sb.append("Caused by: ");
}
sb.append(e.getClass().getName());
sb.append(":");
sb.append(e.getMessage()).append(newLineChar);
StackTraceElement[] ste = e.getStackTrace();
int outputStackLines = ste.length;
int notShownCount = 0;
if (ste.length > maxStackTraceLines) {
outputStackLines = maxStackTraceLines;
notShownCount = ste.length - outputStackLines;
}
for (int i = 0; i < outputStackLines; i++) {
sb.append(atString);
sb.append(ste[i].toString()).append(newLineChar);
}
if (notShownCount > 0) {
sb.append(" ... ");
sb.append(notShownCount);
sb.append(" more").append(newLineChar);
}
Throwable cause = e.getCause();
if (cause != null) {
printThrowable(sb, cause, true);
}
}
}
}
@@ -0,0 +1,186 @@
#
# Used by MimeTypeHelper to find the mime types of based on file extensions.
abs=audio/x-mpeg
ai=application/postscript
aif=audio/x-aiff
aifc=audio/x-aiff
aiff=audio/x-aiff
aim=application/x-aim
art=image/x-jg
asc=text/plain
asf=video/x-ms-asf
asx=video/x-ms-asf
au=audio/basic
avi=video/x-msvideo
avx=video/x-rad-screenplay
bcpio=application/x-bcpio
bin=application/octet-stream
bmp=image/bmp
body=text/html
cdf=application/x-netcdf
cer=application/x-x509-ca-cert
class=application/java
cpio=application/x-cpio
csh=application/x-csh
css=text/css
csv=text/csv
dib=image/bmp
doc=application/msword
dtd=application/xml-dtd
dv=video/x-dv
dvi=application/x-dvi
dms=application/octet-stream
eps=application/postscript
etx=text/x-setext
exe=application/octet-stream
gif=image/gif
gtar=application/x-gtar
gz=application/x-gzip
hdf=application/x-hdf
htc=text/x-component
htm=text/html
html=text/html
hqx=application/mac-binhex40
ico=image/x-icon
ief=image/ief
jad=text/vnd.sun.j2me.app-descriptor
jar=application/java-archive
java=text/plain
jnlp=application/x-java-jnlp-file
jpe=image/jpeg
jpeg=image/jpeg
jpg=image/jpeg
js=text/javascript
jsf=text/plain
jspf=text/plain
kar=audio/midi
latex=application/x-latex
lha=application/octet-stream
lzh=application/octet-stream
m3u=audio/x-mpegurl
mac=image/x-macpaint
man=application/x-troff-man
mathml=application/mathml+xml
me=application/x-troff-me
mid=audio/midi
midi=audio/midi
mif=application/vnd.mif
mov=video/quicktime
movie=video/x-sgi-movie
mp1=audio/x-mpeg
mp2=audio/mpeg
mp3=audio/mpeg
mpa=audio/x-mpeg
mpe=video/mpeg
mpeg=video/mpeg
mpega=audio/x-mpeg
mpga=audio/mpeg
mpg=video/mpeg
mpv2=video/mpeg2
ms=application/x-troff-ms
nc=application/x-netcdf
oda=application/oda
ogg=application/ogg
pbm=image/x-portable-bitmap
pct=image/pict
pdf=application/pdf
pgm=image/x-portable-graymap
pic=image/pict
pict=image/pict
pls=audio/x-scpls
png=image/png
pnm=image/x-portable-anymap
pnt=image/x-macpaint
ppm=image/x-portable-pixmap
pps=application/vnd.ms-powerpoint
ppt=application/vnd.ms-powerpoint
ps=application/postscript
psd=image/x-photoshop
qt=video/quicktime
qti=image/x-quicktime
qtif=image/x-quicktime
ra=audio/x-realaudio
ram=audio/x-pn-realaudio
ras=image/x-cmu-raster
rdf=application/rdf+xml
rgb=image/x-rgb
rpm=audio/x-pn-realaudio-plugin
rm=application/vnd.rn-realmedia
roff=application/x-troff
rtf=text/rtf
rtx=text/richtext
sh=application/x-sh
shar=application/x-shar
shtml=text/x-server-parsed-html
sgml=text/sgml
sgm=text/sgml
smf=audio/x-midi
sit=application/x-stuffit
snd=audio/basic
src=application/x-wais-source
sv4cpio=application/x-sv4cpio
sv4crc=application/x-sv4crc
svg=image/svg+xml
svgz=image/svg
swf=application/x-shockwave-flash
t=application/x-troff
tar=application/x-tar
tcl=application/x-tcl
tex=application/x-tex
texi=application/x-texinfo
texinfo=application/x-texinfo
tif=image/tiff
tiff=image/tiff
tr=application/x-troff
tsv=text/tab-separated-values
txt=text/plain
ulw=audio/basic
ustar=application/x-ustar
vcd=application/x-cdlink
vrml=model/vrml
vsd=application/x-visio
vxml=application/voicexml+xml
wav=audio/x-wav
wbmp=image/vnd.wap.wbmp
wml=text/vnd.wap.wml
wmlc=application/vnd.wap.wmlc
wmls=text/vnd.wap.wmlscript
wmlscriptc=application/vnd.wap.wmlscriptc
wrl=model/vrml
xbm=image/x-xbitmap
xht=application/xhtml+xml
xhtml=application/xhtml+xml
xls=application/vnd.ms-excel
xml=application/xml
xpm=image/x-xpixmap
xsl=application/xml
xslt=application/xslt+xml
xul=application/vnd.mozilla.xul+xml
xwd=image/x-xwindowdump
Z=application/x-compress
z=application/x-compress
zip=application/zip
@@ -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">
General utility objects.
<P>Provides general utility objects.
</P>
</Body>
</HTML>