|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
public interface EventService
The core interface. An EventService provides publish/subscribe services to a single JVM using Class-based and String-based (i.e. "topic") publications and subscriptions.
In class-based pub/sub,EventSubscriber
s subscribe to a type on an EventService
, such
as the EventBus
, by providing a class, interface or generic type. The EventService
notifies subscribers when objects are published on the EventService with a matching type. Full class semantics are
respected. That is, if a subscriber subscribes to a class, the subscriber is notified if an object of
that class is publish or if an object of a subclass of that class is published. Likewise if a subscriber subscribes
to an interface, it will be notified if any object that implements that interface is published. Subscribers can
subscribe "exactly" using subscribeExactly(Class, EventSubscriber)
so that they are notified only if an
object of the exact class is published (and will not be notified if subclasses are published, since this would not
be "exact")
In topic-based pub/sub, an object "payload" is published on a topic name (String). EventTopicSubscriber
s subscribe
to either the exact name of the topic or they may subscribe using a Regular Expression that is used to match topic
names.
See the overview for an general introduction
and package documentation for usage details and examples.
A single subscriber cannot subscribe more than once to an event or topic name. EventService implementations should
handle double-subscription requests by returning false on subscribe(). A single EventSubscriber can subscribe to more
than one event class, and a single EventTopicSubscriber can subscribe to more than one topic name or pattern. A
single object may implement both EventSubscriber and EventTopicSubscriber interfaces. Subscribers are guaranteed to
only be called for the classes and/or topic names they subscribe to. If a subscriber subscribes to a topic and to a
regular expression that matches the topic name, this is considered two different subscriptions and the subscriber
will be called twice for the publication on the topic. Similarly, if a subscriber subscribes to a class and its
subclasses using subscribe() and again to a class of the same type using subscribeExactly(), this is considered two
different subscriptions and the subscriber will be called twice for the publication for a single event of the exact
type.
By default the EventService only holds WeakReferences to subscribers. If a subscriber has no references to it, then
it can be garbage collected. This avoids memory leaks in exchange for the risk of accidentally adding a listener and
have it disappear unexpectedly. If you want to subscribe a subscriber that will have no other reference to it, then
use one of the subscribeStrongly() methods, which will prevent garbage collection.
Unless garbage collected, EventSubscribers will remain subscribed until they are passed to one of the unsubscribe()
methods with the event class or topic name to which there are subscribed.
Subscribers are called in the order in which they are subscribed by default (FIFO), unless subscribers implement
Prioritized
. Those subscribers that implement Prioritized and return a negative priority are moved to the
front of the list (the more negative, the more to the front). Those subscribers that implement Prioritized and return
a positive priority are moved to the end of the list (the more positive, the more to the back). The FIFO guarantee
is only valid for the same subscribe() call. That is, the order of two subscribers, one to List.class and the other
to ArrayList.class is not guaranteed to be in the order of subscription when an ArrayList is published. The same is
true for topic subscribers when using RegEx expressions - when "Foo" is published, the order of subscribers that are
subscribed to "Foo", "Fo*" and "F*" are not guaranteed, though the second "Fo*" subscriber will never be called
before the first "Fo*" subscriber (ditto List and ArrayList). Prioritized subscribers are always guaranteed to be in
the order of priority, no matter the call or the resulting mix of subscribers. All ordering rules apply to all
types subscribers: class, topic, pattern, veto, etc. For Swing users, note that FIFO is
the opposite of Swing, where event listeners are called in the reverse order of when they were subscribed (FILO).
Publication on a class or topic name can be vetoed by a VetoEventListener
. All VetoEventListeners are checked
before any EventSubscribers or EventTopicSubscribers are called. This is unlike the JavaBean's
VetoPropertyEventListener which can leave side effects and half-propogated events. VetoEventListeners are subscribed
in the same manner as EventSubscribers and EventTopicSubscribers.
The state of a published event can be tracked if an event or a topic's payload object implements the
PublicationStatus
interface. EventServices are required to set such objects'
PublicationStatus
at the appropriate times during publication.
This simple example prints "Hello World"
EventService eventService = new ThreadSafeEventService(); //Create a subscriber EventTopicSubscriber subscriber = new EventTopicSubscriber() { public void onEvent(String topic, Object event) { System.out.println(topic+" "+event); } }); eventService.subscribe("Hello", subscriber); eventService.publish("Hello", "World"); System.out.println(subscriber + " Since the reference is used after it is subscribed, it doesn't get garbage collected, this is not necessary if you use subscribeStrongly()");Events and/or topic data can be cached, but are not by default. To cache events or topic data, call
setDefaultCacheSizePerClassOrTopic(int)
, setCacheSizeForEventClass(Class, int)
, or
setCacheSizeForTopic(String, int)
, setCacheSizeForTopic(Pattern, int)
. Retrieve cached values
with getLastEvent(Class)
, getLastTopicData(String)
, getCachedEvents(Class)
, or
getCachedTopicData(String)
. Using caching while subscribing is most likely to make sense only if you
subscribe and publish on the same thread (so caching is very useful for Swing applications since both happen on
the EDT in a single-threaded manner). In multithreaded applications, you never know if your subscriber has handled
an event while it was being subscribed (before the subscribe() method returned) that is newer or older than the
retrieved cached value (taken before or after subscribe() respectively).
There is nothing special about the term "Event," this could just as easily be called a "Message" Service, this term
is already taken by the JMS, which is similar, but is used across processes and networks.
ThreadSafeEventService} for the default implementation
,
SwingEventService} for the Swing-safe implementation
,
EventBus} for simple access to the Swing-safe implementation
,
org.bushe.swing.event.annotation.EventSubscriber} for subscription annotations
,
org.bushe.swing.event.annotation.EventTopicSubscriber} for subscription annotations
| Method Summary | ||
|---|---|---|
void |
clearAllSubscribers()
Clears all current subscribers and veto subscribers |
|
void |
clearCache()
Clear all event caches for all topics and event. |
|
void |
clearCache(java.lang.Class eventClass)
Clears the event cache for a specific event class or interface and it's any of it's subclasses or implementing classes. |
|
void |
clearCache(java.util.regex.Pattern pattern)
Clears the topic data cache for all topics that match a particular pattern. |
|
void |
clearCache(java.lang.String topic)
Clears the topic data cache for a specific topic name. |
|
|
getCachedEvents(java.lang.Class<T> eventClass)
When caching, returns the last set of event published for the type supplied. |
|
java.util.List |
getCachedTopicData(java.lang.String topic)
When caching, returns the last set of payload objects published on the topic name supplied. |
|
int |
getCacheSizeForEventClass(java.lang.Class eventClass)
Returns the number of events cached for a particular class of event. |
|
int |
getCacheSizeForTopic(java.lang.String topic)
Returns the number of cached data objects published on a particular topic. |
|
int |
getDefaultCacheSizePerClassOrTopic()
The default number of events or payloads kept per event class or topic |
|
|
getLastEvent(java.lang.Class<T> eventClass)
When caching, returns the last event publish for the type supplied. |
|
java.lang.Object |
getLastTopicData(java.lang.String topic)
When caching, returns the last payload published on the topic name supplied. |
|
|
getSubscribers(java.lang.Class<T> eventClass)
Union of getSubscribersToClass(Class) and getSubscribersToExactClass(Class) |
|
|
getSubscribers(java.util.regex.Pattern pattern)
Gets the subscribers that subscribed to a regular expression. |
|
|
getSubscribers(java.lang.String topic)
Union of getSubscribersByPattern(String) and geSubscribersToTopic(String) |
|
|
getSubscribers(java.lang.reflect.Type type)
Gets the subscribers that subscribed to a generic type. |
|
|
getSubscribersByPattern(java.lang.String topic)
Gets the subscribers that subscribed with a Pattern that matches the given topic. |
|
|
getSubscribersToClass(java.lang.Class<T> eventClass)
Gets subscribers that subscribed with the given a class, but not those subscribed exactly to the class. |
|
|
getSubscribersToExactClass(java.lang.Class<T> eventClass)
Gets subscribers that are subscribed exactly to a class, but not those subscribed non-exactly to a class. |
|
|
getSubscribersToTopic(java.lang.String topic)
Get the subscribers that subscribed to a topic. |
|
|
getVetoEventListeners(java.lang.String topicOrPattern)
Union of getVetoSubscribersToTopic(String) and getVetoSubscribersByPattern(String)
Misnamed method, should be called getVetoSubscribers(String) . |
|
|
getVetoSubscribers(java.lang.Class<T> eventClass)
Gets veto subscribers that subscribed to a given class. |
|
|
getVetoSubscribers(java.util.regex.Pattern pattern)
Gets the veto subscribers that subscribed to a regular expression. |
|
|
getVetoSubscribers(java.lang.String topic)
Deprecated. use getVetoSubscribersToTopic instead for direct replacement, or use getVetoEventListeners to get topic and pattern matchers. In EventBus 2.0 this name will replace getVetoEventListeners() and have it's union functionality |
|
|
getVetoSubscribersByPattern(java.lang.String topic)
Gets the veto subscribers that are subscribed by pattern that match the topic. |
|
|
getVetoSubscribersToClass(java.lang.Class<T> eventClass)
Gets the veto subscribers that subscribed to a class. |
|
|
getVetoSubscribersToExactClass(java.lang.Class<T> eventClass)
Get veto subscribers that subscribed to a given class exactly. |
|
|
getVetoSubscribersToTopic(java.lang.String topic)
Gets the veto subscribers that subscribed to a topic. |
|
void |
publish(java.lang.Object event)
Publishes an object so that subscribers will be notified if they subscribed to the object's class, one of its subclasses, or to one of the interfaces it implements. |
|
void |
publish(java.lang.String topic,
java.lang.Object o)
Publishes an object on a topic name so that all subscribers to that name or a Regular Expression that matches the topic name will be notified. |
|
void |
publish(java.lang.reflect.Type genericType,
java.lang.Object event)
Use this method to publish generified objects to subscribers of Types, i.e. |
|
void |
setCacheSizeForEventClass(java.lang.Class eventClass,
int cacheSize)
Set the number of events cached for a particular class of event. |
|
void |
setCacheSizeForTopic(java.util.regex.Pattern pattern,
int cacheSize)
Set the number of published data objects cached for a topics matching a pattern. |
|
void |
setCacheSizeForTopic(java.lang.String topicName,
int cacheSize)
Set the number of published data objects cached for a particular event topic. |
|
void |
setDefaultCacheSizePerClassOrTopic(int defaultCacheSizePerClassOrTopic)
Sets the default cache size for each kind of event, default is 0 (no caching). |
|
boolean |
subscribe(java.lang.Class eventClass,
EventSubscriber subscriber)
Subscribes an EventSubscriber to the publication of objects matching a type. |
|
boolean |
subscribe(java.util.regex.Pattern topicPattern,
EventTopicSubscriber subscriber)
Subscribes an EventSubscriber to the publication of all the topic names that match a RegEx Pattern. |
|
boolean |
subscribe(java.lang.String topic,
EventTopicSubscriber subscriber)
Subscribes an EventTopicSubscriber to the publication of a topic name. |
|
boolean |
subscribe(java.lang.reflect.Type type,
EventSubscriber subscriber)
Subscribe an EventSubscriber to publication of generic Types. |
|
boolean |
subscribeExactly(java.lang.Class eventClass,
EventSubscriber subscriber)
Subscribes an EventSubscriber to the publication of objects exactly matching a type. |
|
boolean |
subscribeExactlyStrongly(java.lang.Class eventClass,
EventSubscriber subscriber)
Subscribes an EventSubscriber to the publication of objects matching a type exactly. |
|
boolean |
subscribeStrongly(java.lang.Class eventClass,
EventSubscriber subscriber)
Subscribes an EventSubscriber to the publication of objects matching a type. |
|
boolean |
subscribeStrongly(java.util.regex.Pattern topicPattern,
EventTopicSubscriber subscriber)
Subscribes a subscriber to all the event topic names that match a RegEx expression. |
|
boolean |
subscribeStrongly(java.lang.String topic,
EventTopicSubscriber subscriber)
Subscribes a subscriber to an event topic name. |
|
boolean |
subscribeVetoListener(java.lang.Class eventClass,
VetoEventListener vetoListener)
Subscribes a VetoEventListener to publication of event matching a class. |
|
boolean |
subscribeVetoListener(java.util.regex.Pattern topicPattern,
VetoTopicEventListener vetoListener)
Subscribes an VetoTopicEventListener to all the topic names that match the RegEx Pattern. |
|
boolean |
subscribeVetoListener(java.lang.String topic,
VetoTopicEventListener vetoListener)
Subscribes a VetoTopicEventListener to a topic name. |
|
boolean |
subscribeVetoListenerExactly(java.lang.Class eventClass,
VetoEventListener vetoListener)
Subscribes a VetoEventListener to publication of an exact event class. |
|
boolean |
subscribeVetoListenerExactlyStrongly(java.lang.Class eventClass,
VetoEventListener vetoListener)
Subscribes a VetoEventListener for an event class (but not its subclasses). |
|
boolean |
subscribeVetoListenerStrongly(java.lang.Class eventClass,
VetoEventListener vetoListener)
Subscribes a VetoEventListener for an event class and its subclasses. |
|
boolean |
subscribeVetoListenerStrongly(java.util.regex.Pattern topicPattern,
VetoTopicEventListener vetoListener)
Subscribes a VetoTopicEventListener to a set of topics that match a RegEx expression. |
|
boolean |
subscribeVetoListenerStrongly(java.lang.String topic,
VetoTopicEventListener vetoListener)
Subscribes a VetoEventListener to a topic name. |
|
boolean |
unsubscribe(java.lang.Class eventClass,
EventSubscriber subscriber)
Stop the subscription for a subscriber that is subscribed to a class. |
|
boolean |
unsubscribe(java.lang.Class eventClass,
java.lang.Object subscribedByProxy)
Stop a subscription for an object that is subscribed with a ProxySubscriber. |
|
boolean |
unsubscribe(java.util.regex.Pattern topicPattern,
EventTopicSubscriber subscriber)
Stop the subscription for a subscriber that is subscribed to event topics via a Pattern. |
|
boolean |
unsubscribe(java.util.regex.Pattern pattern,
java.lang.Object subscribedByProxy)
When using annotations, an object may be subscribed by proxy. |
|
boolean |
unsubscribe(java.lang.String topic,
EventTopicSubscriber subscriber)
Stop the subscription for a subscriber that is subscribed to an event topic. |
|
boolean |
unsubscribe(java.lang.String topic,
java.lang.Object subscribedByProxy)
Stop a subscription for an object that is subscribed to a topic with a ProxySubscriber. |
|
boolean |
unsubscribeExactly(java.lang.Class eventClass,
EventSubscriber subscriber)
Stop the subscription for a subscriber that is subscribed to an exact class. |
|
boolean |
unsubscribeExactly(java.lang.Class eventClass,
java.lang.Object subscribedByProxy)
Stop a subscription for an object that is subscribed exactly with a ProxySubscriber. |
|
boolean |
unsubscribeVeto(java.lang.Class eventClass,
java.lang.Object subscribedByProxy)
Stop a veto subscription for an object that is subscribed with a ProxySubscriber. |
|
boolean |
unsubscribeVeto(java.util.regex.Pattern pattern,
java.lang.Object subscribedByProxy)
When using annotations, an object may be subscribed by proxy. |
|
boolean |
unsubscribeVeto(java.lang.String topic,
java.lang.Object subscribedByProxy)
Stop a veto subscription for an object that is subscribed to a topic with a ProxySubscriber. |
|
boolean |
unsubscribeVetoExactly(java.lang.Class eventClass,
java.lang.Object subscribedByProxy)
Stop a veto subscription for an object that is subscribed exactly with a ProxySubscriber. |
|
boolean |
unsubscribeVetoListener(java.lang.Class eventClass,
VetoEventListener vetoListener)
Stop the subscription for a vetoListener that is subscribed to an event class and its subclasses. |
|
boolean |
unsubscribeVetoListener(java.util.regex.Pattern topicPattern,
VetoTopicEventListener vetoListener)
Stop the subscription for a VetoTopicEventListener that is subscribed to an event topic RegEx pattern. |
|
boolean |
unsubscribeVetoListener(java.lang.String topic,
VetoTopicEventListener vetoListener)
Stop the subscription for a VetoTopicEventListener that is subscribed to an event topic name. |
|
boolean |
unsubscribeVetoListenerExactly(java.lang.Class eventClass,
VetoEventListener vetoListener)
Stop the subscription for a vetoListener that is subscribed to an event class (but not its subclasses). |
| Method Detail |
|---|
void publish(java.lang.Object event)
event
- the object to publishvoid publish(java.lang.reflect.Type genericType, java.lang.Object event)
subscribe(Type, EventSubscriber)
, and to publish to subscribers of the non-generic type.
Due to generic type erasure, the type must be supplied by the caller. You can get a declared object's
type by using the TypeReference
class. For Example:
TypeReference<List<Trade>> subscribingTypeReference = new TypeReference<List<Trade>>(){}; EventBus.subscribe(subscribingTypeReference.getType(), mySubscriber); EventBus.subscribe(List.class, thisSubscriberWillGetCalledToo); ... //Likely in some other class TypeReference<List<Trade>> publishingTypeReference = new TypeReference<List<Trade>>(){}; List<Trade> trades = new ArrayList<Trade>(); EventBus.publish(publishingTypeReference.getType(), trades); trades.add(trade); EventBus.publish(publishingTypeReference.getType(), trades);
genericType
- the generified type of the published object.event
- The event that occurredvoid publish(java.lang.String topic, java.lang.Object o)
topic
- The name of the topic subscribed too
- the object to publishboolean subscribe(java.lang.Class eventClass, EventSubscriber subscriber)
eventClass
- the class of published objects to subscriber listen tosubscriber
- The subscriber that will accept the events of the event class when published.
boolean subscribe(java.lang.reflect.Type type, EventSubscriber subscriber)
publish(java.lang.reflect.Type, Object)
.
Due to generic type erasure, the type must be supplied by the publisher. You can get a declared object's
type by using the TypeReference
class. For Example:
TypeReference<List<Trade>> subscribingTypeReference = new TypeReference<List<Trade>>(){}; EventBus.subscribe(subscribingTypeReference.getType(), mySubscriber); EventBus.subscribe(List.class, thisSubscriberWillGetCalledToo); ... //Likely in some other class TypeReference<List<Trade>> publishingTypeReference = new TypeReference<List<Trade>>(){}; List<Trade> trades = new ArrayList<Trade>(); EventBus.publish(publishingTypeReference.getType(), trades); trades.add(trade); EventBus.publish(publishingTypeReference.getType(), trades);
type
- the generic type to subscribe tosubscriber
- the subscriber to the type
boolean subscribeExactly(java.lang.Class eventClass, EventSubscriber subscriber)
eventClass
- the class of published objects to listen tosubscriber
- The subscriber that will accept the events when published.
boolean subscribe(java.lang.String topic, EventTopicSubscriber subscriber)
topic
- the name of the topic listened tosubscriber
- The topic subscriber that will accept the events when published.
boolean subscribe(java.util.regex.Pattern topicPattern, EventTopicSubscriber subscriber)
topicPattern
- pattern that matches to the name of the topic published tosubscriber
- The topic subscriber that will accept the events when published.
boolean subscribeStrongly(java.lang.Class eventClass, EventSubscriber subscriber)
subscribe(Class, EventSubscriber)
, except that the EventService holds
a regularly reference, not a WeakReference.
The subscriber will remain subscribed until unsubscribe(Class,EventSubscriber)
is called.
eventClass
- the class of published objects to listen tosubscriber
- The subscriber that will accept the events when published.
boolean subscribeExactlyStrongly(java.lang.Class eventClass, EventSubscriber subscriber)
subscribeExactly(Class, EventSubscriber)
, except that the EventService
holds a regularly reference, not a WeakReference.
The subscriber will remain subscribed until unsubscribe(Class,EventSubscriber)
is called.
eventClass
- the class of published objects to listen tosubscriber
- The subscriber that will accept the events when published.
boolean subscribeStrongly(java.lang.String topic, EventTopicSubscriber subscriber)
subscribe(String, EventTopicSubscriber)
, except that the EventService
holds a regularly reference, not a WeakReference.
The subscriber will remain subscribed until unsubscribe(String,EventTopicSubscriber)
is called.
topic
- the name of the topic listened tosubscriber
- The topic subscriber that will accept the events when published.
boolean subscribeStrongly(java.util.regex.Pattern topicPattern, EventTopicSubscriber subscriber)
subscribe(java.util.regex.Pattern, EventTopicSubscriber)
, except that the
EventService holds a regularly reference, not a WeakReference.
The subscriber will remain subscribed until unsubscribe(String,EventTopicSubscriber)
is called.
topicPattern
- the name of the topic listened tosubscriber
- The topic subscriber that will accept the events when published.
boolean unsubscribe(java.lang.Class eventClass, EventSubscriber subscriber)
eventClass
- the class of published objects to listen tosubscriber
- The subscriber that is subscribed to the event. The same reference as the one subscribed.
boolean unsubscribeExactly(java.lang.Class eventClass, EventSubscriber subscriber)
eventClass
- the class of published objects to listen tosubscriber
- The subscriber that is subscribed to the event. The same reference as the one subscribed.
boolean unsubscribe(java.lang.String topic, EventTopicSubscriber subscriber)
topic
- the topic listened tosubscriber
- The subscriber that is subscribed to the topic. The same reference as the one subscribed.
boolean unsubscribe(java.util.regex.Pattern topicPattern, EventTopicSubscriber subscriber)
topicPattern
- the regex expression matching topics listened tosubscriber
- The subscriber that is subscribed to the topic. The same reference as the one subscribed.
boolean subscribeVetoListener(java.lang.Class eventClass, VetoEventListener vetoListener)
eventClass
- the class of published objects that can be vetoedvetoListener
- The VetoEventListener that can determine whether an event is published.
boolean subscribeVetoListenerExactly(java.lang.Class eventClass, VetoEventListener vetoListener)
eventClass
- the class of published objects that can be vetoedvetoListener
- The vetoListener that can determine whether an event is published.
boolean subscribeVetoListener(java.lang.String topic, VetoTopicEventListener vetoListener)
topic
- the name of the topic listened tovetoListener
- The vetoListener that can determine whether an event is published.
boolean subscribeVetoListener(java.util.regex.Pattern topicPattern, VetoTopicEventListener vetoListener)
topicPattern
- the RegEx pattern to match topics withvetoListener
- The vetoListener that can determine whether an event is published.
boolean subscribeVetoListenerStrongly(java.lang.Class eventClass, VetoEventListener vetoListener)
unsubscribeVetoListener(Class,VetoEventListener)
is
called.
eventClass
- the class of published objects to listen tovetoListener
- The vetoListener that will accept the events when published.
boolean subscribeVetoListenerExactlyStrongly(java.lang.Class eventClass, VetoEventListener vetoListener)
unsubscribeVetoListener(Class,VetoEventListener)
is
called.
eventClass
- the class of published objects to listen tovetoListener
- The vetoListener that will accept the events when published.
boolean subscribeVetoListenerStrongly(java.lang.String topic, VetoTopicEventListener vetoListener)
unsubscribeVetoListener(String,VetoTopicEventListener)
is
called.
topic
- the name of the topic listened tovetoListener
- The topic vetoListener that will accept or reject publication.
subscribeVetoListenerStrongly(Class,VetoEventListener)
boolean subscribeVetoListenerStrongly(java.util.regex.Pattern topicPattern, VetoTopicEventListener vetoListener)
unsubscribeVetoListener(Pattern,VetoTopicEventListener)
is
called.
topicPattern
- the RegEx pattern that matches the name of the topics listened tovetoListener
- The topic vetoListener that will accept or reject publication.
subscribeVetoListenerStrongly(Pattern,VetoTopicEventListener)
boolean unsubscribeVetoListener(java.lang.Class eventClass, VetoEventListener vetoListener)
eventClass
- the class of published objects that can be vetoedvetoListener
- The vetoListener that will accept or reject publication of an event.
boolean unsubscribeVetoListenerExactly(java.lang.Class eventClass, VetoEventListener vetoListener)
eventClass
- the class of published objects that can be vetoedvetoListener
- The vetoListener that will accept or reject publication of an event.
boolean unsubscribeVetoListener(java.lang.String topic, VetoTopicEventListener vetoListener)
topic
- the name of the topic that is listened tovetoListener
- The vetoListener that can determine whether an event is published on that topic
boolean unsubscribeVetoListener(java.util.regex.Pattern topicPattern, VetoTopicEventListener vetoListener)
topicPattern
- the RegEx pattern matching the name of the topics listened tovetoListener
- The vetoListener that can determine whether an event is published on that topic
<T> java.util.List<T> getSubscribers(java.lang.Class<T> eventClass)
eventClass
- the eventClass of interest
<T> java.util.List<T> getSubscribersToClass(java.lang.Class<T> eventClass)
eventClass
- the eventClass of interest
<T> java.util.List<T> getSubscribersToExactClass(java.lang.Class<T> eventClass)
eventClass
- the eventClass of interest
<T> java.util.List<T> getSubscribers(java.lang.reflect.Type type)
type
- the type of interest
<T> java.util.List<T> getSubscribers(java.lang.String topic)
topic
- the topic of interest
<T> java.util.List<T> getSubscribersToTopic(java.lang.String topic)
topic
- the topic of interest
<T> java.util.List<T> getSubscribers(java.util.regex.Pattern pattern)
pattern
- the RegEx pattern that was subscribed to
<T> java.util.List<T> getSubscribersByPattern(java.lang.String topic)
topic
- a topic to match Patterns against
<T> java.util.List<T> getVetoSubscribers(java.lang.Class<T> eventClass)
eventClass
- the eventClass of interest
<T> java.util.List<T> getVetoSubscribersToExactClass(java.lang.Class<T> eventClass)
eventClass
- the eventClass of interest
<T> java.util.List<T> getVetoSubscribersToClass(java.lang.Class<T> eventClass)
eventClass
- the eventClass of interest
<T> java.util.List<T> getVetoEventListeners(java.lang.String topicOrPattern)
getVetoSubscribersToTopic(String)
and getVetoSubscribersByPattern(String)
Misnamed method, should be called getVetoSubscribers(String)
. Will be deprecated in 1.5.
topicOrPattern
- the topic or pattern of interest
<T> java.util.List<T> getVetoSubscribersToTopic(java.lang.String topic)
topic
- the topic of interest
<T> java.util.List<T> getVetoSubscribers(java.util.regex.Pattern pattern)
pattern
- the RegEx pattern for the topic of interest
<T> java.util.List<T> getVetoSubscribersByPattern(java.lang.String topic)
topic
- the topic to match the pattern string subscribed to
<T> java.util.List<T> getVetoSubscribers(java.lang.String topic)
getVetoSubscribersToTopic(String)
.
Out of sync with getSubscribers(String)
.
topic
- the topic exactly subscribed to
void clearAllSubscribers()
void setDefaultCacheSizePerClassOrTopic(int defaultCacheSizePerClassOrTopic)
defaultCacheSizePerClassOrTopic
- the cache size per eventint getDefaultCacheSizePerClassOrTopic()
void setCacheSizeForEventClass(java.lang.Class eventClass, int cacheSize)
eventClass
- the class of eventcacheSize
- the number of published events to cache for this eventint getCacheSizeForEventClass(java.lang.Class eventClass)
eventClass
- the class of event
setCacheSizeForEventClass(Class,int)
void setCacheSizeForTopic(java.lang.String topicName, int cacheSize)
topicName
- the topic namecacheSize
- the number of published data Objects to cache for this topicvoid setCacheSizeForTopic(java.util.regex.Pattern pattern, int cacheSize)
pattern
- the pattern matching topic namescacheSize
- the number of data Objects to cache for this topicint getCacheSizeForTopic(java.lang.String topic)
topic
- the topic name
setCacheSizeForTopic(String,int)
,
setCacheSizeForTopic(java.util.regex.Pattern,int)
<T> T getLastEvent(java.lang.Class<T> eventClass)
eventClass
- an index into the cache
<T> java.util.List<T> getCachedEvents(java.lang.Class<T> eventClass)
eventClass
- an index into the cache
java.lang.Object getLastTopicData(java.lang.String topic)
topic
- an index into the cache
java.util.List getCachedTopicData(java.lang.String topic)
topic
- an index into the cache
void clearCache(java.lang.Class eventClass)
eventClass
- the event class to clear the cache forvoid clearCache(java.lang.String topic)
topic
- the topic name to clear the cache forvoid clearCache(java.util.regex.Pattern pattern)
pattern
- the pattern to match topic caches tovoid clearCache()
boolean unsubscribe(java.lang.Class eventClass, java.lang.Object subscribedByProxy)
eventClass
- class this object is subscribed to by proxysubscribedByProxy
- object subscribed by proxy
boolean unsubscribeExactly(java.lang.Class eventClass, java.lang.Object subscribedByProxy)
eventClass
- class this object is subscribed to by proxysubscribedByProxy
- object subscribed by proxy
boolean unsubscribe(java.lang.String topic, java.lang.Object subscribedByProxy)
topic
- the topic this object is subscribed to by proxysubscribedByProxy
- object subscribed by proxy
boolean unsubscribe(java.util.regex.Pattern pattern, java.lang.Object subscribedByProxy)
pattern
- the RegEx expression this object is subscribed to by proxysubscribedByProxy
- object subscribed by proxy
boolean unsubscribeVeto(java.lang.Class eventClass, java.lang.Object subscribedByProxy)
eventClass
- class this object is subscribed to by proxysubscribedByProxy
- object subscribed by proxy
boolean unsubscribeVetoExactly(java.lang.Class eventClass, java.lang.Object subscribedByProxy)
eventClass
- class this object is subscribed to by proxysubscribedByProxy
- object subscribed by proxy
boolean unsubscribeVeto(java.lang.String topic, java.lang.Object subscribedByProxy)
topic
- the topic this object is subscribed to by proxysubscribedByProxy
- object subscribed by proxy
boolean unsubscribeVeto(java.util.regex.Pattern pattern, java.lang.Object subscribedByProxy)
pattern
- the RegEx expression this object is subscribed to by proxysubscribedByProxy
- object subscribed by proxy
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


In the Udacity course the talk about the analogy of a house. HTML is the structure and raw materials, CSS defines the colour and the finishings, and i guess the DOM would almost be like the plans or blueprints.
Boxifying Design is about breaking down a webpage into boxes
Content on a website is automatically placed into a boxes made up of padding, border and margin. These areas must be set.


CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] [ RECURSIVE ] VIEW name [ ( column_name [, ...] ) ]
[ WITH ( view_option_name [= view_option_value] [, ... ] ) ]
AS query
[ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
where view_option_name can be one of:
security_barrier [ boolean ]
check_option [ text (local or cascaded) ]
CREATE VIEW defines a view of a query. The view is not physically materialized. Instead, the query is run every time the view is referenced in a query.
CREATE OR REPLACE VIEW is similar, but if a view of the same name already exists, it is replaced. The new query must generate the same columns that were generated by the existing view query (that is, the same column names in the same order and with the same data types), but it may add additional columns to the end of the list. The calculations giving rise to the output columns may be completely different.
If a schema name is given (for example, CREATE VIEW myschema.myview ...) then the view is created in the specified schema. Otherwise it is created in the current schema. Temporary views exist in a special schema, so a schema name cannot be given when creating a temporary view. The name of the view must be distinct from the name of any other view, table, sequence, index or foreign table in the same schema.
If specified, the view is created as a temporary view. Temporary views are automatically dropped at the end of the current session. Existing permanent relations with the same name are not visible to the current session while the temporary view exists, unless they are referenced with schema-qualified names.
If any of the tables referenced by the view are temporary, the view is created as a temporary view (whether TEMPORARY is specified or not).
Creates a recursive view. The syntax
CREATE RECURSIVE VIEW name (columns) AS SELECT ...;
is equivalent to
CREATE VIEW name AS WITH RECURSIVE name (columns) AS (SELECT ...) SELECT columns FROM name;
A view column list must be specified for a recursive view.
The name (optionally schema-qualified) of a view to be created.
An optional list of names to be used for columns of the view. If not given, the column names are deduced from the query.
This clause specifies optional parameters for a view; the following parameters are supported:
This should be used if the view is intended to provide row-level security. See Section 38.5 for full details.
This parameter may be either local or cascaded, and is equivalent to specifying WITH [ CASCADED | LOCAL ] CHECK OPTION (see below). This option can be changed on existing views using ALTER VIEW.
A SELECT or VALUES command which will provide the columns and rows of the view.
This option controls the behavior of automatically updatable views. When this option is specified, INSERT and UPDATE commands on the view will be checked to ensure that new rows satisfy the view-defining condition (that is, the new rows are checked to ensure that they are visible through the view). If they are not, the update will be rejected. If the CHECK OPTION is not specified, INSERT and UPDATE commands on the view are allowed to create rows that are not visible through the view. The following check options are supported:
New rows are only checked against the conditions defined directly in the view itself. Any conditions defined on underlying base views are not checked (unless they also specify the CHECK OPTION).
New rows are checked against the conditions of the view and all underlying base views. If the CHECK OPTION is specified, and neither LOCAL nor CASCADED is specified, then CASCADED is assumed.
The CHECK OPTION may not be used with RECURSIVE views.
Note that the CHECK OPTION is only supported on views that are automatically updatable, and do not have INSTEAD OF triggers or INSTEAD rules. If an automatically updatable view is defined on top of a base view that has INSTEAD OF triggers, then the LOCAL CHECK OPTION may be used to check the conditions on the automatically updatable view, but the conditions on the base view with INSTEAD OF triggers will not be checked (a cascaded check option will not cascade down to a trigger-updatable view, and any check options defined directly on a trigger-updatable view will be ignored). If the view or any of its base relations has an INSTEAD rule that causes the INSERT or UPDATE command to be rewritten, then all check options will be ignored in the rewritten query, including any checks from automatically updatable views defined on top of the relation with the INSTEAD rule.
Use the DROP VIEW statement to drop views.
Be careful that the names and types of the view's columns will be assigned the way you want. For example:
CREATE VIEW vista AS SELECT 'Hello World';
is bad form in two ways: the column name defaults to ?column?, and the column data type defaults to unknown. If you want a string literal in a view's result, use something like:
CREATE VIEW vista AS SELECT text 'Hello World' AS hello;
Access to tables referenced in the view is determined by permissions of the view owner. In some cases, this can be used to provide secure but restricted access to the underlying tables. However, not all views are secure against tampering; see Section 38.5 for details. Functions called in the view are treated the same as if they had been called directly from the query using the view. Therefore the user of a view must have permissions to call all functions used by the view.
When CREATE OR REPLACE VIEW is used on an existing view, only the view's defining SELECT rule is changed. Other view properties, including ownership, permissions, and non-SELECT rules, remain unchanged. You must own the view to replace it (this includes being a member of the owning role).
Simple views are automatically updatable: the system will allow INSERT, UPDATE and DELETE statements to be used on the view in the same way as on a regular table. A view is automatically updatable if it satisfies all of the following conditions:
The view must have exactly one entry in its FROM list, which must be a table or another updatable view.
The view definition must not contain WITH, DISTINCT, GROUP BY, HAVING, LIMIT, or OFFSET clauses at the top level.
The view definition must not contain set operations (UNION, INTERSECT or EXCEPT) at the top level.
The view's select list must not contain any aggregates, window functions or set-returning functions.
The view must not have the security_barrier property.
An automatically updatable view may contain a mix of updatable and non-updatable columns. A column is updatable if it is a simple reference to an updatable column of the underlying base relation; otherwise the column is read-only, and an error will be raised if an INSERT or UPDATE statement attempts to assign a value to it.
If the view is automatically updatable the system will convert any INSERT, UPDATE or DELETE statement on the view into the corresponding statement on the underlying base relation.
If an automatically updatable view contains a WHERE condition, the condition restricts which rows of the base relation are available to be modified by UPDATE and DELETE statements on the view. However, an UPDATE is allowed to change a row so that it no longer satisfies the WHERE condition, and thus is no longer visible through the view. Similarly, an INSERT command can potentially insert base-relation rows that do not satisfy the WHERE condition and thus are not visible through the view. The CHECK OPTION may be used to prevent INSERT and UPDATE commands from creating such rows that are not visible through the view.
A more complex view that does not satisfy all these conditions is read-only by default: the system will not allow an insert, update, or delete on the view. You can get the effect of an updatable view by creating INSTEAD OF triggers on the view, which must convert attempted inserts, etc. on the view into appropriate actions on other tables. For more information see CREATE TRIGGER. Another possibility is to create rules (see CREATE RULE), but in practice triggers are easier to understand and use correctly.
Note that the user performing the insert, update or delete on the view must have the corresponding insert, update or delete privilege on the view. In addition the view's owner must have the relevant privileges on the underlying base relations, but the user performing the update does not need any permissions on the underlying base relations (see Section 38.5).
Create a view consisting of all comedy films:
CREATE VIEW comedies AS SELECT * FROM films WHERE kind = 'Comedy';
This will create a view containing the columns that are in the film table at the time of view creation. Though * was used to create the view, columns added later to the table will not be part of the view.
Create a view with LOCAL CHECK OPTION:
CREATE VIEW universal_comedies AS SELECT * FROM comedies WHERE classification = 'U' WITH LOCAL CHECK OPTION;
This will create a view based on the comedies view, showing only films with kind = 'Comedy' and classification = 'U'. Any attempt to INSERT or UPDATE a row in the view will be rejected if the new row doesn't have classification = 'U', but the film kind will not be checked.
Create a view with CASCADED CHECK OPTION:
CREATE VIEW pg_comedies AS SELECT * FROM comedies WHERE classification = 'PG' WITH CASCADED CHECK OPTION;
This will create a view that checks both the kind and classification of new rows.
Create a view with a mix of updatable and non-updatable columns:
CREATE VIEW comedies AS SELECT f.*, country_code_to_name(f.country_code) AS country, (SELECT avg(r.rating) FROM user_ratings r WHERE r.film_id = f.id) AS avg_rating FROM films f WHERE f.kind = 'Comedy';
This view will support INSERT, UPDATE and DELETE. All the columns from the films table will be updatable, whereas the computed columns country and avg_rating will be read-only.
Create a recursive view consisting of the numbers from 1 to 100:
CREATE RECURSIVE VIEW nums_1_100 (n) AS VALUES (1) UNION ALL SELECT n+1 FROM nums_1_100 WHERE n < 100;


Links to wonderful organizations
There are many great organizations that I interact with as a supporter or member. You are welcome to ask me more about them or how to get involved as well. Below are some of them:
-
Girls Outdoor Adventure in Leadership and Science (GOALS) is an organization that provides a free 2-week backpacking trip with a field-science flare to underrepresented 10th graders in the Sacramento area. We also provide mentorship to the scholars in the following school year. I have worked on the curriculum team and I am currently a mentor.
-
I ride the bus to get from Sacramento to UC Davis campus, which is cheap and fast. UC Davis was going to erradicate the service as we knew it and active riders quickly mobilized to fight it. Due to our work, we saved our express and affordable transit line, which will impact hundreds of riders each week for years to come. I had the privledge to work with such an amazing group. See more at acrossthecauseway.com.
-
The Carpentries is an organization run by volunteers that promotes data and software literacy to the community. I am a certified Carpentries Instructor and I have taught R carpentries workshops on the UC Davis campus.
-
Hands-down the coolest place in Davis is the UC Davis Craft Center. If you are ever thinking of attending or working at UC Davis, you should check this place out. There are classes for pottery, woodworking, glass, metal, and more. I learned how to weld in their metal studio and I hope to learn how to blacksmith too!
-
I have been a member of the Rizzo Lab since Fall of 2016. We generally study forest disease systems, which brings together a set of plant pathologists, ecologists, and people who wear both hats.
-
I have also been a member of the Graduate Group in Ecology since Fall of 2016. It’s a very supportive group of students and faculty. There’s a wide breadth of expertise, meaning you can likely find the help you need right on campus.


Organisational Chart
Sheev Palpatine
Manager
Employee ID: 66
Email Address:
<EMAIL_ADDRESS>Office number:<PHONE_NUMBER>
Anakin Skywalker
Engineer
Employee ID: 123
Email Address:
<EMAIL_ADDRESS>GitHub Account:
github.com/Darth-Vader
Luke Skywalker
Engineer
Employee ID: 456
Email Address:
<EMAIL_ADDRESS>GitHub Account:
github.com/Last-Jedi
Obi-wan Kenobi
Engineer
Employee ID: 42356
Email Address:
<EMAIL_ADDRESS>GitHub Account:
github.com/High-Ground
C3PO
Intern
Employee ID: 333
Email Address:
<EMAIL_ADDRESS>School: Phantom Menace
R2D2
Intern
Employee ID: 001
Email Address:
<EMAIL_ADDRESS>School: AotC


Aleia's Notes : From Side Hustle to Full-Time
You need to control your web presence and I want to make it easier for you to do that. If you see something you like, drop me a note. If you don’t, drop me a note and I can work with you to create a custom package.


In the JMockit toolkit, the Annotations API provides support for the creation of state-based tests. The focus when doing this kind of testing is not on the interactions between objects, but on their state after the code under test is exercised, and on the data items exchanged between objects.
Regular state verification, performed after exercising the unit under test, is typically done through JUnit/TestNG assertions written at the end of each test method. The Annotations API extends the ability of a test to do state verification, by allowing those same JUnit/TestNG assertions to be executed whenever a dependency is invoked from the tested code. As the tested unit passes data to dependencies through method and constructor invocations, the corresponding mock implementations specified for those dependencies get called. These implementations (usually defined inside test classes) will then execute the appropriate assertions on the received invocation arguments. In addition, the API allows the test to verify if any given method or constructor of a mocked dependency is called at all, or more generally to verify the actual number of invocations against an specified exact, minimum, or maximum number of invocations.
For the remaining of this chapter, lets say we want to write unit tests for an application that uses the
javax.security.auth.login.LoginContext class (from the standard JAAS API) in order to authenticate users.
In this case, we don't want our tests to actually execute any of the real JAAS code, since it may
depend on external configuration and might not easily work in a developer testing environment.
Besides, we also don't want to exercise real JAAS code in a unit test because obviously that is
not part of the application code we are trying to test.
(Of course, in integration tests we just might work with a real JAAS setup.)
Therefore, an application class depending on LoginContext
will be our "unit under test",
while the LoginContext
class (the dependency) will need to have at least some of its
methods and constructors "mocked" for any given test which involves authentication logic.
In the context of the JMockit Annotations API, a mock method is one annotated with the
mockit.Mock
annotation.
The class to which such methods belong is a mock class.
For short, in this chapter we will refer to such annotated mock methods simply as "mocks" (in other contexts, the
word "mock" may refer to an instance of a mocked class instead).
The example below shows several mocks defined in a mock class.
public static class MockLoginContext
{
@Mock
public void $init(String name, CallbackHandler callbackHandler)
{
assertEquals("test", name);
assertNotNull(callbackHandler);
}
@Mock
public void login() {}
@Mock
public Subject getSubject() { return null; }
}
Mock classes are often defined as nested classes inside a JUnit/TestNG test class.
That's why this example mock class is declared to be static
; it could also have been
an inner (non-static) class.
There is nothing preventing mock classes from being top-level, though.
That would be useful if the mock class is to be reused in multiple test classes.
As we'll see later, though, the most convenient way to implement mock classes is by making them
anonymous and local to an individual test method.
A new mock class is created (as part of the test code) when we have a "real class" defined in
production code which needs to be mocked for a given test.
By convention, for a real class named Abc
we create a corresponding mock class named
MockAbc
(when using named mock classes, that is).
This is just a convention, though. A mock class in fact is completely independent from whichever real class it
targets. It should define at least one mock method, and may have any number of additional methods and constructors;
it can also define any number of fields.
For each mock method, on the other hand, there must exist a "real method/constructor" with the
same signature in the targeted real class. For a mocked method, the signature consists of the
method name and parameters; for a mocked constructor, it's just the parameters, with the mock method having
the special name "$init
".
If the real method/constructor corresponding to a given mock method is missing from the real class, an
IllegalArgumentException
will be thrown when a test attempts to apply the mock class to the
corresponding real class (the next section discusses how exactly this is done).
Notice this exception can be caused by a refactoring in the real class (such as renaming the real method), so it's
important to understand why it happens.
Finally, notice there is no need to have mocks for all methods and constructors in a real class. Any such method or constructor for which no corresponding mock exists in the mock class will simply stay "as is", that is, it won't be mocked. This, of course, assuming there isn't some other mock class applied by the same test to the same real class, something which is perfectly valid (and sometimes useful). If two (or more) mock classes happen to be applied to the same real class for the same test, then such mock classes should avoid defining the same mock twice. In case a mock is duplicated, though, the "last" one to be applied wins.
When a mock class is applied to a real class, the latter gets the implementation of those methods and constructors which have corresponding mocks temporarily replaced/redefined with the implementations of the matching mock methods, as defined in the mock class. In other words, the real class becomes "mocked" for the duration of the test which applied the mock class, and will respond accordingly whenever it receives invocations during test execution. At runtime, what really happens is that the execution of a mocked method/constructor is intercepted and redirected to the corresponding mock method, which then executes and returns (unless an exception/error is thrown) to the original caller, without this one noticing that a different method was actually executed. Normally, the "caller" class is the one under test, while the mocked class is a dependency.
In the example above, we have three mock methods, with one of them (named "$init
") targeting a
constructor.
Since such mocks can be used to verify the "state" passed from the class/unit under test to its dependencies, we
commonly see JUnit/TestNG assertions in them.
Such assertions will verify that the input arguments are as expected. When one of them fails, the test will fail for
the same reason (and with the same AssertionError
).
Obviously, writing these assertions (if any) is up to the developer.
A mock method for a non-void
real method will have to return an appropriate value to the caller, based
on the requirements of the class under test.
When an exceptional situation is being tested, a mock method will typically throw an exception or error to simulate
that situation.
Later we will see concrete examples for all of these different test cases.
A given mock class must be applied to a corresponding real class to have any effect.
We call this "setting up" the mock class.
This is normally done for a specific test or set of tests. In the first case, it occurs inside
individual test methods. In the second one, a @BeforeMethod
(TestNG),
setUp()
(JUnit 3.8), or @Before
(JUnit 4) method can be used.
During the time a mock class is in effect, the methods and constructors of the real class which
have corresponding mocks will stay mocked, with any calls made on them automatically and
transparently redirected to the corresponding mocks for execution.
There are several different ways to set up mock classes, each with a different way to specify the
corresponding real class, as we'll now see.
For the MockLoginContext
mock class above, the corresponding real class is
javax.security.auth.login.LoginContext
.
To set it up for an individual test, we could write the following (assuming the necessary imports):
@Test
public void setUpMocksForGivenRealClassWithGivenMockInstance() throws Exception
{
Mockit.setUpMock(LoginContext.class, new MockLoginContext());
// Inside an application class which creates a suitable CallbackHandler:
new LoginContext("test", callbackHandler).login();
...
}
Since the call above to Mockit.setUpMock
occurs inside a test method, the mocking of
LoginContext
by MockLoginContext
will be in effect only for this
particular test.
When the constructor invocation that instantiates LoginContext
executes, the corresponding
"$init
" mock method in MockLoginContext
will be executed, asserting the
validity of the invocation arguments.
Similarly, when the LoginContext#login
method is called, the corresponding mock method will be executed,
which in this case will do nothing since the method has no parameters and void
return type.
Notice the test instantiates the mock class and passes this instance in the call to
Mockit.setUpMock(Class> realClass, Object mock)
.
This mock instance will be the one on which any mock method (such as login
) is called.
The (partial) example test above would simply verify that the LoginContext
class is
instantiated with valid arguments when one particular constructor that takes a context name and a callback handler is
used.
If the class is not instantiated at all, the test would still pass (unless some other condition causes it to fail).
The invocation of the login
method also has no effect on the outcome of this test, except for the fact
that such an invocation will result in the execution of an empty mock method instead of the real method.
Now, what if we wanted to simulate an authentication failure for a different test?
The LoginContext#login()
method declares that it can throw a LoginException
"if the authentication fails", so what we need to do is very simple (using JUnit 4 in this example):
public static class MockLoginContextThatFailsAuthentication
{
@Mock
public void $init(String name) {}
@Mock
public void login() throws LoginException
{
throw new LoginException();
}
}
@Test(expected = LoginException.class)
public void setUpMocksForGivenRealClassWithoutPrecreatedMockInstance() throws Exception
{
Mockit.setUpMock(LoginContext.class, MockLoginContextThatFailsAuthentication.class);
// Inside an application class:
new LoginContext("test").login();
}
This test will only pass if the LoginContext#login
method throws an exception, which
it will when the corresponding mock method is executed.
Notice that in this case we passed the class literal for the mock class instead of an instance.
This will cause a new instance of the mock class to be created automatically every time
a non-static
mock method needs to be called (which happens whenever a mocked method
on the real class is called).
The mock method will be called on this new instance, which will then be discarded
(that is, it won't be reused later for new invocations).
Naturally, mock methods that are static
are never called on any instance, so no new
instance is created for them.
So far, we have only mocked public instance methods with public instance mock methods.
In reality, any other kind of method in a real class can be mocked: methods with
private
, protected
or "package-private" accessibility,
static
methods, final
methods, and native
methods.
(Also synchronized
and strictfp
methods, but these modifiers only
affect the method implementation, not its interface.)
Even more, an static
method in the real class can be mocked by an instance mock method, and
vice-versa (an instance real method with an static mock); the same applies for the final
modifier.
In a named mock class, mocks usually need to be declared as public
, otherwise an
IllegalAccessError
might get thrown.
@MockClass
annotation
The Mockit.setUpMock
method, in all of its two-parameter variations, requires the real class to be
explicitly provided through an argument.
The Mockit.setUpMocks
method, in contrast, takes only mock class literals and/or mock class instances.
The applicable real class is specified through the mockit.MockClass
annotation,
applied on the mock class itself, as the following example shows.
@MockClass(realClass = LoginContext.class)
public static class MockLoginContext
{
// @Mocks here...
}
@MockClass(realClass = SomethingElse.class)
public final class MockSomethingElse
{
// @Mocks here...
}
@Test
public void setUpMocksForMultipleClasses()
{
Mockit.setUpMocks(MockLoginContext.class, new MockSomethingElse());
// Calls code under test that uses the "LoginContext" and "SomethingElse" classes:
...
}
The realClass
attribute is mandatory for @MockClass
.
A mock class is normally used for the same real class every time. Therefore, nothing more natural
than associating said class directly with the mock class, avoiding the need to specify it every
time the mocks are set up.
Named mock classes, typically defined as nested or inner classes of the test class, definitely have their place. Often, however, an specific group of mocks for a given real class will be useful for a single test. In such a situation we can create anonymous mock classes inside individual test methods, as demonstrated by the next example.
@Test
public void setUpMocksUsingAnonymousMockClass() throws Exception
{
Mockit.setUpMock(LoginContext.class, new Object()
{
@Mock
void $init(String name) { assertEquals("test", name); }
@Mock
void login() {}
});
new LoginContext("test").login();
}
An anonymous mock class is always instantiated at the place of definition and cannot be annotated with
@MockClass
, so we need a mock setup mechanism that takes both the real class and the
mock instance.
A more elegant alternative to the use of Mockit.setUpMock
with an "in-line mock class" is shown next,
using the mockit.MockUp<T>
generic base class.
@Test
public void setUpMocksUsingLocalMockUpClass() throws Exception
{
new MockUp<LoginContext>()
{
@Mock
void $init(String name) { assertEquals("test", name); }
@Mock
void login() {}
};
new LoginContext("test").login();
}
In this case, we still have an anonymous mock class, but it is created as a subclass of
MockUp<T>
where the real class is specified through the generic
type parameter T
.
(Subclasses of MockUp
can also be named, of course.)
Given this succinct and readable syntax, and the fact that mock classes tend to be specific to individual tests, the
creation of such mock-up classes should be the most common way to define mocks with the Annotations API.
As the previous example tests have shown, it is perfectly safe to declare mock methods in an anonymous mock class as
non-public
(always).
This is an added bonus over annotated (and named) mock classes, which often (but not always) need to be public with
their mocks also public.
Most of the time a mock class targets a real class directly. But what if we need a mock object that implements a certain interface, to be passed to code under test? The two following example tests show how it is done, one using an annotated mock class, the other a mock-up class. The mocked interface is javax.security.auth.callback.CallbackHandler.
@Test
public void setUpMocksForInterface() throws Exception
{
CallbackHandler callbackHandler = Mockit.setUpMock(new MockCallbackHandler());
callbackHandler.handle(new Callback[] {new NameCallback("Enter name:")});
}
@MockClass(realClass = CallbackHandler.class)
public static class MockCallbackHandler
{
@Mock
public void handle(Callback[] callbacks)
{
assertEquals(1, callbacks.length);
assertTrue(callbacks[0] instanceof NameCallback);
}
}
@Test
public void mockInterfaceWithMockUp() throws Exception
{
CallbackHandler callbackHandler = new MockUp<CallbackHandler>()
{
@Mock
void handle(Callback[] callbacks)
{
assertEquals(1, callbacks.length);
assertTrue(callbacks[0] instanceof NameCallback);
}
}.getMockInstance();
callbackHandler.handle(new Callback[] {new NameCallback("Enter name:")});
}
The Mockit.setUpMock(Object)
method returns a proxy object that implements the desired interface, when the mock class
specifies that interface as the value of the realClass
attribute (if an actual class
is specified in the attribute, the method will apply the mock class and return null
).
The method accepts either an instance of the annotated mock class or the Class
literal for the same.
Again, a more elegant alternative is obtained with the use of a mock-up class, which provides
the proxy instance through a call to the getMockInstance()
method.
This method returns null
if the mocked type is not an interface.
Notice that for the first test the mock class and its mock methods are declared to be
public
and must be so to avoid an IllegalAccessError
, while in the
second test the mock-up class and the mock method don't have to be public (an anonymous
class is always non-public anyway).
The @MockClass
annotation also gives us the ability to specify methods and/or
constructors in the real class that should be stubbed out so they have no effect when
called during a test.
Stubbing out a method achieves the same result as mocking it with a mock method that does nothing, except for
returning the default value according to the method return type when it's not void
.
The following example tests make use of this feature.
@Test
public void mockAndStubOutClassAccordingToSpecifiedStubs() throws Exception
{
Mockit.setUpMocks(new MockLoginContextWithStubs());
LoginContext context = new LoginContext("");
context.login();
context.logout();
}
@MockClass(realClass = LoginContext.class, stubs = {"(String)", "logout"})
final class MockLoginContextWithStubs
{
@Mock
void login() {} // this could also have been an stub
}
@Test
public void mockAndStubOutClassAccordingToSpecifiedInverseStubs() throws Exception
{
Mockit.setUpMocks(MockLoginContextWithInverseStubs.class);
LoginContext context = new LoginContext("", null, null);
context.login();
context.logout();
}
@MockClass(realClass = LoginContext.class, stubs = "", inverse = true)
static class MockLoginContextWithInverseStubs
{
@Mock
static void login() {}
}
In the first test above, the constructor of the real class (LoginContext
) which has
one parameter of type String
is stubbed out, as well as all methods in the same
class with name logout
. Parameters are ignored if not specified in the stub filter,
so all overloads (in case there is more than one) with the same method name will be stubbed out.
The second mock class, MockLoginContextWithInverseStubs
, uses the
inverse
attribute (which by default is false
) to specify that all
methods and constructors not matching the specified stub filters will be stubbed out.
In this example, the list of stub filters contains only an empty filter which matches nothing, so everything in the
real class is stubbed out. Any mocks defined in the mock class will override the stub, however.
Each stub filter string specified with the stubs
attribute can match any number of
methods of the real class, since the initial part actually is a regular expression for method names.
For constructors, this part is left empty since they have no names.
The second part in a stub filter string, which can be empty for methods but never for
constructors, is a comma-separated list of parameter type names, between parentheses.
Each parameter type name either is the name of a primitive type, or a fully qualified reference type name.
For convenience, it can be a unique suffix for such type names instead; this makes it
easy to specify reference type names, since in most cases the package name can be omitted.
Finally, as seen in the example above, the empty stub filter will match no methods or
constructors in the real class, or all methods and constructors if used with inverse = true
.
All example tests shown so far only used JUnit/TestNG "asserts" to verify invocation arguments. This is the part of the API that extends conventional state-based testing to the data items exchanged between objects. Sometimes, though, we may want to verify if a given method/constructor in a dependency is invoked at all by the unit under test. We may also want to verify exactly how many invocations a given mock received during the execution of a test, or specify that the test should fail if more/less than a certain number of invocations occurs. For this, we can specify declarative constraints on the invocation count of a given mock, as the following example shows.
@Test
public void specifyInvocationCountConstraints() throws Exception
{
Mockit.setUpMock(LoginContext.class, new Object()
{
@Mock(minInvocations = 1)
void $init(String name) { assertEquals("test", name); }
@Mock(invocations = 1)
void login() {}
@Mock(maxInvocations = 1)
void logout() {}
});
new LoginContext("test").login();
}
(In the test above we used an anonymous mock class with the setUpMock
method,
although a nicer solution could be obtained with a local MockUp
object.)
In this test we used all three attributes of the @Mock
annotation related to
invocation counts.
The first mock specifies that the LoginContext(String)
constructor must be invoked
at least once during the test.
The second one specifies that the login()
method must be invoked exactly once, while the third
declares that logout()
can be invoked, but not more than once.
It is also valid to specify both minInvocations
and maxInvocations
on
the same mock, in order to constrain the invocation count to a given range.
When a class in production code performs some work in one or more static initialization blocks, we often
need to stub it out so it doesn't interfere with test execution.
To do just that for a given real class, we can write something like
@MockClass(realClass = MyRealClass.class, stubs = "<clinit>")
.
If we instead want some test code to execute when the static initialization of the real class
gets executed by the JVM, then we can define an special mock, as shown below.
@Test
public void mockStaticInitializer()
{
new MockUp<ClassWithStaticInitializers>()
{
@Mock(invocations = 1)
void $clinit()
{
// Do something here.
}
};
ClassWithStaticInitializers.doSomething();
}
We can even verify that static initialization occurs, as specified by the invocation count constraint above. Notice however that once loaded by the JVM, a class will be initialized no more than once, so the test would fail if it runs after the class has already been initialized.
We have already seen two different situations when mock classes get instantiated:
new
operator, and passed to JMockit in
a call to a Mockit.setUpMock
or Mockit.setUpMocks
method, or alternatively as a
MockUp
subclass instance.
In this case the same mock instance is used for all calls to instance mock methods, as long as the mock class
remains in effect.
Sometimes it may be important to have more control on when exactly a mock class is automatically instantiated by
JMockit.
There is also a situation which is not covered by the previously described instantiation mechanisms, and which may be
needed or useful for certain test cases: instantiation per mocked instance.
To cover such needs the @MockClass
annotation has an instantiation
attribute, whose values are given by the
Instantiation
"enum".
The default value for this attribute is Instantiation.PerMockInvocation
.
The following sub-sections describe each of the possible instantiation modes which can be used to control how and when JMockit creates automatic mock class instances. Notice this is applicable only to situation 2 above.
For a mock class annotated as
@MockClass(realClass = ..., instantiation = PerMockSetup)
,
a call like Mockit.setUpMock(realClass, MyMockClass.class)
or
Mockit.setUpMocks(MyMockClass.class)
will result in the creation of the mock
instance at the time of the call.
This single mock instance will then be used for all instance method invocations, for as long as
the mock class remains in effect.
Notice this is equivalent to passing an instance created by test code in one of those mock setup calls.
For a mock class annotated as
@MockClass(realClass = ..., instantiation = PerMockInvocation)
,
a call like Mockit.setUpMock(realClass, MyMockClass.class)
or
Mockit.setUpMocks(MyMockClass.class)
will not result in the creation of any
mock instance at this time, but will later if and when an instance mock method needs to be invoked.
For each such invocation, a new mock instance is created and then discarded as soon as the mock call terminates.
Notice this is the default JMockit behavior when a class literal for the mock class is passed in
a mock setup call, and the instantiation
attribute isn't specified.
For a mock class annotated as
@MockClass(realClass = ..., instantiation = PerMockedInstance)
,
a call like Mockit.setUpMock(realClass, MyMockClass.class)
or
Mockit.setUpMocks(MyMockClass.class)
will result in the on-demand creation
of one new mock instance for each and every new mocked instance (ie, an instance of the real class).
In other words, once the mock class is in effect, whenever a mocked instance method of the real
class is invoked, a paired instance of the mock class will be created if none yet exists for that
particular instance of the real class; this same mock instance will then be used for all
invocations to mock instance methods.
The ability to have a mock class instance for each real class instance will normally only be useful if the mock class stores some state that is specific to each instance of the real class.
Notice the mock object lifetime described above can only be achieved by using this particular instantiation mode.
As we have seen, there is a relationship between mocked instances (that is, instances of real classes which have been mocked) and mock instances (instances of mock classes). Mock instances can be created explicitly in test code, or automatically by JMockit according to the instantiation mode of the mock class. Mocked instances are created inside tested code, or in test code so they can be passed to tested code.
For certain use cases, a mock method executing on a mock instance may need access to the
corresponding mocked instance.
This can be achieved by declaring an instance field of name it
in
the mock class, with the type of the mocked real class.
Every time a mocked instance method is redirected to execute the corresponding mock instance
method, the it
field on the mock instance will be set to the mocked instance.
If a mocked constructor has a corresponding $init
mock method, then the
field will be set to the newly created (and uninitialized) instance.
In practice, the use of an it
field by itself is uncommon, so the following example
test is a contrived (although interesting) one. The next section describes a more likely use for such fields.
@Test
public void accessMockedInstanceThroughItField() throws Exception
{
final Subject testSubject = new Subject();
new MockUp<LoginContext>()
{
LoginContext it;
@Mock(invocations = 1)
void $init(String name, Subject subject)
{
assertNotNull(name);
assertSame(testSubject, subject);
setField(it, subject); // forces setting of private Subject field, since no setter is available
}
@Mock(invocations = 1)
void login()
{
assertNull(it.getSubject()); // getSubject() returns null until the subject is authenticated
setField(it, "loginSucceeded", true); // private field set to true when login succeeds
}
@Mock(invocations = 1)
void logout()
{
assertSame(testSubject, it.getSubject());
}
};
LoginContext theMockedInstance = new LoginContext("test", testSubject);
theMockedInstance.login();
theMockedInstance.logout();
}
The example above (which is an actual test in JMockit's own test suite) used a mock-up class, but
annotated and regular anonymous mock classes can also declare an it
field.
The setField
methods used in this test are statically imported from the
mockit.Deencapsulation
utility class, and are only used here to make the test more
meaningful.
The local variable theMockedInstance
contains the instance which the it
field will be set to on the mock-up instance, for each of the three mock invocations in this particular test.
Usually, a reentrant method is one which can be re-entered once it is already executing. Recursive methods, for example, are typically reentrant. A reentrant mock method is similar, but instead of causing itself to be re-entered, it causes the corresponding mocked method to be re-entered; and when this happens the original code of the real method is executed, without going through the mock again.
If the mock is an instance method mocking a real instance method, it will need access to the
mocked instance in order to call back the mocked instance method.
For this, the mock class will need to declare an appropriate it
field.
A mocked method which has a reentrant mock will have different behavior than if it had a regular
mock, so we use the @Mock(reentrant = true)
annotation
attribute to tell JMockit about our intentions.
The example test below exercises a LoginContext
object created normally (without any
mocking in effect at creation time), using an unspecified configuration
.
(For the complete version of the test, see the
mockit.MockAnnotationsTest
class.)
@Test
public void reenterMockedMethodsThroughItField() throws Exception
{
// Create objects to be exercised by the code under test:
LoginContext loginContext = new LoginContext("test", null, null, configuration);
// Set up mocks:
ReentrantMockLoginContext mockInstance = new ReentrantMockLoginContext();
// Exercise the code under test:
assertNull(loginContext.getSubject());
loginContext.login();
assertNotNull(loginContext.getSubject());
assertTrue(mockInstance.loggedIn);
mockInstance.ignoreLogout = true;
loginContext.logout(); // first entry, won't re-enter
assertTrue(mockInstance.loggedIn);
mockInstance.ignoreLogout = false;
loginContext.logout(); // second entry, will re-enter
assertFalse(mockInstance.loggedIn);
}
static final class ReentrantMockLoginContext extends MockUp<LoginContext>
{
LoginContext it;
boolean ignoreLogout;
boolean loggedIn;
@Mock(reentrant = true)
void login() throws LoginException
{
try {
it.login(); // re-enters the mocked method, executing the real code
loggedIn = true;
}
finally {
// This is here just to show that arbitrary actions can be taken inside the mock,
// before and/or after the real method gets executed.
System.out.println("Login attempted for " + it.getSubject());
}
}
@Mock(reentrant = true)
void logout() throws LoginException
{
// A reentrant mock execution can re-enter the mocked method or not, based on a condition.
if (!ignoreLogout) {
it.logout();
loggedIn = false;
}
}
}
In the example above, all real code exercised by the test actually gets executed, even though some methods
(login
and logout
) are mocked.
The example indeed is contrived; in practice, reentrant mocks would not normally be useful for testing per
se, not directly at least.
You may have noticed that a reentrant mock effectively behaves like advice (from AOP jargon) for the corresponding real method. This is a powerful ability that can be useful for certain things. JMockit itself uses mock classes containing reentrant mocks to provide integration with the JUnit and TestNG test runners.
Most tests will probably only use dedicated mock classes, specifically created for each particular test. There will be times, though, when the same mock class can be reused by multiple test methods, either in a single test class or across the entire test suite. We will now see different ways to set up mocks so they are shared by a whole group of tests, as well as ways to define reusable mock classes.
In a given test class, we can define instance methods that will run before and after each test
method (even when the test throws an error or exception).
In JUnit 3.8, these are the setUp()
and tearDown()
method overrides.
In JUnit 4.x we use the @Before
and @After
annotations on one or more arbitrary instance methods of the test class. The same applies to the
@BeforeMethod
and @AfterMethod
annotations of TestNG.
Any mock class that can be applied from inside a test method can also be applied from a "before" method, using one of the "set-up" methods or by instantiating a mock-up class. Such a mock class will remain in effect for the execution of all test methods in the test class. The only difference of applying mocks in a "before" method is that they also remain in effect inside "after" methods, if any.
For example, if we wanted to mock the LoginContext
class with a mock-up class for a bunch
of related tests, we would have the following methods in the test class:
public class MyTestClass
{
@Before
public void setUpSharedMocks()
{
new MockUp<LoginContext>()
{
// shared mocks here...
};
}
// test methods that will share the mocks set up above...
}
If we had an annotated mock class instead of a mock-up, the set up would be done with a
Mockit.setUpMocks(NamedMockClass.class)
call or with a Mockit.setUpMock
variant.
The example above uses JUnit 4, but the equivalent code for JUnit 3.8 or TestNG would be almost the same.
It is also valid to extend from base test classes, which may optionally define "before" and/or "after" methods containing calls to the Annotations API.
Named mock classes of all kinds (annotated with @MockClass
or not, mock-up classes)
can be designed as concrete (and optionally final
) classes that are then used in specific tests.
When instantiated directly by test code, such mock instances can be configured through constructor arguments, fields,
or non-mock methods.
Alternatively, they can be designed as base classes (possibly abstract
) to be extended by concrete mock
classes inside specific test classes or methods.
The example tests for this section come from JMockit's own test suite. They exercise the following class, partially reproduced here:
public final class TextFile
{
// fields and constructors that accept a TextReader or DefaultTextReader object...
public List<String[]> parse()
{
skipHeader();
List<String[]> result = new ArrayList<String[]>();
while(true) {
String strLine = nextLine();
if (strLine == null) {
closeReader();
break;
}
String[] parsedLine = strLine.split(",");
result.add(parsedLine);
}
return result;
}
// private helper methods that call "skip(n)", "readLine()", and "close()"...
public interface TextReader
{
long skip(long n) throws IOException;
String readLine() throws IOException;
void close() throws IOException;
}
static final class DefaultTextReader implements TextReader
{
DefaultTextReader(String fileName) throws FileNotFoundException { ...mocked... }
public long skip(long n) throws IOException { ...mocked... }
public String readLine() throws IOException { ...mocked... }
public void close() throws IOException { ...mocked... }
}
}
Some of the tests for the class above are as follows.
public final class TextFileUsingMockUpsTest
{
// A reusable mock-up class to be directly instantiated in specific tests.
static final class MockTextReaderConstructor extends MockUp<DefaultTextReader>
{
@Mock(invocations = 1)
void $init(String fileName) { assertThat(fileName, equalTo("file")); }
}
@Test
public void parseTextFileUsingDefaultTextReader() throws Exception
{
new MockTextReaderConstructor();
new MockTextReaderForParse<DefaultTextReader>() {};
List<String[]> result = new TextFile("file", 200).parse();
// assert result from parsing
}
...
The test above uses two reusable mock classes. The first one encapsulates a mock for the single constructor of the
TextFile.DefaultTextReader
nested class.
Any tests exercising code in the TextFile
class that invokes this constructor will
therefore use this mock class.
And since it is a mock-up class, it can be applied through simple instantiation inside the test method.
The second mock class used by the test targets the same DefaultTextReader
class.
As we see next, it defines mocks for a whole different set of members, which happen to be the methods called from
the TextFile#parse()
method.
...
// A reusable base mock class to be extended in specific tests.
static class MockTextReaderForParse<T extends TextReader> extends MockUp<T>
{
static final String[] LINES = { "line1", "another,line", null};
int invocation;
@Mock(invocations = 1)
long skip(long n)
{
assertEquals(200, n);
return n;
}
@Mock(invocations = 3)
String readLine() throws IOException { return LINES[invocation++]; }
@Mock(invocations = 1)
void close() {}
}
...
The mock-up class above, like the mockit.MockUp<T>
class which it extends, is
generic.
In this particular case, this is necessary because the tested TextFile
class works
with two different types for the "text reader" dependency:
TextFile.TextReader
(an interface which client code can implement), and
TextFile.DefaultTextReader
(an internal default implementation of the interface).
The previous test simply used this mock class as is, by defining an anonymous subclass which specifies the
type to be mocked as the DefaultTextReader
concrete class.
The next test, on the other hand, passes a TextReader
implementation to
TextFile
:
...
@Test
public void parseTextFileUsingProvidedTextReader() throws Exception
{
TextReader textReader = new MockTextReaderForParse<TextReader>() {}.getMockInstance();
List<String[]> result = new TextFile(textReader, 200).parse();
// assert result from parsing
}
...
The interface implementation, in this case, is a mock proxy object obtained through the
MockUp<T>#getMockInstance()
method.
Finally, we get to a more interesting case, where the concrete mock subclass actually overrides some of the mocks inherited from the base mock class:
...
@Test
public void doesNotCloseTextReaderInCaseOfIOFailure() throws Exception
{
new MockTextReaderConstructor();
new MockTextReaderForParse<DefaultTextReader>()
{
@Override @Mock
String readLine() throws IOException { throw new IOException(); }
@Override @Mock(invocations = 0)
void close() {}
};
TextFile textFile = new TextFile("file", 200);
try {
textFile.parse();
fail();
}
catch (RuntimeException e) {
assertTrue(e.getCause() instanceof IOException);
}
}
}
The test forces an IOException
to be thrown in the first call to readLine()
.
(This exception will get wrapped in a RuntimeException
by the parse
method.)
It also specifies, through an invocation count constraint, that the close()
method should never be
called.
This shows that not only the behavior of the inherited mock is overridden, but also any of the metadata specified
through the @Mock
annotation.


Meerkat
Central
this
very
important.
sifangti.club
baidu
ol one
ol two
ol three
ul one
ul two
ul three


Matrix Multiplication Calculator " Matrix A dimensions: " 1 2 3 1 2 3 " Matrix B dimensions: " 1 2 3 1 2 3


Passwords must be at least 8 characters long, contain at least one number, one uppercase character and one lowercase character.