* 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;
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<KeyType extends Serializable, ValueType extends Serializable> {
-
+
private static final Logger LOGGER = Logger.getLogger(CachedObject.class);
-
+
/**
- * Callback invoked to compute an object if it was not found in the cache.
- * @param <T> Type of the object
+ * Callback invoked to compute an object if it was not found in the cache.
+ *
+ * @param <T>
+ * Type of the object
*/
public static interface Computation<Key extends Serializable, Value extends Serializable> {
/**
- * 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<KeyType, ValueType> _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<KeyType, ValueType> _computation;
-
+ private Computation<KeyType, ValueType> _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<KeyType,ValueType> aCache, KeyType aObjectKey, Computation<KeyType,ValueType> aComputation) {
- _cache = aCache;
- _objectKey = aObjectKey;
- _computation = aComputation;
+ public CachedObject(Cache<KeyType, ValueType> aCache, KeyType aObjectKey,
+ Computation<KeyType, ValueType> 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;
}
}
implements org.wamblee.cache.Cache<KeyType, ValueType> {
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
*/
_manager = CacheManager.create();
_cache = _manager.getCache(aCacheName);
if (_cache == null) {
- LOGGER.warn("Creating cache '" + aCacheName + "' because it is not configured");;
+ LOGGER.warn("Creating cache '" + aCacheName
+ + "' because it is not configured");
_manager.addCache(aCacheName);
_cache = _manager.getCache(aCacheName);
}
- assert _cache != null;
+ assert _cache != null;
} finally {
is.close();
}
*/
public ValueType get(KeyType aKey) {
try {
- Element element = _cache.get(aKey);
- if ( element == null ) {
- return null;
+ Element element = _cache.get(aKey);
+ if (element == null) {
+ return null;
}
- return (ValueType)element.getValue();
+ return (ValueType) element.getValue();
} catch (CacheException e) {
throw new RuntimeException("Cache problem key = '" + aKey + "'", e);
}
* 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;
import java.util.HashMap;
/**
- * A very simple cache based on a HashMap,
- * It never expires any entries, and has no bounds on its size.
+ * A very simple cache based on a HashMap, It never expires any entries, and has
+ * no bounds on its size.
*/
-public class ForeverCache<KeyType extends Serializable,ValueType extends Serializable>
- implements Cache<KeyType,ValueType> {
+public class ForeverCache<KeyType extends Serializable, ValueType extends Serializable>
+ implements Cache<KeyType, ValueType> {
/**
- * Cached entries.
+ * Cached entries.
*/
- private HashMap<KeyType, ValueType> _map;
-
+ private HashMap<KeyType, ValueType> _map;
+
/**
- * Constructs the cache.
- *
+ * Constructs the cache.
+ *
*/
- public ForeverCache() {
- _map = new HashMap<KeyType,ValueType>();
+ public ForeverCache() {
+ _map = new HashMap<KeyType, ValueType>();
}
-
- /* (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() {
* Releases the lock.
*/
void release();
-}
\ No newline at end of file
+}
/**
- * Determines if an object matches.
+ * Determines if an object matches a certain condition.
*/
public interface Condition<T> {
/**
- * 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);
}
* 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<T> implements Condition<T> {
-
+
private List<Condition<T>> _conditions;
-
+
+ /**
+ * Constructs the condition.
+ *
+ * @param aCondition1
+ * First condition.
+ * @param aCondition2
+ * Second condition.
+ */
public OrCondition(Condition<T> aCondition1, Condition<T> aCondition2) {
_conditions = new ArrayList<Condition<T>>();
- _conditions.add(aCondition1);
+ _conditions.add(aCondition1);
_conditions.add(aCondition2);
}
-
- public OrCondition(List<Condition<T>> aConditions) {
- _conditions = aConditions;
+
+ /**
+ * Constructs the or condition.
+ *
+ * @param aConditions
+ * List of conditions to use in the logical or.
+ */
+ public OrCondition(List<Condition<T>> 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<T> condition: _conditions) {
- if ( condition.matches(aObject)) {
- return true;
+ for (Condition<T> condition : _conditions) {
+ if (condition.matches(aObject)) {
+ return true;
}
}
- return false;
+ return false;
}
}
* 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.
*/
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 extends Object> T bla(Class<T> ddk) {
- return null;
- }
}
/**
* The standard means to obtain the bean factory.
*/
-public class BeanKernel {
+public final class BeanKernel {
private static final Log LOG = LogFactory.getLog(BeanKernel.class);
* Cached bean factory.
*/
private static BeanFactory BEAN_FACTORY;
+
+ /**
+ * Disabled constructor.
+ *
+ */
+ private BeanKernel() {
+ // Empty
+ }
/**
* Overrides the default mechanism for looking up the bean factory by
* 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 <T> Type of the first object.
- * @param <U> Type of the second object.
+ * @param <T>
+ * Type of the first object.
+ * @param <U>
+ * Type of the second object.
*/
-public class Pair<T,U> {
-
- private T _t;
- private U _u;
-
- public Pair(T t, U u ) {
- _t = t;
- _u = u;
- }
-
- public Pair(Pair<T,U> p) {
- _t = p._t;
- _u = p._u;
- }
-
- public T getFirst() {
- return _t;
- }
-
- public U getSecond() {
- return _u;
- }
+public class Pair<T, U> {
+
+ 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<T, U> 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;
+ }
}
private String _factoryName;
+ /**
+ * Constructs the bean factory.
+ * @param aFactoryName Spring bean factory to use.
+ */
public SpringBeanFactory(String aFactoryName) {
_factoryName = aFactoryName;
}
* 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;
/**
* 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 + ")";
}
}
* 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;
import java.io.IOException;
import java.io.InputStream;
-
-
/**
* Resource implemention for reading from a file.
*/
/**
* 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));
}
}
* 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;
}
* 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.
*/
/**
* 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;
}
}
* 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<ObservableType,Event> implements ObserverNotifier<ObservableType,Event>{
+public class DefaultObserverNotifier<ObservableType, Event> implements
+ ObserverNotifier<ObservableType, Event> {
/**
- * 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<ObservableType, Event> aObserver, ObservableType aObservable, Event aEvent) {
- aObserver.send(aObservable, aEvent);
+ public void update(Observer<ObservableType, Event> aObserver,
+ ObservableType aObservable, Event aEvent) {
+ aObserver.send(aObservable, aEvent);
}
}
* 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;
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<ObservableType, Event> {
-
+
private static final Logger LOGGER = Logger.getLogger(Observable.class);
-
+
/**
- * Observable.
+ * Observable.
*/
private ObservableType _observable;
-
+
/**
- * Used to notify observers.
+ * Used to notify observers.
*/
- private ObserverNotifier<ObservableType,Event> _notifier;
-
+ private ObserverNotifier<ObservableType, Event> _notifier;
+
/**
- * Map of subscription to observer.
+ * Map of subscription to observer.
*/
- private Map<Long, Observer<ObservableType,Event>> _observers;
-
+ private Map<Long, Observer<ObservableType, Event>> _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<ObservableType,Event> aNotifier) {
+ public Observable(ObservableType aObservable,
+ ObserverNotifier<ObservableType, Event> aNotifier) {
_observable = aObservable;
- _notifier = aNotifier;
+ _notifier = aNotifier;
_observers = new TreeMap<Long, Observer<ObservableType, Event>>();
- _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<ObservableType, Event> 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<Observer<ObservableType,Event>> observers = new ArrayList<Observer<ObservableType, Event>>();
- synchronized (this) {
+ // Make sure we do the notification while not holding the lock to avoid
+ // potential deadlock
+ // situations.
+ List<Observer<ObservableType, Event>> observers = new ArrayList<Observer<ObservableType, Event>>();
+ synchronized (this) {
observers.addAll(_observers.values());
}
- for (Observer<ObservableType,Event> observer: observers) {
- _notifier.update(observer, _observable, aEvent);
+ for (Observer<ObservableType, Event> 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();
}
/**
* This is a type-safe version of {@link java.util.Observable}.
*/
-public interface Observer<ObservableType,Event> {
+public interface Observer<ObservableType, Event> {
/**
* Called when an event has occurred on the observable.
- * @param aObservabdle Observable.
+ * @param aObservable Observable.
* @param aEvent Event.
*/
void send(ObservableType aObservable, Event aEvent);
/**
* 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);
}
* {@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();
}
}
* 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<ObjectElem>());
}
-
-
/**
- * 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<ObjectElem> 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());
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) {
}
/**
- * 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<ObjectElem> aProcessed) {
+ public static void processList(List aPersistent, List aMerged,
+ List<ObjectElem> aProcessed) {
Object[] merged = aMerged.toArray();
Object[] persistent = aPersistent.toArray();
if (merged.length != persistent.length) {
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<ObjectElem> aProcessed) {
+ public static void processSet(Set aPersistent, Set aMerged,
+ List<ObjectElem> 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<ObjectElem> aProcessed) {
- if ( aMerged.size() != aPersistent.size() ) {
- throw new RuntimeException("Sizes differ " + aMerged.size() + " " + aPersistent.size());
+ public static void processMap(Map aPersistent, Map aMerged,
+ List<ObjectElem> 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");
}
}
}
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;
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.
* @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();
+ }
}
}
}
* @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.
* @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();
* @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();
* @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.
* @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.
* @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.
* @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.
}
});
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
}
});
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
* 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() {
* 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() {
* 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;
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<ObservableTest, String> _observable;
-
- /* (non-Javadoc)
+ private Observable<ObservableTest, String> _observable;
+
+ /*
+ * (non-Javadoc)
+ *
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
super.setUp();
-
- _observable = new Observable<ObservableTest, String>(this, new DefaultObserverNotifier());
+
+ _observable = new Observable<ObservableTest, String>(this,
+ new DefaultObserverNotifier());
}
-
+
/**
* Tests subscription and notification of one subscriber.
*/
- public void testOneObserver() {
+ public void testOneObserver() {
Mock mockObserver = mock(Observer.class);
- Observer<ObservableTest,String> observer = (Observer<ObservableTest,String>)mockObserver.proxy();
+ Observer<ObservableTest, String> observer = (Observer<ObservableTest, String>) 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<Long> subscriptions = new ArrayList<Long>();
- for (int i = 0; i < nsubscribers; i++) {
+ for (int i = 0; i < nsubscribers; i++) {
Mock mockObserver = mock(Observer.class);
- Observer<ObservableTest,String> observer = (Observer<ObservableTest,String>)mockObserver.proxy();
+ Observer<ObservableTest, String> observer = (Observer<ObservableTest, String>) 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);
}
/**
* 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);
* 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 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);
}
}
* 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 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<String,String> dbProps = getHibernateProperties();
-
- for (Map.Entry<String,String> entry : dbProps.entrySet()) {
- System.out.println("Property: " + entry.getKey() + "=" + entry.getValue());
+
+ Map<String, String> dbProps = getHibernateProperties();
+
+ for (Map.Entry<String, String> entry : dbProps.entrySet()) {
+ System.out.println("Property: " + entry.getKey() + "="
+ + entry.getValue());
conf.setProperty(entry.getKey(), entry.getValue());
}
-
+
return conf;
}
-
- private static Map<String,String> 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<String,String> result = new TreeMap<String,String>();
- 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<String, String> 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<String, String> result = new TreeMap<String, String>();
+ 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;
}
}
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.
* 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<? extends SpringConfigFiles> aSpringFiles,
Class<? extends HibernateMappingFiles> aMappingFiles) {
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);
* @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();
}
/*
*/
protected PlatformTransactionManager getTransactionManager() {
PlatformTransactionManager manager = (PlatformTransactionManager) getSpringContext()
- .getBean(TRANSACTION_MANAGER);
- assertNotNull(manager);
- return manager;
+ .getBean(TRANSACTION_MANAGER);
+ assertNotNull(manager);
+ return manager;
}
/**
* @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;
}
/**
}
public void cleanDatabase() throws SQLException {
-
- if (! isDatabaseConfigured() ) {
- return;
+
+ if (!isDatabaseConfigured()) {
+ return;
}
-
+
String[] tables = getTableNames();
try {
SQLException exc = new SQLException(e.getMessage());
exc.initCause(e);
throw exc;
- }
+ }
}
/**
JdbcTemplate template = new JdbcTemplate(getDataSource());
int result = template.update(aSql, aArgs);
- Map map = new TreeMap();
+ Map<String, Integer> map = new TreeMap<String, Integer>();
map.put("result", new Integer(result));
return map;
+ " 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;
}
/**
return count;
}
-
- protected int countResultSet(ResultSet aResultSet) throws SQLException {
+
+ protected int countResultSet(ResultSet aResultSet) throws SQLException {
int count = 0;
while (aResultSet.next()) {
* 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;
/**
* @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());
+ }
}
-
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;
}
-
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;
}