From 5b6b49fbe01397461e67238481c84a62c8ed4bef Mon Sep 17 00:00:00 2001 From: Erik Brakkee Date: Thu, 16 Mar 2006 18:53:49 +0000 Subject: [PATCH] --- .../src/org/wamblee/cache/CachedObject.java | 132 ++++--- support/src/org/wamblee/cache/EhCache.java | 31 +- .../src/org/wamblee/cache/ForeverCache.java | 50 +-- support/src/org/wamblee/concurrency/Lock.java | 2 +- .../src/org/wamblee/conditions/Condition.java | 8 +- .../org/wamblee/conditions/OrCondition.java | 43 ++- .../src/org/wamblee/general/BeanFactory.java | 2 +- .../wamblee/general/BeanFactoryException.java | 13 +- .../src/org/wamblee/general/BeanKernel.java | 10 +- support/src/org/wamblee/general/Pair.java | 81 +++-- .../wamblee/general/SpringBeanFactory.java | 4 + .../src/org/wamblee/io/ClassPathResource.java | 33 +- support/src/org/wamblee/io/FileResource.java | 18 +- support/src/org/wamblee/io/InputResource.java | 12 +- .../src/org/wamblee/io/StreamResource.java | 15 +- .../observer/DefaultObserverNotifier.java | 30 +- .../src/org/wamblee/observer/Observable.java | 126 ++++--- .../src/org/wamblee/observer/Observer.java | 4 +- .../org/wamblee/persistence/Persistent.java | 8 +- .../hibernate/HibernateSupport.java | 211 ++++++----- support/src/org/wamblee/xml/XSLT.java | 87 +++-- .../concurrency/ReadWriteLockTest.java | 110 +++--- .../org/wamblee/observer/ObservableTest.java | 104 +++--- .../org/wamblee/test/HibernateExporter.java | 16 +- .../org/wamblee/test/HibernateUpdater.java | 28 +- .../test/org/wamblee/test/HibernateUtils.java | 73 ++-- .../test/org/wamblee/test/SpringTestCase.java | 97 ++--- .../test/org/wamblee/test/TestSupport.java | 342 +++++++++--------- .../wamblee/test/TestTransactionCallback.java | 15 +- .../TestTransactionCallbackWithoutResult.java | 10 +- 30 files changed, 990 insertions(+), 725 deletions(-) diff --git a/support/src/org/wamblee/cache/CachedObject.java b/support/src/org/wamblee/cache/CachedObject.java index 8a4772f8..787bc870 100644 --- a/support/src/org/wamblee/cache/CachedObject.java +++ b/support/src/org/wamblee/cache/CachedObject.java @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.cache; @@ -21,91 +21,109 @@ import java.io.Serializable; import org.apache.log4j.Logger; /** - * Represents a cached object. The object is either retrieved from the cache if the cache - * has it, or a call back is invoked to get the object (and put it in the cache). + * Represents a cached object. The object is either retrieved from the cache if + * the cache has it, or a call back is invoked to get the object (and put it in + * the cache). */ public class CachedObject { - + private static final Logger LOGGER = Logger.getLogger(CachedObject.class); - + /** - * Callback invoked to compute an object if it was not found in the cache. - * @param Type of the object + * Callback invoked to compute an object if it was not found in the cache. + * + * @param + * Type of the object */ public static interface Computation { /** - * Gets the object. Called when the object is not in the cache. - * @param aObjectKey Id of the object in the cache. - * @return Object, must be non-null. + * Gets the object. Called when the object is not in the cache. + * + * @param aObjectKey + * Id of the object in the cache. + * @return Object, must be non-null. */ - Value getObject(Key aObjectKey); + Value getObject(Key aObjectKey); } - + /** - * Cache to use. + * Cache to use. */ private Cache _cache; - + /** - * Key of the object in the cache. + * Key of the object in the cache. */ - private KeyType _objectKey; - + private KeyType _objectKey; + /** - * Computation used to obtain the object if it is not found in the cache. + * Computation used to obtain the object if it is not found in the cache. */ - private Computation _computation; - + private Computation _computation; + /** - * Constructs the cached object. - * @param aCache Cache to use. - * @param aObjectKey Key of the object in the cache. - * @param aComputation Computation to get the object in case the object is not in the cache. + * Constructs the cached object. + * + * @param aCache + * Cache to use. + * @param aObjectKey + * Key of the object in the cache. + * @param aComputation + * Computation to get the object in case the object is not in the + * cache. */ - public CachedObject(Cache aCache, KeyType aObjectKey, Computation aComputation) { - _cache = aCache; - _objectKey = aObjectKey; - _computation = aComputation; + public CachedObject(Cache aCache, KeyType aObjectKey, + Computation aComputation) { + _cache = aCache; + _objectKey = aObjectKey; + _computation = aComputation; } - + /** - * Gets the object. Since the object is cached, different calls to this method may return - * different objects. - * @return Object. + * Gets the object. Since the object is cached, different calls to this + * method may return different objects. + * + * @return Object. */ - public ValueType get() { - ValueType object = (ValueType)_cache.get(_objectKey); // the used cache is thread safe. - if ( object == null ) { - // synchronize the computation to make sure that the object is only computed - // once when multiple concurrent threads detect that the entry must be - // recomputed. - synchronized (this) { - object = (ValueType)_cache.get(_objectKey); - if ( object == null ) { - // No other thread did a recomputation so we must do this now. - LOGGER.debug("Refreshing cache for '" + _objectKey + "'"); - object = _computation.getObject(_objectKey); - _cache.put(_objectKey, object); - } + public ValueType get() { + ValueType object = (ValueType) _cache.get(_objectKey); // the used + // cache is + // thread safe. + if (object == null) { + // synchronize the computation to make sure that the object is only + // computed + // once when multiple concurrent threads detect that the entry must + // be + // recomputed. + synchronized (this) { + object = (ValueType) _cache.get(_objectKey); + if (object == null) { + // No other thread did a recomputation so we must do this + // now. + LOGGER.debug("Refreshing cache for '" + _objectKey + "'"); + object = _computation.getObject(_objectKey); + _cache.put(_objectKey, object); + } } } - return object; + return object; } - + /** - * Invalidates the cache for the object so that it is recomputed the next - * time it is requested. - * + * Invalidates the cache for the object so that it is recomputed the next + * time it is requested. + * */ - public void invalidate() { + public void invalidate() { _cache.remove(_objectKey); } - + /** - * Gets the cache. - * @return Cache. + * Gets the cache. + * + * @return Cache. */ - public Cache getCache() { - return _cache; + public Cache getCache() { + return _cache; } } diff --git a/support/src/org/wamblee/cache/EhCache.java b/support/src/org/wamblee/cache/EhCache.java index 4f56cd3a..b870f325 100644 --- a/support/src/org/wamblee/cache/EhCache.java +++ b/support/src/org/wamblee/cache/EhCache.java @@ -35,23 +35,25 @@ public class EhCache { private static final Logger LOGGER = Logger.getLogger(EhCache.class); - + /** - * EH Cache manager. + * EH Cache manager. */ private CacheManager _manager; /** - * EH cache. + * EH cache. */ private Cache _cache; /** - * Constructs a cache based on EHCache. - * @param aResource Resource containing the configuration file for - * EHCache. - * @param aCacheName Name of the cache to use. If a cache with this name does - * not exist, one is created based on default settings. + * Constructs a cache based on EHCache. + * + * @param aResource + * Resource containing the configuration file for EHCache. + * @param aCacheName + * Name of the cache to use. If a cache with this name does not + * exist, one is created based on default settings. * @throws IOException * @throws CacheException */ @@ -62,11 +64,12 @@ public class EhCache - implements Cache { +public class ForeverCache + implements Cache { /** - * Cached entries. + * Cached entries. */ - private HashMap _map; - + private HashMap _map; + /** - * Constructs the cache. - * + * Constructs the cache. + * */ - public ForeverCache() { - _map = new HashMap(); + public ForeverCache() { + _map = new HashMap(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.wamblee.cache.Cache#put(KeyType, ValueType) */ public synchronized void put(KeyType aKey, ValueType aValue) { - _map.put(aKey, aValue); + _map.put(aKey, aValue); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.wamblee.cache.Cache#get(KeyType) */ public synchronized ValueType get(KeyType aKey) { return _map.get(aKey); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.wamblee.cache.Cache#remove(KeyType) */ public synchronized void remove(KeyType aKey) { _map.remove(aKey); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.wamblee.cache.Cache#clear() */ public synchronized void clear() { diff --git a/support/src/org/wamblee/concurrency/Lock.java b/support/src/org/wamblee/concurrency/Lock.java index a30c45ee..6c6cb126 100644 --- a/support/src/org/wamblee/concurrency/Lock.java +++ b/support/src/org/wamblee/concurrency/Lock.java @@ -32,4 +32,4 @@ public interface Lock { * Releases the lock. */ void release(); -} \ No newline at end of file +} diff --git a/support/src/org/wamblee/conditions/Condition.java b/support/src/org/wamblee/conditions/Condition.java index 98da09ee..b9f8d77c 100644 --- a/support/src/org/wamblee/conditions/Condition.java +++ b/support/src/org/wamblee/conditions/Condition.java @@ -18,14 +18,14 @@ package org.wamblee.conditions; /** - * Determines if an object matches. + * Determines if an object matches a certain condition. */ public interface Condition { /** - * Determines if a program matches. - * @param aProgram Program to match. - * @return True iff the program matches. + * Determines if an object matches a condition. + * @param aObject object to match. + * @return True iff the object matches. */ boolean matches(T aObject); } diff --git a/support/src/org/wamblee/conditions/OrCondition.java b/support/src/org/wamblee/conditions/OrCondition.java index 14bd24ad..2997a4a6 100644 --- a/support/src/org/wamblee/conditions/OrCondition.java +++ b/support/src/org/wamblee/conditions/OrCondition.java @@ -12,41 +12,56 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.conditions; import java.util.ArrayList; import java.util.List; - /** - * + * Represents a logical or of different boolean conditions. */ public class OrCondition implements Condition { - + private List> _conditions; - + + /** + * Constructs the condition. + * + * @param aCondition1 + * First condition. + * @param aCondition2 + * Second condition. + */ public OrCondition(Condition aCondition1, Condition aCondition2) { _conditions = new ArrayList>(); - _conditions.add(aCondition1); + _conditions.add(aCondition1); _conditions.add(aCondition2); } - - public OrCondition(List> aConditions) { - _conditions = aConditions; + + /** + * Constructs the or condition. + * + * @param aConditions + * List of conditions to use in the logical or. + */ + public OrCondition(List> aConditions) { + _conditions = aConditions; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program) */ public boolean matches(T aObject) { - for (Condition condition: _conditions) { - if ( condition.matches(aObject)) { - return true; + for (Condition condition : _conditions) { + if (condition.matches(aObject)) { + return true; } } - return false; + return false; } } diff --git a/support/src/org/wamblee/general/BeanFactory.java b/support/src/org/wamblee/general/BeanFactory.java index 53f006f6..f93e1fef 100644 --- a/support/src/org/wamblee/general/BeanFactory.java +++ b/support/src/org/wamblee/general/BeanFactory.java @@ -34,7 +34,7 @@ public interface BeanFactory { * class for retrieving an implementation of that class. This * means that the bean implementing the class is configured in the bean factory * with id equal to the class name of the interface. - * @param aClass + * @param aClass Class of the object to find. * @return Object (always non-null). * @throws BeanFactoryException In case the object could not be found. */ diff --git a/support/src/org/wamblee/general/BeanFactoryException.java b/support/src/org/wamblee/general/BeanFactoryException.java index 5eb7b48e..9f60d21b 100644 --- a/support/src/org/wamblee/general/BeanFactoryException.java +++ b/support/src/org/wamblee/general/BeanFactoryException.java @@ -21,15 +21,20 @@ package org.wamblee.general; public class BeanFactoryException extends RuntimeException { static final long serialVersionUID = -1215992188624874902L; + /** + * Constructs the exception. + * @param aMsg Message. + */ public BeanFactoryException(String aMsg) { super(aMsg); } + /** + * Constructs the exception. + * @param aMsg Message. + * @param aThrowable Cause of the exception. + */ public BeanFactoryException(String aMsg, Throwable aThrowable) { super(aMsg, aThrowable); } - - public static T bla(Class ddk) { - return null; - } } diff --git a/support/src/org/wamblee/general/BeanKernel.java b/support/src/org/wamblee/general/BeanKernel.java index fa48fb97..d140de3d 100644 --- a/support/src/org/wamblee/general/BeanKernel.java +++ b/support/src/org/wamblee/general/BeanKernel.java @@ -27,7 +27,7 @@ import org.wamblee.io.InputResource; /** * The standard means to obtain the bean factory. */ -public class BeanKernel { +public final class BeanKernel { private static final Log LOG = LogFactory.getLog(BeanKernel.class); @@ -46,6 +46,14 @@ public class BeanKernel { * Cached bean factory. */ private static BeanFactory BEAN_FACTORY; + + /** + * Disabled constructor. + * + */ + private BeanKernel() { + // Empty + } /** * Overrides the default mechanism for looking up the bean factory by diff --git a/support/src/org/wamblee/general/Pair.java b/support/src/org/wamblee/general/Pair.java index f7a3d972..fd8d494d 100644 --- a/support/src/org/wamblee/general/Pair.java +++ b/support/src/org/wamblee/general/Pair.java @@ -12,37 +12,64 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.general; /** - * Represents a pair of objects. This is inspired on the C++ Standard Template Library - * pair template. + * Represents a pair of objects. This is inspired on the C++ Standard Template + * Library pair template. * - * @param Type of the first object. - * @param Type of the second object. + * @param + * Type of the first object. + * @param + * Type of the second object. */ -public class Pair { - - private T _t; - private U _u; - - public Pair(T t, U u ) { - _t = t; - _u = u; - } - - public Pair(Pair p) { - _t = p._t; - _u = p._u; - } - - public T getFirst() { - return _t; - } - - public U getSecond() { - return _u; - } +public class Pair { + + private T _t; + + private U _u; + + /** + * Constructs the pair. + * + * @param aT + * First object. + * @param aU + * Second object. + */ + public Pair(T aT, U aU) { + _t = aT; + _u = aU; + } + + /** + * Copies a pair. + * + * @param aPair + * Pair to copy. + */ + public Pair(Pair aPair) { + _t = aPair._t; + _u = aPair._u; + } + + /** + * Gets the first object of the pair. + * + * @return First object. + */ + public T getFirst() { + return _t; + } + + /** + * Gets the second object of the pair. + * + * @return Second object. + */ + public U getSecond() { + return _u; + } } diff --git a/support/src/org/wamblee/general/SpringBeanFactory.java b/support/src/org/wamblee/general/SpringBeanFactory.java index 05a421e8..eda62110 100644 --- a/support/src/org/wamblee/general/SpringBeanFactory.java +++ b/support/src/org/wamblee/general/SpringBeanFactory.java @@ -27,6 +27,10 @@ public class SpringBeanFactory implements BeanFactory { private String _factoryName; + /** + * Constructs the bean factory. + * @param aFactoryName Spring bean factory to use. + */ public SpringBeanFactory(String aFactoryName) { _factoryName = aFactoryName; } diff --git a/support/src/org/wamblee/io/ClassPathResource.java b/support/src/org/wamblee/io/ClassPathResource.java index 23c89417..32014a10 100644 --- a/support/src/org/wamblee/io/ClassPathResource.java +++ b/support/src/org/wamblee/io/ClassPathResource.java @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.io; import java.io.IOException; @@ -29,28 +29,35 @@ public class ClassPathResource implements InputResource { /** * Construct the class path resource. - * @param aResource Resource + * + * @param aResource + * Resource */ - public ClassPathResource( String aResource ) { + public ClassPathResource(String aResource) { _resource = aResource; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.wamblee.io.InputResource#getInputStream() */ - public InputStream getInputStream( ) throws IOException { - InputStream stream = Thread.currentThread( ).getContextClassLoader( ) - .getResourceAsStream( _resource ); - if ( stream == null ) { - throw new IOException("Class path resource '" + _resource + "' not found."); + public InputStream getInputStream() throws IOException { + InputStream stream = Thread.currentThread().getContextClassLoader() + .getResourceAsStream(_resource); + if (stream == null) { + throw new IOException("Class path resource '" + _resource + + "' not found."); } - return stream; + return stream; } - - /** (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ - public String toString( ) { + public String toString() { return "ClassPathResource(" + _resource + ")"; } } diff --git a/support/src/org/wamblee/io/FileResource.java b/support/src/org/wamblee/io/FileResource.java index 63ac27e6..ee43f72f 100644 --- a/support/src/org/wamblee/io/FileResource.java +++ b/support/src/org/wamblee/io/FileResource.java @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.io; import java.io.BufferedInputStream; @@ -21,8 +21,6 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; - - /** * Resource implemention for reading from a file. */ @@ -34,16 +32,20 @@ public class FileResource implements InputResource { /** * Constructs the resource. - * @param aFile File to read. + * + * @param aFile + * File to read. */ - public FileResource( File aFile ) { + public FileResource(File aFile) { _file = aFile; } - /** (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.wamblee.io.InputResource#getInputStream() */ - public InputStream getInputStream( ) throws IOException { - return new BufferedInputStream( new FileInputStream( _file ) ); + public InputStream getInputStream() throws IOException { + return new BufferedInputStream(new FileInputStream(_file)); } } diff --git a/support/src/org/wamblee/io/InputResource.java b/support/src/org/wamblee/io/InputResource.java index aa4fb91c..f5e84965 100644 --- a/support/src/org/wamblee/io/InputResource.java +++ b/support/src/org/wamblee/io/InputResource.java @@ -12,23 +12,23 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.io; import java.io.IOException; import java.io.InputStream; - /** * Represents a resource from which information can be read. */ public interface InputResource { /** - * Gets the input stream to the resource. The obtained input stream - * must be closed once reading has finished. + * Gets the input stream to the resource. The obtained input stream must be + * closed once reading has finished. * * @return Input stream to the resource, never null. - * @throws IOException in case the resource cannot be found. + * @throws IOException + * in case the resource cannot be found. */ - InputStream getInputStream( ) throws IOException; + InputStream getInputStream() throws IOException; } diff --git a/support/src/org/wamblee/io/StreamResource.java b/support/src/org/wamblee/io/StreamResource.java index e2feb534..11f815c4 100644 --- a/support/src/org/wamblee/io/StreamResource.java +++ b/support/src/org/wamblee/io/StreamResource.java @@ -12,13 +12,12 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.io; import java.io.IOException; import java.io.InputStream; - /** * Input resource based on an input stream. */ @@ -30,16 +29,20 @@ public class StreamResource implements InputResource { /** * Constructs a resource. - * @param aStream Input stream to read. + * + * @param aStream + * Input stream to read. */ - public StreamResource( InputStream aStream ) { + public StreamResource(InputStream aStream) { _stream = aStream; } - /** (non-Javadoc) + /* + * (non-Javadoc) + * * @see InputResource#getInputStream() */ - public InputStream getInputStream( ) throws IOException { + public InputStream getInputStream() throws IOException { return _stream; } } diff --git a/support/src/org/wamblee/observer/DefaultObserverNotifier.java b/support/src/org/wamblee/observer/DefaultObserverNotifier.java index fbc39709..2e028ea7 100644 --- a/support/src/org/wamblee/observer/DefaultObserverNotifier.java +++ b/support/src/org/wamblee/observer/DefaultObserverNotifier.java @@ -12,28 +12,34 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.observer; /** - * Default observer notifier which calls {@link org.wamblee.observer.Observer#send(ObservableType, Event)} - * immediately. + * Default observer notifier which calls + * {@link org.wamblee.observer.Observer#send(ObservableType, Event)} + * immediately. */ -public class DefaultObserverNotifier implements ObserverNotifier{ +public class DefaultObserverNotifier implements + ObserverNotifier { /** - * Constructs the notifier. - * + * Constructs the notifier. + * */ - public DefaultObserverNotifier() { + public DefaultObserverNotifier() { // Empty } - - /* (non-Javadoc) - * @see org.wamblee.observer.ObserverNotifier#update(org.wamblee.observer.Observer, ObservableType, Event) + + /* + * (non-Javadoc) + * + * @see org.wamblee.observer.ObserverNotifier#update(org.wamblee.observer.Observer, + * ObservableType, Event) */ - public void update(Observer aObserver, ObservableType aObservable, Event aEvent) { - aObserver.send(aObservable, aEvent); + public void update(Observer aObserver, + ObservableType aObservable, Event aEvent) { + aObserver.send(aObservable, aEvent); } } diff --git a/support/src/org/wamblee/observer/Observable.java b/support/src/org/wamblee/observer/Observable.java index 7af7ea7d..2980afaf 100644 --- a/support/src/org/wamblee/observer/Observable.java +++ b/support/src/org/wamblee/observer/Observable.java @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.observer; @@ -23,105 +23,123 @@ import java.util.TreeMap; import org.apache.log4j.Logger; - /** - * Implements subscription and notification logic for an observer pattern. - * This class is thread safe. + * Implements subscription and notification logic for an observer pattern. This + * class is thread safe. */ public class Observable { - + private static final Logger LOGGER = Logger.getLogger(Observable.class); - + /** - * Observable. + * Observable. */ private ObservableType _observable; - + /** - * Used to notify observers. + * Used to notify observers. */ - private ObserverNotifier _notifier; - + private ObserverNotifier _notifier; + /** - * Map of subscription to observer. + * Map of subscription to observer. */ - private Map> _observers; - + private Map> _observers; + /** - * Counter for subscriptions. Holds the next subscription. + * Counter for subscriptions. Holds the next subscription. */ - private long _counter; - + private long _counter; + /** - * Constructs the observable. - * @param aObservable Observable this instance is used for. - * @param aNotifier Object used for implementing notification of listeners. + * Constructs the observable. + * + * @param aObservable + * Observable this instance is used for. + * @param aNotifier + * Object used for implementing notification of listeners. */ - public Observable(ObservableType aObservable, ObserverNotifier aNotifier) { + public Observable(ObservableType aObservable, + ObserverNotifier aNotifier) { _observable = aObservable; - _notifier = aNotifier; + _notifier = aNotifier; _observers = new TreeMap>(); - _counter = 0; + _counter = 0; } - + /** - * Subscribe an obvers. - * @param aObserver Observer to subscribe. - * @return Event Event to send. + * Subscribe an obvers. + * + * @param aObserver + * Observer to subscribe. + * @return Event Event to send. */ public synchronized long subscribe(Observer aObserver) { - long subscription = _counter++; // integer rage is so large it will never roll over. + long subscription = _counter++; // integer rage is so large it will + // never roll over. _observers.put(subscription, aObserver); - return subscription; + return subscription; } - + /** - * Unsubscribe an observer. - * @param aSubscription Subscription which is used - * @throws IllegalArgumentException In case the subscription is not known. + * Unsubscribe an observer. + * + * @param aSubscription + * Subscription which is used + * @throws IllegalArgumentException + * In case the subscription is not known. */ public synchronized void unsubscribe(long aSubscription) { Object obj = _observers.remove(aSubscription); - if ( obj == null ) { - throw new IllegalArgumentException("Subscription '" + aSubscription + "'"); + if (obj == null) { + throw new IllegalArgumentException("Subscription '" + aSubscription + + "'"); } } - + /** - * Gets the number of subscribed observers. + * Gets the number of subscribed observers. + * + * @return Number of subscribed observers. */ - public int getObserverCount() { - return _observers.size(); + public int getObserverCount() { + return _observers.size(); } - + /** - * Notifies all subscribed observers. - * @param aEvent Event to send. + * Notifies all subscribed observers. + * + * @param aEvent + * Event to send. */ public void send(Event aEvent) { - // Make sure we do the notification while not holding the lock to avoid potential deadlock - // situations. - List> observers = new ArrayList>(); - synchronized (this) { + // Make sure we do the notification while not holding the lock to avoid + // potential deadlock + // situations. + List> observers = new ArrayList>(); + synchronized (this) { observers.addAll(_observers.values()); } - for (Observer observer: observers) { - _notifier.update(observer, _observable, aEvent); + for (Observer observer : observers) { + _notifier.update(observer, _observable, aEvent); } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.lang.Object#finalize() */ @Override protected void finalize() throws Throwable { - if ( _observers.size() > 0 ) { - LOGGER.error("Still observers registered at finalization of observer!"); - for (Observer observer: _observers.values()) { + if (_observers.size() > 0) { + LOGGER + .error("Still observers registered at finalization of observer!"); + for (Observer observer : _observers.values()) { LOGGER.error(" observer: " + observer); } } - + super.finalize(); } diff --git a/support/src/org/wamblee/observer/Observer.java b/support/src/org/wamblee/observer/Observer.java index 9150ddb0..3f74773c 100644 --- a/support/src/org/wamblee/observer/Observer.java +++ b/support/src/org/wamblee/observer/Observer.java @@ -19,11 +19,11 @@ package org.wamblee.observer; /** * This is a type-safe version of {@link java.util.Observable}. */ -public interface Observer { +public interface Observer { /** * Called when an event has occurred on the observable. - * @param aObservabdle Observable. + * @param aObservable Observable. * @param aEvent Event. */ void send(ObservableType aObservable, Event aEvent); diff --git a/support/src/org/wamblee/persistence/Persistent.java b/support/src/org/wamblee/persistence/Persistent.java index cd56ca4c..57faf95e 100644 --- a/support/src/org/wamblee/persistence/Persistent.java +++ b/support/src/org/wamblee/persistence/Persistent.java @@ -30,25 +30,29 @@ public interface Persistent { /** * Gets the primary key. - * @return Primary key. + * @return Primary key. + * @see #setPrimaryKey(Serializable) */ Serializable getPrimaryKey(); /** * Sets the primary key. - * @param aKey Primary key. + * @param aKey Primary key. + * @see #getPrimaryKey() */ void setPrimaryKey(Serializable aKey); /** * Gets the version. * @return Version. + * @see #setPersistedVersion(int) */ int getPersistedVersion(); /** * Sets the version. * @param aVersion Version. + * @see #getPersistedVersion() */ void setPersistedVersion(int aVersion); } diff --git a/support/src/org/wamblee/persistence/hibernate/HibernateSupport.java b/support/src/org/wamblee/persistence/hibernate/HibernateSupport.java index 29debe78..65160dd1 100644 --- a/support/src/org/wamblee/persistence/hibernate/HibernateSupport.java +++ b/support/src/org/wamblee/persistence/hibernate/HibernateSupport.java @@ -34,27 +34,30 @@ import org.wamblee.persistence.Persistent; * {@link org.springframework.orm.hibernate.support.HibernateDaoSupport}. */ public class HibernateSupport extends HibernateDaoSupport { - + private static final Log LOG = LogFactory.getLog(HibernateSupport.class); - + /** - * This class provided an equality operation based on the object reference of the - * wrapped object. This is required because we cannto assume that the equals operation - * has any meaning for different types of persistent objects. This allows us to use - * the standard collection classes for detecting cyclic dependences and avoiding - * recursion. - * + * This class provided an equality operation based on the object reference + * of the wrapped object. This is required because we cannto assume that the + * equals operation has any meaning for different types of persistent + * objects. This allows us to use the standard collection classes for + * detecting cyclic dependences and avoiding recursion. + * */ private static final class ObjectElem { private Object _object; + public ObjectElem(Object aObject) { - _object = aObject; + _object = aObject; } - public boolean equals(Object obj) { - return ((ObjectElem)obj)._object == _object; + + public boolean equals(Object aObj) { + return ((ObjectElem) aObj)._object == _object; } + public int hashCode() { - return _object.hashCode(); + return _object.hashCode(); } } @@ -72,60 +75,67 @@ public class HibernateSupport extends HibernateDaoSupport { * the hibernate merge operation because hibernate itself leaves the object * passed to merge untouched. * - * Use this method with extreme caution since it will recursively load all - * objects that the current object has relations with and for which cascade="merge" - * was specified in the Hibernate mapping file. + * Use this method with extreme caution since it will recursively load all + * objects that the current object has relations with and for which + * cascade="merge" was specified in the Hibernate mapping file. * - * @param aPersistent Object to merge. + * @param aPersistent + * Object to merge. */ public void merge(Persistent aPersistent) { merge(getHibernateTemplate(), aPersistent); } - + /** - * As {@link #merge(Persistent)} but with a given template. - * This method can be accessed in a static way. - * @param aTemplate Hibernate template - * @param aPersistent Object to merge. + * As {@link #merge(Persistent)} but with a given template. This method can + * be accessed in a static way. + * + * @param aTemplate + * Hibernate template + * @param aPersistent + * Object to merge. */ public static void merge(HibernateTemplate aTemplate, Persistent aPersistent) { - Persistent merged = (Persistent) aTemplate.merge( - aPersistent); + Persistent merged = (Persistent) aTemplate.merge(aPersistent); processPersistent(aPersistent, merged, new ArrayList()); } - - /** - * Copies primary keys and version from the result of the merged to the + * Copies primary keys and version from the result of the merged to the * object that was passed to the merge operation. It does this by traversing - * the properties of the object. It copies the primary key and version for + * the properties of the object. It copies the primary key and version for * objects that implement {@link Persistent} and applies the same rules to - * objects in maps and sets as well (i.e. recursively). - * @param aPersistent Object whose primary key and version are to be set. - * @param aMerged Object that was the result of the merge. - * @param aProcessed List of already processed Persistent objects of the persistent part. + * objects in maps and sets as well (i.e. recursively). + * + * @param aPersistent + * Object whose primary key and version are to be set. + * @param aMerged + * Object that was the result of the merge. + * @param aProcessed + * List of already processed Persistent objects of the persistent + * part. */ public static void processPersistent(Persistent aPersistent, Persistent aMerged, List aProcessed) { - if ( aPersistent == null && aMerged == null ) { - return; + if (aPersistent == null && aMerged == null) { + return; } - if ( aPersistent == null || aMerged == null ) { - throw new RuntimeException("persistent or merged object is null '" + aPersistent + "'" + - " '" + aMerged + "'"); + if (aPersistent == null || aMerged == null) { + throw new RuntimeException("persistent or merged object is null '" + + aPersistent + "'" + " '" + aMerged + "'"); } - ObjectElem elem = new ObjectElem(aPersistent); - if ( aProcessed.contains(elem)) { - return; // already processed. + ObjectElem elem = new ObjectElem(aPersistent); + if (aProcessed.contains(elem)) { + return; // already processed. } aProcessed.add(elem); - + LOG.info("Setting pk/version on " + aPersistent + " from " + aMerged); - - if ( aPersistent.getPrimaryKey() != null && - !aMerged.getPrimaryKey().equals(aPersistent.getPrimaryKey()) ) { - LOG.error("Mismatch between primary key values: " + aPersistent + " " + aMerged); + + if (aPersistent.getPrimaryKey() != null + && !aMerged.getPrimaryKey().equals(aPersistent.getPrimaryKey())) { + LOG.error("Mismatch between primary key values: " + aPersistent + + " " + aMerged); } else { aPersistent.setPersistedVersion(aMerged.getPersistedVersion()); aPersistent.setPrimaryKey(aMerged.getPrimaryKey()); @@ -141,24 +151,29 @@ public class HibernateSupport extends HibernateDaoSupport { Set merged = (Set) getter.invoke(aMerged); Set persistent = (Set) getter.invoke(aPersistent); processSet(persistent, merged, aProcessed); - } else if ( List.class.isAssignableFrom(returnType)) { + } else if (List.class.isAssignableFrom(returnType)) { List merged = (List) getter.invoke(aMerged); List persistent = (List) getter.invoke(aPersistent); processList(persistent, merged, aProcessed); - } else if ( Map.class.isAssignableFrom(returnType)) { + } else if (Map.class.isAssignableFrom(returnType)) { Map merged = (Map) getter.invoke(aMerged); Map persistent = (Map) getter.invoke(aPersistent); processMap(persistent, merged, aProcessed); - } else if ( Persistent.class.isAssignableFrom(returnType)) { - Persistent merged = (Persistent) getter.invoke(aMerged); - Persistent persistent = (Persistent) getter.invoke(aPersistent); + } else if (Persistent.class.isAssignableFrom(returnType)) { + Persistent merged = (Persistent) getter.invoke(aMerged); + Persistent persistent = (Persistent) getter + .invoke(aPersistent); processPersistent(persistent, merged, aProcessed); - } else if ( returnType.isArray() && - Persistent.class.isAssignableFrom(returnType.getComponentType())) { - Persistent[] merged = (Persistent[]) getter.invoke(aMerged); - Persistent[] persistent = (Persistent[]) getter.invoke(aPersistent); - for (int i = 0; i < persistent.length; i++) { - processPersistent(persistent[i], merged[i], aProcessed); + } else if (returnType.isArray() + && Persistent.class.isAssignableFrom(returnType + .getComponentType())) { + Persistent[] merged = (Persistent[]) getter + .invoke(aMerged); + Persistent[] persistent = (Persistent[]) getter + .invoke(aPersistent); + for (int i = 0; i < persistent.length; i++) { + processPersistent(persistent[i], merged[i], + aProcessed); } } } catch (InvocationTargetException e) { @@ -172,12 +187,17 @@ public class HibernateSupport extends HibernateDaoSupport { } /** - * Process the persistent objects in the collections. - * @param aPersistent Collection in the original object. - * @param aMerged Collection as a result of the merge. - * @param aProcessed List of processed persistent objects. + * Process the persistent objects in the collections. + * + * @param aPersistent + * Collection in the original object. + * @param aMerged + * Collection as a result of the merge. + * @param aProcessed + * List of processed persistent objects. */ - public static void processList(List aPersistent, List aMerged, List aProcessed) { + public static void processList(List aPersistent, List aMerged, + List aProcessed) { Object[] merged = aMerged.toArray(); Object[] persistent = aPersistent.toArray(); if (merged.length != persistent.length) { @@ -187,55 +207,70 @@ public class HibernateSupport extends HibernateDaoSupport { for (int i = 0; i < merged.length; i++) { assert merged[i].equals(persistent[i]); if (merged[i] instanceof Persistent) { - processPersistent((Persistent)persistent[i], (Persistent)merged[i], aProcessed); + processPersistent((Persistent) persistent[i], + (Persistent) merged[i], aProcessed); } } } - + /** - * Process the persistent objects in sets. - * @param aPersistent Collection in the original object. - * @param aMerged Collection as a result of the merge. - * @param aProcessed List of processed persistent objects. + * Process the persistent objects in sets. + * + * @param aPersistent + * Collection in the original object. + * @param aMerged + * Collection as a result of the merge. + * @param aProcessed + * List of processed persistent objects. */ - public static void processSet(Set aPersistent, Set aMerged, List aProcessed) { + public static void processSet(Set aPersistent, Set aMerged, + List aProcessed) { if (aMerged.size() != aPersistent.size()) { throw new RuntimeException("Array sizes differ " + aMerged.size() + " " + aPersistent.size()); } - for (Object merged: aMerged) { + for (Object merged : aMerged) { // Find the object that equals the merged[i] - for (Object persistent: aPersistent) { - if ( persistent.equals(merged)) { - processPersistent((Persistent)persistent, (Persistent)merged, aProcessed); + for (Object persistent : aPersistent) { + if (persistent.equals(merged)) { + processPersistent((Persistent) persistent, + (Persistent) merged, aProcessed); break; } } } } - + /** - * Process the Map objects in the collections. - * @param aPersistent Collection in the original object. - * @param aMerged Collection as a result of the merge. - * @param aProcessed List of processed persistent objects. + * Process the Map objects in the collections. + * + * @param aPersistent + * Collection in the original object. + * @param aMerged + * Collection as a result of the merge. + * @param aProcessed + * List of processed persistent objects. */ - public static void processMap(Map aPersistent, Map aMerged, List aProcessed) { - if ( aMerged.size() != aPersistent.size() ) { - throw new RuntimeException("Sizes differ " + aMerged.size() + " " + aPersistent.size()); + public static void processMap(Map aPersistent, Map aMerged, + List aProcessed) { + if (aMerged.size() != aPersistent.size()) { + throw new RuntimeException("Sizes differ " + aMerged.size() + " " + + aPersistent.size()); } Set keys = aMerged.keySet(); - for (Object key: keys) { - if ( !aPersistent.containsKey(key) ) { - throw new RuntimeException("Key '" + key + "' not found"); + for (Object key : keys) { + if (!aPersistent.containsKey(key)) { + throw new RuntimeException("Key '" + key + "' not found"); } - Object mergedValue = aMerged.get(key); - Object persistentValue = aPersistent.get(key); - if ( mergedValue instanceof Persistent ) { - if ( persistentValue instanceof Persistent ) { - processPersistent((Persistent)persistentValue, (Persistent)mergedValue, aProcessed); + Object mergedValue = aMerged.get(key); + Object persistentValue = aPersistent.get(key); + if (mergedValue instanceof Persistent) { + if (persistentValue instanceof Persistent) { + processPersistent((Persistent) persistentValue, + (Persistent) mergedValue, aProcessed); } else { - throw new RuntimeException("Value in original object is null, whereas merged object contains a value"); + throw new RuntimeException( + "Value in original object is null, whereas merged object contains a value"); } } } diff --git a/support/src/org/wamblee/xml/XSLT.java b/support/src/org/wamblee/xml/XSLT.java index 14789e86..e7c5fc76 100644 --- a/support/src/org/wamblee/xml/XSLT.java +++ b/support/src/org/wamblee/xml/XSLT.java @@ -17,7 +17,8 @@ package org.wamblee.xml; import java.io.ByteArrayInputStream; -import java.io.File; +import java.io.IOException; +import java.io.InputStream; import javax.xml.transform.Result; import javax.xml.transform.Source; @@ -30,12 +31,21 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import org.w3c.dom.Document; +import org.wamblee.io.InputResource; /** * XSLT utilities. */ public class XSLT { + /** + * Constructs the XSLT processor. + * + */ + public XSLT() { + // Empty. + } + /** * Transforms a DOM document into another DOM document using a given XSLT * transformation. @@ -45,43 +55,70 @@ public class XSLT { * @param aXslt * XSLT to use. * @return Transformed document. + * @throws IOException + * In case of problems reading resources. + * @throws TransformerException + * In case transformation fails. */ - public static Document transform( Document aDocument, File aXslt ) { - Source source = new DOMSource( aDocument ); - DOMResult result = new DOMResult( ); - transform( source, result, aXslt ); - return (Document) result.getNode( ); - } - - public static Document transform(byte[] aDocument, File aXslt ) { - Source source = new StreamSource( new ByteArrayInputStream(aDocument) ); - DOMResult result = new DOMResult( ); - transform( source, result, aXslt ); - return (Document) result.getNode( ); + public Document transform(Document aDocument, InputResource aXslt) + throws IOException, TransformerException { + Source source = new DOMSource(aDocument); + DOMResult result = new DOMResult(); + transform(source, result, aXslt); + return (Document) result.getNode(); } /** - * Transforms a DOM document into another DOM document using a given XSLT - * transformation. + * Transforms a document using XSLT. * * @param aDocument * Document to transform. * @param aXslt * XSLT to use. * @return Transformed document. + * @throws IOException + * In case of problems reading resources. + * @throws TransformerException + * In case transformation fails. + */ + public Document transform(byte[] aDocument, InputResource aXslt) + throws IOException, TransformerException { + Source source = new StreamSource(new ByteArrayInputStream(aDocument)); + DOMResult result = new DOMResult(); + transform(source, result, aXslt); + return (Document) result.getNode(); + } + + /** + * Transforms a document using XSLT. + * + * @param aSource + * Document to transform. + * @param aResult + * Result of the transformation. + * @param aXslt + * XSLT to use. + * @throws IOException + * In case of problems reading resources. + * @throws TransformerException + * In case transformation fails. */ - public static void transform( Source aSource, Result aResult, - File aXslt ) { + public void transform(Source aSource, Result aResult, InputResource aXslt) + throws IOException, TransformerException { + InputStream xslt = null; try { - Source xslt = new StreamSource( aXslt ); - Transformer transformer = TransformerFactory.newInstance( ) - .newTransformer( xslt ); - transformer.transform( aSource, aResult ); - } catch ( TransformerConfigurationException e ) { + xslt = aXslt.getInputStream(); + Source xsltSource = new StreamSource(xslt); + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(xsltSource); + transformer.transform(aSource, aResult); + } catch (TransformerConfigurationException e) { throw new RuntimeException( - "Configuration problem of XSLT transformation", e ); - } catch ( TransformerException e ) { - throw new RuntimeException( "Error transforming document", e ); + "Configuration problem of XSLT transformation", e); + } finally { + if (xslt != null) { + xslt.close(); + } } } } diff --git a/support/test/org/wamblee/concurrency/ReadWriteLockTest.java b/support/test/org/wamblee/concurrency/ReadWriteLockTest.java index 84afd1c5..2c159e94 100644 --- a/support/test/org/wamblee/concurrency/ReadWriteLockTest.java +++ b/support/test/org/wamblee/concurrency/ReadWriteLockTest.java @@ -26,9 +26,21 @@ import junit.framework.TestCase; * @see ReadWriteLock */ public class ReadWriteLockTest extends TestCase { + /** + * + */ + private static final int HALF_SECOND = 500; + /** + * + */ + private static final int ONE_SECOND = 1000; + /** + * + */ + private static final int TWO_SECONDS = 2000; private ReadWriteLock _lock; - int _nReaders; - int _nWriters; + private int _nReaders; + private int _nWriters; /** * Constructor for ReadWriteLockTest. @@ -101,14 +113,14 @@ public class ReadWriteLockTest extends TestCase { * @throws InterruptedException May not occur. */ public void testMultipleReaders() throws InterruptedException { - Runnable runnable = new ReadLocker(_lock, this, 2000); + Runnable runnable = new ReadLocker(_lock, this, TWO_SECONDS); Thread t1 = new Thread(runnable); t1.start(); Thread t2 = new Thread(runnable); t2.start(); - Thread.sleep(1000); + Thread.sleep(ONE_SECOND); assertTrue("Not enough readers!", getReaderCount() == 2); t1.join(); t2.join(); @@ -120,13 +132,13 @@ public class ReadWriteLockTest extends TestCase { * @throws InterruptedException May not occur. */ public void testSingleWriter() throws InterruptedException { - WriteLocker writer = new WriteLocker(_lock, this, 1000); + WriteLocker writer = new WriteLocker(_lock, this, ONE_SECOND); Thread t1 = new Thread(writer); Thread t2 = new Thread(writer); t1.start(); t2.start(); - Thread.sleep(500); + Thread.sleep(HALF_SECOND); assertTrue("Wrong writer count: " + getWriterCount(), getWriterCount() == 1); t1.join(); @@ -139,20 +151,20 @@ public class ReadWriteLockTest extends TestCase { * @throws InterruptedException May not occur. */ public void testMultipleWriters() throws InterruptedException { - WriteLocker writer1 = new WriteLocker(_lock, this, 1500); - WriteLocker writer2 = new WriteLocker(_lock, this, 1000); + WriteLocker writer1 = new WriteLocker(_lock, this, HALF_SECOND + ONE_SECOND); + WriteLocker writer2 = new WriteLocker(_lock, this, ONE_SECOND); Thread t1 = new Thread(writer1); Thread t2 = new Thread(writer2); t1.start(); - Thread.sleep(500); + Thread.sleep(HALF_SECOND); assertTrue(getWriterCount() == 1); t2.start(); - Thread.sleep(500); + Thread.sleep(HALF_SECOND); assertTrue(getWriterCount() == 1); // first writer still // has the lock. - Thread.sleep(1000); + Thread.sleep(ONE_SECOND); // at t = 2, the second writer still must have // a lock. @@ -168,22 +180,22 @@ public class ReadWriteLockTest extends TestCase { * @throws InterruptedException May not occur. */ public void testReadWrite1() throws InterruptedException { - ReadLocker readLocker = new ReadLocker(_lock, this, 2000); + ReadLocker readLocker = new ReadLocker(_lock, this, TWO_SECONDS); Thread t1 = new Thread(readLocker); - WriteLocker writeLocker = new WriteLocker(_lock, this, 2000); + WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS); Thread t2 = new Thread(writeLocker); t1.start(); // acquire read lock - Thread.sleep(500); + Thread.sleep(HALF_SECOND); assertTrue(getReaderCount() == 1); t2.start(); - Thread.sleep(500); + Thread.sleep(HALF_SECOND); // 1 second underway, reader still holding the // lock so write lock cannot be acquired. assertTrue(getReaderCount() == 1); assertTrue(getWriterCount() == 0); - Thread.sleep(1500); + Thread.sleep(ONE_SECOND + HALF_SECOND); // 2.5 seconds underway, read lock released and // write lock must be acquired. @@ -201,32 +213,32 @@ public class ReadWriteLockTest extends TestCase { * @throws InterruptedException May not occur. */ public void testReadWrite2() throws InterruptedException { - ReadLocker readLocker1 = new ReadLocker(_lock, this, 2500); - ReadLocker readLocker2 = new ReadLocker(_lock, this, 2500); + ReadLocker readLocker1 = new ReadLocker(_lock, this, TWO_SECONDS + HALF_SECOND); + ReadLocker readLocker2 = new ReadLocker(_lock, this, TWO_SECONDS + HALF_SECOND); Thread t1 = new Thread(readLocker1); Thread t2 = new Thread(readLocker2); - WriteLocker writeLocker = new WriteLocker(_lock, this, 2000); + WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS); Thread t3 = new Thread(writeLocker); t1.start(); // acquire read lock - Thread.sleep(1000); + Thread.sleep(ONE_SECOND); assertTrue(getReaderCount() == 1); t2.start(); - Thread.sleep(500); + Thread.sleep(HALF_SECOND); assertTrue(getReaderCount() == 2); t3.start(); - Thread.sleep(500); + Thread.sleep(HALF_SECOND); // 2 seconds, assertTrue(getReaderCount() == 2); assertTrue(getWriterCount() == 0); - Thread.sleep(1000); + Thread.sleep(ONE_SECOND); // 3 seconds underway, first read lock must // have been released. assertTrue(getReaderCount() == 1); assertTrue(getWriterCount() == 0); - Thread.sleep(500); + Thread.sleep(HALF_SECOND); // 4 seconds underway, write lock must have // been acquired. @@ -245,22 +257,22 @@ public class ReadWriteLockTest extends TestCase { * @throws InterruptedException May not occur. */ public void testReadWrite3() throws InterruptedException { - ReadLocker readLocker = new ReadLocker(_lock, this, 2000); + ReadLocker readLocker = new ReadLocker(_lock, this, TWO_SECONDS); Thread t1 = new Thread(readLocker); - WriteLocker writeLocker = new WriteLocker(_lock, this, 2000); + WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS); Thread t2 = new Thread(writeLocker); t2.start(); // acquire write lock - Thread.sleep(500); + Thread.sleep(HALF_SECOND); assertTrue(getWriterCount() == 1); t1.start(); - Thread.sleep(500); + Thread.sleep(HALF_SECOND); // 1 second underway, writer still holding the // lock so read lock cannot be acquired. assertTrue(getWriterCount() == 1); assertTrue(getReaderCount() == 0); - Thread.sleep(1500); + Thread.sleep(ONE_SECOND + HALF_SECOND); // 2.5 seconds underway, write lock released and // read lock must be acquired. @@ -296,7 +308,7 @@ public class ReadWriteLockTest extends TestCase { } }); t1.start(); - Thread.sleep(1000); // wait until thread is started + Thread.sleep(ONE_SECOND); // wait until thread is started _lock.releaseRead(); // release lock from wrong thread. } catch (RuntimeException e) { return; // ok @@ -323,7 +335,7 @@ public class ReadWriteLockTest extends TestCase { } }); t1.start(); - Thread.sleep(1000); // wait until thread is started + Thread.sleep(ONE_SECOND); // wait until thread is started _lock.releaseWrite(); // release lock from wrong thread. } catch (RuntimeException e) { return; // ok @@ -433,15 +445,15 @@ public class ReadWriteLockTest extends TestCase { * lock, and performs a callback after the lock has been released. */ class ReadLocker implements Runnable { - ReadWriteLock _lock; - ReadWriteLockTest _lockTest; - int _sleepTime; - - public ReadLocker(ReadWriteLock lock, ReadWriteLockTest lockTest, - int sleepTime) { - _lock = lock; - _lockTest = lockTest; - _sleepTime = sleepTime; + private ReadWriteLock _lock; + private ReadWriteLockTest _lockTest; + private int _sleepTime; + + public ReadLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest, + int aSleepTime) { + _lock = aLock; + _lockTest = aLockTest; + _sleepTime = aSleepTime; } public void run() { @@ -467,15 +479,15 @@ class ReadLocker implements Runnable { * lock, and performs a callback after the lock has been released. */ class WriteLocker implements Runnable { - ReadWriteLock _lock; - ReadWriteLockTest _lockTest; - int _sleepTime; - - public WriteLocker(ReadWriteLock lock, ReadWriteLockTest lockTest, - int sleepTime) { - _lock = lock; - _lockTest = lockTest; - _sleepTime = sleepTime; + private ReadWriteLock _lock; + private ReadWriteLockTest _lockTest; + private int _sleepTime; + + public WriteLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest, + int aSleepTime) { + _lock = aLock; + _lockTest = aLockTest; + _sleepTime = aSleepTime; } public void run() { diff --git a/support/test/org/wamblee/observer/ObservableTest.java b/support/test/org/wamblee/observer/ObservableTest.java index b2b7bdd5..eef88a27 100644 --- a/support/test/org/wamblee/observer/ObservableTest.java +++ b/support/test/org/wamblee/observer/ObservableTest.java @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.observer; @@ -23,83 +23,95 @@ import org.jmock.Mock; import org.jmock.cglib.MockObjectTestCase; /** - * Test of the observer pattern implementation. + * Test of the observer pattern implementation. */ public class ObservableTest extends MockObjectTestCase { - + + /** + * + */ + private static final int SUBSCRIBER_COUNT = 100; + private static final String UPDATE = "send"; - - private Observable _observable; - - /* (non-Javadoc) + private Observable _observable; + + /* + * (non-Javadoc) + * * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); - - _observable = new Observable(this, new DefaultObserverNotifier()); + + _observable = new Observable(this, + new DefaultObserverNotifier()); } - + /** * Tests subscription and notification of one subscriber. */ - public void testOneObserver() { + public void testOneObserver() { Mock mockObserver = mock(Observer.class); - Observer observer = (Observer)mockObserver.proxy(); + Observer observer = (Observer) mockObserver + .proxy(); long subscription = _observable.subscribe(observer); - - assertEquals(1, _observable.getObserverCount()); - + + assertEquals(1, _observable.getObserverCount()); + String message = "hallo"; - mockObserver.expects(once()).method(UPDATE).with(same(this), eq(message)); - + mockObserver.expects(once()).method(UPDATE).with(same(this), + eq(message)); + _observable.send(message); - _observable.unsubscribe(subscription); - assertEquals(0, _observable.getObserverCount()); - + _observable.unsubscribe(subscription); + assertEquals(0, _observable.getObserverCount()); + _observable.send(message); - + } - - + /** - * Subscribes many susbcribers and sends notifications to subscribers. - * Verifies that unique subscription number are returned. - * Also verifies that the correct subscribers are notfied. + * Subscribes many susbcribers and sends notifications to subscribers. + * Verifies that unique subscription number are returned. Also verifies that + * the correct subscribers are notfied. */ - public void testManySubscribers() { - int nsubscribers = 100; + public void testManySubscribers() { + int nsubscribers = SUBSCRIBER_COUNT; Mock[] mocks = new Mock[nsubscribers]; - + List subscriptions = new ArrayList(); - for (int i = 0; i < nsubscribers; i++) { + for (int i = 0; i < nsubscribers; i++) { Mock mockObserver = mock(Observer.class); - Observer observer = (Observer)mockObserver.proxy(); + Observer observer = (Observer) mockObserver + .proxy(); long subscription = _observable.subscribe(observer); - + mocks[i] = mockObserver; - assertTrue( subscriptions.add(subscription)); + assertTrue(subscriptions.add(subscription)); } - + assertEquals(nsubscribers, _observable.getObserverCount()); - + String message = "hallo"; - for (int i = 0; i < nsubscribers; i++) { - mocks[i].expects(once()).method(UPDATE).with(same(this), eq(message)); + for (int i = 0; i < nsubscribers; i++) { + mocks[i].expects(once()).method(UPDATE).with(same(this), + eq(message)); } - + _observable.send(message); - - for (int i = nsubscribers/2; i < nsubscribers; i++) { - _observable.unsubscribe(subscriptions.get(i)); + + for (int i = nsubscribers / 2; i < nsubscribers; i++) { + _observable.unsubscribe(subscriptions.get(i)); } - assertEquals(nsubscribers - ( nsubscribers - nsubscribers/2), _observable.getObserverCount()); - - message = "blabla"; - for (int i = 0; i < nsubscribers/2; i++) { - mocks[i].expects(once()).method(UPDATE).with(same(this), eq(message)); + assertEquals(nsubscribers - (nsubscribers - nsubscribers / 2), + _observable.getObserverCount()); + + message = "blabla"; + for (int i = 0; i < nsubscribers / 2; i++) { + mocks[i].expects(once()).method(UPDATE).with(same(this), + eq(message)); } _observable.send(message); } diff --git a/support/test/org/wamblee/test/HibernateExporter.java b/support/test/org/wamblee/test/HibernateExporter.java index 29bd2570..7b0bafa9 100644 --- a/support/test/org/wamblee/test/HibernateExporter.java +++ b/support/test/org/wamblee/test/HibernateExporter.java @@ -25,11 +25,19 @@ import org.hibernate.tool.hbm2ddl.SchemaExport; /** * Exporting the hibernate mapping. */ -public class HibernateExporter { +public final class HibernateExporter { - public static void main(String[] args) throws IOException { - String file = args[0]; - File dir = new File(args[1]); + /** + * Disabled constructor. + * + */ + private HibernateExporter() { + // Empty + } + + public static void main(String[] aArgs) throws IOException { + String file = aArgs[0]; + File dir = new File(aArgs[1]); Configuration conf = HibernateUtils.getConfiguration(dir); diff --git a/support/test/org/wamblee/test/HibernateUpdater.java b/support/test/org/wamblee/test/HibernateUpdater.java index 833764c0..3882ebfd 100644 --- a/support/test/org/wamblee/test/HibernateUpdater.java +++ b/support/test/org/wamblee/test/HibernateUpdater.java @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.test; @@ -23,18 +23,26 @@ import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaUpdate; /** - * Exporting the hibernate mapping. + * Exporting the hibernate mapping. */ -public class HibernateUpdater { +public final class HibernateUpdater { - public static void main(String[] args) throws IOException { - String file = args[0]; - File dir = new File(args[0]); - + /** + * Disabled constructor. + * + */ + private HibernateUpdater() { + // Empty + } + + public static void main(String[] aArgs) throws IOException { + String file = aArgs[0]; + File dir = new File(aArgs[0]); + Configuration conf = HibernateUtils.getConfiguration(dir); - - SchemaUpdate lSchemaUpdate = new SchemaUpdate( conf ); - lSchemaUpdate.execute( true, true ); + + SchemaUpdate lSchemaUpdate = new SchemaUpdate(conf); + lSchemaUpdate.execute(true, true); } } diff --git a/support/test/org/wamblee/test/HibernateUtils.java b/support/test/org/wamblee/test/HibernateUtils.java index 4630eb81..41895b08 100644 --- a/support/test/org/wamblee/test/HibernateUtils.java +++ b/support/test/org/wamblee/test/HibernateUtils.java @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.test; @@ -29,48 +29,63 @@ import org.wamblee.io.ClassPathResource; import org.wamblee.io.InputResource; /** - * Hibernate utilities. + * Hibernate utilities. */ -public class HibernateUtils { - +public final class HibernateUtils { + private static final String DATABASE_PROPS = "test.database.properties"; /** - * @param dir + * Disabled. + * + */ + private HibernateUtils() { + // Empty + } + + /** + * @param aDir * @return */ - public static Configuration getConfiguration(File dir) throws IOException { + public static Configuration getConfiguration(File aDir) throws IOException { Configuration conf = new Configuration(); - File[] files = dir.listFiles((FileFilter)(new AwkFilenameFilter(".*\\.hbm\\.xml"))); - for (File f: files) { + File[] files = aDir.listFiles((FileFilter) (new AwkFilenameFilter( + ".*\\.hbm\\.xml"))); + for (File f : files) { System.out.println("Mapping file: " + f); conf.addFile(f); } - - Map dbProps = getHibernateProperties(); - - for (Map.Entry entry : dbProps.entrySet()) { - System.out.println("Property: " + entry.getKey() + "=" + entry.getValue()); + + Map dbProps = getHibernateProperties(); + + for (Map.Entry entry : dbProps.entrySet()) { + System.out.println("Property: " + entry.getKey() + "=" + + entry.getValue()); conf.setProperty(entry.getKey(), entry.getValue()); } - + return conf; } - - private static Map getHibernateProperties() throws IOException { - - System.out.println( "Reading properties file: " + DATABASE_PROPS); - InputResource lPropFile = new ClassPathResource( DATABASE_PROPS ); - Properties props = new Properties(); - props.load( lPropFile.getInputStream( ) ); - - Map result = new TreeMap(); - result.put( "hibernate.connection.driver_class", props.getProperty( "database.driver" ) ); - result.put( "hibernate.connection.url", props.getProperty( "database.url" ) ); - result.put( "hibernate.connection.username", props.getProperty( "database.username" ) ); - result.put( "hibernate.connection.password", props.getProperty( "database.password" ) ); - - return result; + + private static Map getHibernateProperties() + throws IOException { + + System.out.println("Reading properties file: " + DATABASE_PROPS); + InputResource lPropFile = new ClassPathResource(DATABASE_PROPS); + Properties props = new Properties(); + props.load(lPropFile.getInputStream()); + + Map result = new TreeMap(); + result.put("hibernate.connection.driver_class", props + .getProperty("database.driver")); + result.put("hibernate.connection.url", props + .getProperty("database.url")); + result.put("hibernate.connection.username", props + .getProperty("database.username")); + result.put("hibernate.connection.password", props + .getProperty("database.password")); + + return result; } } diff --git a/support/test/org/wamblee/test/SpringTestCase.java b/support/test/org/wamblee/test/SpringTestCase.java index 8b436215..8b563b68 100644 --- a/support/test/org/wamblee/test/SpringTestCase.java +++ b/support/test/org/wamblee/test/SpringTestCase.java @@ -63,11 +63,11 @@ import org.wamblee.general.BeanKernel; import org.wamblee.persistence.hibernate.HibernateMappingFiles; /** - * Test case support class for spring tests. + * Test case support class for spring tests. */ public class SpringTestCase extends MockObjectTestCase { - private Log LOG = LogFactory.getLog(SpringTestCase.class); + private static final Log LOG = LogFactory.getLog(SpringTestCase.class); /** * Session factory bean name. @@ -94,22 +94,22 @@ public class SpringTestCase extends MockObjectTestCase { * Schema pattern. */ private static final String SCHEMA_PATTERN = "%"; - + /** * List of (String) configuration file locations for spring. */ private String[] _configLocations; - + /** * Application context for storing bean definitions that vary on a test by * test basis and cannot be hardcoded in the spring configuration files. */ private GenericApplicationContext _parentContext; - + /** - * Cached spring application context. + * Cached spring application context. */ - private ApplicationContext _context; + private ApplicationContext _context; public SpringTestCase(Class aSpringFiles, Class aMappingFiles) { @@ -117,9 +117,10 @@ public class SpringTestCase extends MockObjectTestCase { SpringConfigFiles springFiles = aSpringFiles.newInstance(); _configLocations = springFiles.toArray(new String[0]); } catch (Exception e) { - fail("Could not construct spring config files class '" + aSpringFiles.getName() + "'"); + fail("Could not construct spring config files class '" + + aSpringFiles.getName() + "'"); } - + // Register the Hibernate mapping files as a bean. _parentContext = new GenericApplicationContext(); BeanDefinition lDefinition = new RootBeanDefinition(aMappingFiles); @@ -135,35 +136,37 @@ public class SpringTestCase extends MockObjectTestCase { * @return Spring context. */ protected synchronized ApplicationContext getSpringContext() { - if ( _context == null ) { + if (_context == null) { _context = new ClassPathXmlApplicationContext( - (String[]) _configLocations, _parentContext); + (String[]) _configLocations, _parentContext); assertNotNull(_context); } - return _context; + return _context; } /** * @return Hibernate session factory. */ protected SessionFactory getSessionFactory() { - SessionFactory factory = (SessionFactory) getSpringContext().getBean(SESSION_FACTORY); - assertNotNull(factory); - return factory; + SessionFactory factory = (SessionFactory) getSpringContext().getBean( + SESSION_FACTORY); + assertNotNull(factory); + return factory; } protected void setUp() throws Exception { LOG.info("Performing setUp()"); super.setUp(); - - _context = null; // make sure we get a new application context for every - // new test. - BeanKernel - .overrideBeanFactory(new TestSpringBeanFactory(getSpringContext())); - - cleanDatabase(); + _context = null; // make sure we get a new application context for + // every + // new test. + + BeanKernel.overrideBeanFactory(new TestSpringBeanFactory( + getSpringContext())); + + cleanDatabase(); } /* @@ -185,9 +188,9 @@ public class SpringTestCase extends MockObjectTestCase { */ protected PlatformTransactionManager getTransactionManager() { PlatformTransactionManager manager = (PlatformTransactionManager) getSpringContext() - .getBean(TRANSACTION_MANAGER); - assertNotNull(manager); - return manager; + .getBean(TRANSACTION_MANAGER); + assertNotNull(manager); + return manager; } /** @@ -207,9 +210,10 @@ public class SpringTestCase extends MockObjectTestCase { * @return Hibernate template. */ protected HibernateTemplate getTemplate() { - HibernateTemplate template = (HibernateTemplate) getSpringContext().getBean(HibernateTemplate.class.getName()); - assertNotNull(template); - return template; + HibernateTemplate template = (HibernateTemplate) getSpringContext() + .getBean(HibernateTemplate.class.getName()); + assertNotNull(template); + return template; } /** @@ -254,11 +258,11 @@ public class SpringTestCase extends MockObjectTestCase { } public void cleanDatabase() throws SQLException { - - if (! isDatabaseConfigured() ) { - return; + + if (!isDatabaseConfigured()) { + return; } - + String[] tables = getTableNames(); try { @@ -273,7 +277,7 @@ public class SpringTestCase extends MockObjectTestCase { SQLException exc = new SQLException(e.getMessage()); exc.initCause(e); throw exc; - } + } } /** @@ -370,7 +374,7 @@ public class SpringTestCase extends MockObjectTestCase { JdbcTemplate template = new JdbcTemplate(getDataSource()); int result = template.update(aSql, aArgs); - Map map = new TreeMap(); + Map map = new TreeMap(); map.put("result", new Integer(result)); return map; @@ -548,23 +552,24 @@ public class SpringTestCase extends MockObjectTestCase { + " statement: " + aStatement); } } - - private boolean isDatabaseConfigured() { - try { - getDataSource(); - } catch (NoSuchBeanDefinitionException e ) { - return false; + + private boolean isDatabaseConfigured() { + try { + getDataSource(); + } catch (NoSuchBeanDefinitionException e) { + return false; } - return true; + return true; } /** * @return Returns the dataSource. */ public DataSource getDataSource() { - DataSource ds = (DriverManagerDataSource) getSpringContext().getBean(DATA_SOURCE); - assertNotNull(ds); - return ds; + DataSource ds = (DriverManagerDataSource) getSpringContext().getBean( + DATA_SOURCE); + assertNotNull(ds); + return ds; } /** @@ -581,8 +586,8 @@ public class SpringTestCase extends MockObjectTestCase { return count; } - - protected int countResultSet(ResultSet aResultSet) throws SQLException { + + protected int countResultSet(ResultSet aResultSet) throws SQLException { int count = 0; while (aResultSet.next()) { diff --git a/support/test/org/wamblee/test/TestSupport.java b/support/test/org/wamblee/test/TestSupport.java index 4cb23e3b..c10c24b3 100644 --- a/support/test/org/wamblee/test/TestSupport.java +++ b/support/test/org/wamblee/test/TestSupport.java @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.wamblee.test; import java.io.File; @@ -27,169 +27,179 @@ import junit.framework.Assert; /** * @author Erik Test support utility. */ -public class TestSupport { - - /** - * Obtain root directory of JUnit tests. - * - * @return Directory name. - */ - public static File getTestRootDir() { - return new File("testdata"); - } - - /** - * Returns a temporary directory. - * - * @return Temporary directory. - */ - public static File getTmpDir() { - return new File(getTestRootDir(), "tmpdir"); - } - - /** - * Recursively remove a directory. - * - * @param aSrc - * Directoryto remove. - */ - public static void removeDir(File aSrc) { - if (!aSrc.exists()) { - return; - } - Assert.assertTrue(aSrc.getPath(), aSrc.isDirectory()); - File[] files = aSrc.listFiles(); - for (int i = 0; i < files.length; i++) { - File file = files[i]; - if (file.isDirectory()) { - removeDir(file); - } else { - Assert.assertTrue(file.getPath(), file.delete()); - } - } - Assert.assertTrue(aSrc.getPath(), aSrc.delete()); - } - - /** - * Recursively copy a directory. - * - * @param aSrc - * Source directory - * @param aTarget - * Target directory. - */ - public static void copyDir(File aSrc, File aTarget) { - Assert.assertTrue(aSrc.isDirectory()); - Assert.assertTrue(!aTarget.exists()); - - aTarget.mkdirs(); - - File[] files = aSrc.listFiles(); - for (int i = 0; i < files.length; i++) { - File file = files[i]; - if (file.isDirectory()) { - if (!file.getName().equals(".svn")) { - copyDir(new File(aSrc, file.getName()), new File(aTarget, - file.getName())); - } - } else { - copyFile(file, new File(aTarget, file.getName())); - } - } - } - - /** - * Copy a file. If copying fails then the testcase will fail. - * - * @param aSrc - * Source file. - * @param aTarget - * Target file. - */ - public static void copyFile(File aSrc, File aTarget) { - - try { - FileInputStream fis = new FileInputStream(aSrc); - FileOutputStream fos = new FileOutputStream(aTarget); - FileChannel fcin = fis.getChannel(); - FileChannel fcout = fos.getChannel(); - - // map input file - - MappedByteBuffer mbb = fcin.map(FileChannel.MapMode.READ_ONLY, 0, - fcin.size()); - - // do the file copy - fcout.write(mbb); - - // finish up - - fcin.close(); - fcout.close(); - fis.close(); - fos.close(); - } catch (IOException e) { - Assert.assertTrue("Copying file " + aSrc.getPath() + " to " - + aTarget.getPath() + " failed.", false); - } - } - - /** - * Remove a file or directory. The test case will fail if this does not - * succeed. - * - * @param aFile - * entry to remove. - */ - public static void delete(File aFile) { - Assert.assertTrue("Could not delete " + aFile.getPath(), aFile.delete()); - } - - /** - * Remove all files within a given directory including the directory itself. - * This only attempts to remove regular files and not directories within the - * directory. If the directory contains a nested directory, the deletion - * will fail. The test case will fail if this fails. - * - * @param aDir - * Directory to remove. - */ - public static void deleteDir(File aDir) { - cleanDir(aDir); - delete(aDir); - } - - /** - * Remove all regular files within a given directory. - * - * @param outputDirName - */ - public static void cleanDir(File aDir) { - if (!aDir.exists()) { - return; // nothing to do. - } - File[] entries = aDir.listFiles(); - for (int i = 0; i < entries.length; i++) { - File file = entries[i]; - if (file.isFile()) { - Assert.assertTrue("Could not delete " + entries[i].getPath(), - entries[i].delete()); - } - } - } - - /** - * Creates directory if it does not already exist. The test case will fail - * if the directory cannot be created. - * - * @param aDir - * Directory to create. - */ - public static void createDir(File aDir) { - if (aDir.isDirectory()) { - return; // nothing to do. - } - Assert.assertTrue("Could not create directory " + aDir.getPath(), aDir - .mkdirs()); - } +public final class TestSupport { + + /** + * Disabled constructor. + * + */ + private TestSupport() { + // Empty + } + + /** + * Obtain root directory of JUnit tests. + * + * @return Directory name. + */ + public static File getTestRootDir() { + return new File("testdata"); + } + + /** + * Returns a temporary directory. + * + * @return Temporary directory. + */ + public static File getTmpDir() { + return new File(getTestRootDir(), "tmpdir"); + } + + /** + * Recursively remove a directory. + * + * @param aSrc + * Directoryto remove. + */ + public static void removeDir(File aSrc) { + if (!aSrc.exists()) { + return; + } + Assert.assertTrue(aSrc.getPath(), aSrc.isDirectory()); + File[] files = aSrc.listFiles(); + for (int i = 0; i < files.length; i++) { + File file = files[i]; + if (file.isDirectory()) { + removeDir(file); + } else { + Assert.assertTrue(file.getPath(), file.delete()); + } + } + Assert.assertTrue(aSrc.getPath(), aSrc.delete()); + } + + /** + * Recursively copy a directory. + * + * @param aSrc + * Source directory + * @param aTarget + * Target directory. + */ + public static void copyDir(File aSrc, File aTarget) { + Assert.assertTrue(aSrc.isDirectory()); + Assert.assertTrue(!aTarget.exists()); + + aTarget.mkdirs(); + + File[] files = aSrc.listFiles(); + for (int i = 0; i < files.length; i++) { + File file = files[i]; + if (file.isDirectory()) { + if (!file.getName().equals(".svn")) { + copyDir(new File(aSrc, file.getName()), new File(aTarget, + file.getName())); + } + } else { + copyFile(file, new File(aTarget, file.getName())); + } + } + } + + /** + * Copy a file. If copying fails then the testcase will fail. + * + * @param aSrc + * Source file. + * @param aTarget + * Target file. + */ + public static void copyFile(File aSrc, File aTarget) { + + try { + FileInputStream fis = new FileInputStream(aSrc); + FileOutputStream fos = new FileOutputStream(aTarget); + FileChannel fcin = fis.getChannel(); + FileChannel fcout = fos.getChannel(); + + // map input file + + MappedByteBuffer mbb = fcin.map(FileChannel.MapMode.READ_ONLY, 0, + fcin.size()); + + // do the file copy + fcout.write(mbb); + + // finish up + + fcin.close(); + fcout.close(); + fis.close(); + fos.close(); + } catch (IOException e) { + Assert.assertTrue("Copying file " + aSrc.getPath() + " to " + + aTarget.getPath() + " failed.", false); + } + } + + /** + * Remove a file or directory. The test case will fail if this does not + * succeed. + * + * @param aFile + * entry to remove. + */ + public static void delete(File aFile) { + Assert + .assertTrue("Could not delete " + aFile.getPath(), aFile + .delete()); + } + + /** + * Remove all files within a given directory including the directory itself. + * This only attempts to remove regular files and not directories within the + * directory. If the directory contains a nested directory, the deletion + * will fail. The test case will fail if this fails. + * + * @param aDir + * Directory to remove. + */ + public static void deleteDir(File aDir) { + cleanDir(aDir); + delete(aDir); + } + + /** + * Remove all regular files within a given directory. + * + * @param outputDirName + */ + public static void cleanDir(File aDir) { + if (!aDir.exists()) { + return; // nothing to do. + } + File[] entries = aDir.listFiles(); + for (int i = 0; i < entries.length; i++) { + File file = entries[i]; + if (file.isFile()) { + Assert.assertTrue("Could not delete " + entries[i].getPath(), + entries[i].delete()); + } + } + } + + /** + * Creates directory if it does not already exist. The test case will fail + * if the directory cannot be created. + * + * @param aDir + * Directory to create. + */ + public static void createDir(File aDir) { + if (aDir.isDirectory()) { + return; // nothing to do. + } + Assert.assertTrue("Could not create directory " + aDir.getPath(), aDir + .mkdirs()); + } } diff --git a/support/test/org/wamblee/test/TestTransactionCallback.java b/support/test/org/wamblee/test/TestTransactionCallback.java index fa07b698..ff46779b 100644 --- a/support/test/org/wamblee/test/TestTransactionCallback.java +++ b/support/test/org/wamblee/test/TestTransactionCallback.java @@ -1,21 +1,18 @@ - package org.wamblee.test; import java.util.Map; - /** - * Transaction callback for testing. - * The test will fail if any type of exception is thrown. + * Transaction callback for testing. The test will fail if any type of exception + * is thrown. */ public interface TestTransactionCallback { /** * Executes code within a transaction, causing the testcase to fail if any * type of exception is thrown. - * - * @return A map containg the resuls of the execution. This is - * a convenient method of returning multiple results from - * a call. + * + * @return A map containg the resuls of the execution. This is a convenient + * method of returning multiple results from a call. */ - Map execute( ) throws Exception; + Map execute() throws Exception; } diff --git a/support/test/org/wamblee/test/TestTransactionCallbackWithoutResult.java b/support/test/org/wamblee/test/TestTransactionCallbackWithoutResult.java index 05a23573..84e213f5 100644 --- a/support/test/org/wamblee/test/TestTransactionCallbackWithoutResult.java +++ b/support/test/org/wamblee/test/TestTransactionCallbackWithoutResult.java @@ -1,16 +1,14 @@ - package org.wamblee.test; - /** - * Transaction callback for testing. - * The test will fail if any type of exception is thrown. + * Transaction callback for testing. The test will fail if any type of exception + * is thrown. */ public interface TestTransactionCallbackWithoutResult { /** * Executes code within a transaction, causing the testcase to fail if any * type of exception is thrown. - * + * */ - void execute( ) throws Exception; + void execute() throws Exception; } -- 2.31.1