Change license to Apache2 and reformat

This commit is contained in:
rbygrave committed 2012-09-15 00:00:08 +12:00
1 parent 96ce4c0ddf
commit 7aae897def
560 files changed
+73292 -85907

No files matched your search

@@ -1,164 +1,147 @@
/**
* 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();
}
}
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();
}
}
@@ -1,236 +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;
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();
}
}
}
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();
}
}
}
@@ -1,97 +1,78 @@
/**
* 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();
}
};
}
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();
}
};
}
@@ -1,68 +1,49 @@
/**
* 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;
}
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;
}
}
@@ -1,105 +1,86 @@
/**
* 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();
}
};
}
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();
}
};
}
@@ -1,50 +1,33 @@
/**
* 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();
}
};
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();
}
};
@@ -1,232 +1,215 @@
/**
* 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);
}
}
}
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);
}
}
}
@@ -1,124 +1,107 @@
/**
* 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();
}
}
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();
}
}
@@ -1,88 +1,71 @@
/**
* 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;
}
}
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;
}
}
@@ -1,68 +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.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;
}
}
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;
}
}
@@ -1,51 +1,34 @@
/**
* 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;
}
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;
}
@@ -1,54 +1,37 @@
/**
* 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;
}
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;
}
@@ -1,94 +1,77 @@
/**
* 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();
}
}
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();
}
}
@@ -1,81 +1,64 @@
/**
* 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);
}
}
}
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);
}
}
}
@@ -1,155 +1,136 @@
/**
* 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?");
}
}
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?");
}
}
@@ -1,43 +1,26 @@
/**
* 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);
}
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);
}
@@ -1,41 +1,24 @@
/**
* 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);
}
}
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);
}
}
@@ -1,67 +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.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);
}
}
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);
}
}
@@ -1,250 +1,233 @@
/**
* 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();
}
}
}
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();
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,407 +1,390 @@
/**
* 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);
}
}
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);
}
}
@@ -1,345 +1,328 @@
/**
* 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();
}
}
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();
}
}
@@ -1,157 +1,138 @@
/**
* 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;
}
}
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;
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,115 +1,98 @@
/**
* 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;
}
}
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;
}
}
@@ -1,181 +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.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;
}
}
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;
}
}
@@ -1,125 +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.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);
}
}
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);
}
}
@@ -1,86 +1,69 @@
/**
* 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.");
}
}
}
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.");
}
}
}
@@ -1,276 +1,259 @@
/**
* 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;
}
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;
}
@@ -1,489 +1,472 @@
/**
* 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;
}
}
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;
}
}
@@ -1,194 +1,177 @@
/**
* 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;
}
};
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;
}
};
@@ -1,113 +1,96 @@
/**
* 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;
};
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;
};
@@ -1,40 +1,23 @@
/**
* 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);
}
}
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);
}
}
@@ -1,345 +1,328 @@
/**
* 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();
}
}
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();
}
}
@@ -1,219 +1,202 @@
/**
* 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);
}
}
}
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);
}
}
}
@@ -1,87 +1,70 @@
/**
* 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);
}
}
}
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);
}
}
}
@@ -1,39 +1,22 @@
/**
* 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);
}
}
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);
}
}
@@ -1,40 +1,23 @@
/**
* 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);
}
}
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);
}
}
@@ -1,62 +1,45 @@
/**
* 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();
}
}
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();
}
}
@@ -1,66 +1,49 @@
/**
* 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;
}
}
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;
}
}
@@ -1,30 +1,13 @@
/**
* 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);
}
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);
}
@@ -1,176 +1,159 @@
/**
* 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();
}
}
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();
}
}
@@ -1,231 +1,214 @@
/**
* 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";
}
}
}
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";
}
}
}
@@ -1,80 +1,63 @@
/**
* 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;
}
}
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;
}
}
@@ -1,57 +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;
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");
};
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");
};
@@ -1,40 +1,23 @@
/**
* 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);
}
}
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);
}
}
File diff suppressed because it is too large. Load diff
@@ -1,32 +1,15 @@
/**
* 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);
}
};
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);
}
};
@@ -1,108 +1,91 @@
/**
* 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);
}
}
}
}
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);
}
}
}
}