Author: steveh
Date: Tue Nov 16 15:27:21 2004
New Revision: 76055
Added:
incubator/beehive/site/src/documentation/content/xdocs/controls/controlsOverview.xml
(contents, props changed)
incubator/beehive/site/src/documentation/content/xdocs/controls/controlsProgramming.xml
(contents, props changed)
Log:
Forrest XML versions of Kyle's ControlsOverview and ControlsProgramming docs.
Added:
incubator/beehive/site/src/documentation/content/xdocs/controls/controlsOverview.xml
==============================================================================
--- (empty file)
+++
incubator/beehive/site/src/documentation/content/xdocs/controls/controlsOverview.xml
Tue Nov 16 15:27:21 2004
@@ -0,0 +1,423 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V1.2//EN"
"http://forrest.apache.org/dtd/document-v13.dtd">
+<document>
+ <header>
+ <title>Controls Overview</title>
+ </header>
+ <body>
+ <section>
+ <title>Overview</title>
+ <section>
+ <title>Problem: Complexity -- Learning Curve </title>
+ <p>
+J2EE provides a rich set of component types, protocols, and system services
that can be used to assemble an application or service</p>
+ <p>
+ <strong>
+As the scope of the J2EE architectural design space has grown, the complexity
of assembling solutions has also grown.</strong>
+ </p>
+ <p>Many of the basic building blocks provide their own set of
mechanisms for how J2EE abstractions are accessed, how usage is parameterized,
and how resources associated with them (connections, sessions, etc) are
managed.</p>
+ <p>
+An objective of the J2EE community is to expand beyond the Java system
software developer that has traditionally built J2EE solutions to enfranchise a
new type of developer: the corporate developer. The corporate developer is
often a very strong programmer, but may have significantly less experience with
object-oriented design, building distributed systems, and Java/J2EE.</p>
+ <p>
+ <strong>The goal is to enable a collaboration where the
base J2EE distributed system architecture and back-end components can be
designed and built by the J2EE system software developer, then assembled into
exposed web user interfaces, web services, or applications by the corporate or
application developer.
+</strong>
+ </p>
+ <p>But the complexity and diversity of J2EE client access
models stands in direct opposition to achieving this goal. Depending upon the
system architecture and components constructed by the system developer, the
application developer might have to learn a variety of new technologies and
APIs to work within the architecture.
+</p>
+ <p>Consider a simple example: A systems developer has built a
distributed system where synchronous services are exposed as Enterprise
JavaBeans and asynchronous services are exposed via JMS queues. A corporate
developer new to J2EE is tasked with building a web user interface that
integrates with these services.
+</p>
+ <p>To accomplish his task, the corporate developer now has to
learn how to:</p>
+ <ul>
+ <li>Create a JNDI context and lookup resources. If
resources are app-scoped, then how to provide the appropriate deployment
descriptor configuration.</li>
+ <li>How to use home/business interfaces of exposed EJBs to
access business methods, including understanding differences in usage depending
upon whether the exposed EJBs are Stateless Session Beans, Stateful Session
Beans, or Entity Beans.</li>
+ <li>How to obtain JMS connections/sessions, and references
to queues.</li>
+ <li>How to construct and enqueue a JMS message.</li>
+ <li>How to properly manage the resources associated with
the above, such that vital system resources (such as connections) are used
efficiently and correctly. The cost of a subtle mistake can be poor system
performance or even system failure.</li>
+ </ul>
+ <p>
+What initially appears to be a simple task in the abstract (call these EJBs or
enqueue a message that looks like this) can devolve into hours or days or
reading J2EE HowTo books and Javadoc API references, getting the right
deployment descriptor values configured, and calling all the right APIs, at all
of the right times, in the right order. In the resulting application or
service, often the directly application-related code (i.e. calling the bean
business method or building message contents) is a small fraction of the total
code required to accomplish the task.</p>
+ <p>
+Here is an example of the code required to invoke a single method on an
exposed EJB using standard J2EE APIs: </p>
+ <source>Trader trader = null;
+try
+{
+ InitialContext ic = new InitialContext();
+ TraderHome home = (TraderHome)ic.lookup("MyTraderBean");
+ Trader trader = home.create();
+ TradeResult tradeResult = trader.buy(stock, shares);
+ return tradeResult;
+}
+catch (NamingException ne)
+{
+ ...
+}
+finally
+{
+ if (trader != null)
+ trader.remove();
+}</source>
+ <p>A common solution to this problem is often to task the J2EE
professional developer with constructing facades or custom frameworks that hide
some of the underlying complexity and resource access mechanisms and provides
appropriate guarantees that system resources (connections, sessions, handles,
etc) are utilized properly. But constructing these intermediate abstractions is
an inefficient use of (an often scarce and expensive) systems development
resources. Depending upon the "thickness" of the intermediate abstractions,
this approach can also have performance or application deployment footprint
implications. </p>
+ </section>
+ <section>
+ <title>Solution: Controls -- Unified Client Programming Model
</title>
+ <p>Controls reduce the complexity and learning curve
associated with acting as a client of J2EE resources by providing a unified
client model that can provide access to diverse types of resources.</p>
+ <p>
+ <strong>To the client, Controls appear as JavaBeans that
can be instantiated and used for resource access.</strong>
+ </p>
+ <p>Properties that parameterize resource access can be set
using JSR-175 metadata attributes, as arguments to factory-based instantiation,
or even bound using externalized configuration data. These configuration
mechanisms are consistent across all resource types, and Controls provide the
appropriate mapping to resource-type-specific APIs or deployment descriptor
entries. </p>
+ <p>
+Controls present operations on the resource as methods on the JavaBean
interface. They also support a two-way communication style where resource
events can be delivered to a registered listener.</p>
+ <p>
+ <strong>
+Controls provide a consistent model for discovering the configuration options,
operations, and events exposed by a resource. </strong>
+ </p>
+ <p>
+Controls can also provide transparent (to the client) resource management of
connections, sessions, or other resources to be obtained on behalf of the
client, held for an appropriate resource scope to achieve best performance, and
then released. This resource management mechanism frees the client from having
to learn or understand the acquisition mechanisms, and from having to directly
participate in guaranteeing their release. The Controls architecture provides
this functionality by defining a simple resource management contract that can
cooperate with an outer container to manage resources at the appropriate scope
(for example, bounded to a transaction context or outer container operation or
request scope).</p>
+ <p>
+Using a Control that exposes the Trader EJB in the earlier example, the code
to invoke the buy() method on this bean can become:</p>
+ <p>The TraderBean Control fully encapsulates the JNDI lookup
as well as the home/bean interface operations needed to get an instance of the
Trader EJB and invoke the buy() method on it, and exposes the JNDI name of the
EJB as a property that can be set either programmatic, via metadata, or using
an external deployment descriptor. </p>
+ <p>
+Controls also provide an extensibility model that allows customized view of a
resource to be constructed, with discrete operations defined as methods on the
control. For example, it is possible to define a custom operation on a Control
type representing a JMS queue resource, that uses metadata attributes to define
the format of the message, with message contents set from message parameters.
This enables the professional developer (or even the corporate developer) to
construct new customized facades for resource access with a minimum of effort.
</p>
+ <p>Weblogic Workshop Controls can be considered a "proof of
concept" for the Controls architecture. Workshop Controls have used similar
techniques to provide a base mechanism for unified access to:</p>
+ <ul>
+ <li>Enterprise JavaBeans</li>
+ <li>JMS Queues and Topics</li>
+ <li>Web Services</li>
+ <li>Database Access via JDBC</li>
+ <li>Enterprise Resources via JCA</li>
+ </ul>
+ <p>
+ <strong>The goal of the Controls architecture is not to
define the standards for how specific resource types will be exposed; rather,
it is to guarantee that when exposed they will have a commonality in mechanism
that makes them easier to understand and use by developers.</strong>
+ </p>
+ </section>
+ <section>
+ <title>Problem: Resource Diversity -- Tooling Challenges
</title>
+ <p>
+Beyond adding to overall complexity, the diversity of J2EE resource types and
access mechanisms also makes it difficult for tools to offer assistance to
developers who need to use them.</p>
+ <p>
+ <strong>
+
+For existing client models, the configuration of resource access is often some
combination of resource-specific API usage and deployment descriptor entries.
This generally requires custom IDE code that is knows how to generate the right
(resource-specific) code or configuration entries.</strong>
+ </p>
+ <p>Specific resource types often need custom code in order to
define wizards or property-driven user interface that aids in the process of
defining a client of the resource. There is no common mechanism for discovering
the potential set of configurable attributes for a resource type. This means
that any graphical presentation of client attributes or wizards must be
custom-authored based upon resource type.
+</p>
+ <p>
+Once configured, there is the secondary problem of how the IDE represents a
configured client resource in source form. There are at least two potential
options: save the attributes as generated source code and/or deployment
descriptor entries that are resource-specific or define a canonical
representation that is native to the IDE. Both are problematic. Two-way editing
can be difficult, if the canonical format is generated source code or
descriptors are visible to the end user and directly editable. Using some
IDE-specific canonical representation (either based upon a closed framework or
configuration data) means the configured client abstraction isn't portable to
other development environments or editable outside of the IDE. </p>
+ <p>
+Using the IDE to develop directly to native resource APIs or descriptor
formats is also lacking in that it doesn't necessary have an associated
constraint or extensibility model. If a resource should be consistently
accessed with a particular configuration or expected semantics, there is no
good way to describe resource constraints for clients or to enforce that they
are followed. A concrete example is a JMS queue where it is expected that
messages will always conform to a specific format or contain an expected set of
properties. There is no good way of representing this constraint to the client,
or of enforcing that it consistently following, short of runtime errors when it
is not. </p>
+ <p>
+The lack of a single canonical representation also makes it difficult for the
systems developer to collaborate with the corporate developer, short of
constructing and exposing custom facades for client access. But even then,
there is the IDE problem of knowing what facades are available, and how they
should be configured and used once selected.</p>
+ <p>
+ <strong>
+Without any well-defined source format for representing client resource
configuration, packaging models, or discovery mechanisms, there is no
non-proprietary way for the IDE to present the notion of configured resources,
nor to pre-configure client access to resources.</strong>
+ </p>
+ </section>
+ <section>
+ <title>Solution: Controls -- Unified Tooling Model </title>
+ <p>Controls, like the JavaBeans upon which they are built, are
designed for tooling. Beyond the common programming model presented to
developers, Controls also offer resource discovery and property introspection
mechanisms that allow an IDE to locate available Controls and present and
interactively configure their properties.
+
+</p>
+ <p>
+ <strong>Because Controls expose operations, events, and
properties using common mechanisms, an IDE can support client use cases based
upon these mechanisms as well as a common authoring model for defining new
types of Controls, without the need for a large amount of resource-specific
code.
+</strong>
+ </p>
+ <p>
+Using a common client model allows a single base of IDE code to allow the use
of a variety of resource types, based upon introspection. Using a shared model
(and code) for presenting and configuring client access also results in a
consistent user experience when working with resources, both on the client and
authoring side. While the developer might be using a diverse set of resources
in the course of building a user interface, service, or application, the
learning curve from a user interaction perspective can be reduced in the same
way that it is reduced from an API perspective by having a common model.
+</p>
+ <p>
+ <strong>Controls extend the base properties support of
JavaBeans to add support for metadata-based (JSR-175) attributes, constraints,
and an extensibility model, allowing an IDE to define new Control types that
are pre-configured for specific resource access use cases.
+
+</strong>
+ </p>
+ <p>The earlier programming example showed a simple customized
Control defined to access an Enterprise JavaBean advertised at a particular
JNDI location. This example could easily have been constructed by an IDE using
JMX to explore advertised EJBs on a J2EE server, and then generating the
necessary Control definition that exposes the EJB with the specific
home/business interfaces represented as operations on the bean and the correct
JNDI location pre-configured as an attribute.
+</p>
+ <p>
+
+The Controls architecture supports the definition of configuration options
list for a particular Control type. This lists the base set of properties that
are associated with the type and can be used to:</p>
+ <ul>
+ <li>Specify the attributes in the set that can be
configured using JSR-175 metadata, and the syntax for doing so. This enables an
IDE to present property-style selection of metadata-based attributes and
values, as well as providing the ability to validate the annotations on any
usage of the type and relationships between annotations.
+</li>
+ <li>Specify the attributes in the set that should be
settable dynamically using property getters/setters on instances of the type.
This can be used to support auto-generation of Control types with property
accessors based upon the attribute set.
+</li>
+ <li> Derive a schema for representing the configuration of
the attribute set using XML. These can be used in common tools for state
management (to persist the representation of a Control instance and its
attributes as XML) as well as in an externalized configuration mechanism that
allows attributes to be bound externally using deployment descriptor-style
configuration files. This makes the construction of instance introspectors and
administrative tools much more straightforward, as compared to using ad-hoc
deployment descriptor formats.
+
+</li>
+ </ul>
+ <p>Controls also provide a JAR-based packaging mechanism, for
how Control types can be discovered within a jar. </p>
+ <p><strong>
+The Controls architecture provides a well-defined packaging model that enables
system vendors, 3rd party providers, or J2EE system developers (in the
collaborative scenario) to distribute controls that offer client access to
provided services or components. An IDE can then discover packaged controls to
present them in a palette or list of available resource types for client use.
+</strong></p>
+
+
+
+ </section>
+ </section>
+ <section>
+ <title>The Controls Architecture</title>
+<p>The following picture shows the basic runtime architecture and the
relationships between a resource client, the associated Control, and the
accessed J2EE resource:</p>
+<p>todo: image</p>
+<p>The Resource Client represents user code in a web application, service, or
application that needs access to the J2EE resource. The Resource Client and
supporting Control will always live in the same virtual machine and communicate
directly using local Java method invocation. The accessed resource may or may
not reside within the same virtual machine, depending upon the nature of the
resource and the application server environment. </p>
+<p>
+Dynamic property accessors and resource operations are exposed on the Control
and used by the client to initiate resource access. Data from the resource may
be returned as return values from operations or fired as events on the bean
event interface to registered listeners. </p>
+<p>
+Resource access may be parameterized by JSR-175 metadata declared directly on
the Control instance, class, or method declarations, or by properties provided
to the factory-based constructor. In addition to this, there is an external
configuration model for how properties can be bound from external configuration
(ex. deployment descriptors), enabling deploy-time binding of attributes.
Examples of resource attributes that might be parameterized by metadata or
external configuration or JNDI names associated with resources, resource or
protocol configuration, message formats, etc. </p>
+<p>
+The Control itself will often hold a reference to a resource proxy associated
with the accessed resource, and will use the proxy to enact operations
requested by the client. Examples of resource proxies are EJB home or remote
stubs, JMS connections or sessions, web service client proxies, etc. The
Control manages the state and lifetime of this proxy reference, coordinated by
a set of resource management notification events that are provided to it
indicating how long the proxy resources can be held by an outer container that
determines the resource scope.
+</p>
+<p>
+The actual communication between the resource proxy and the resource itself is
generally a function of the underlying resource. For EJBs, it might reflect
communication via RMI or local Java invocation, for web services it might be
service invocation based upon</p>
+<p>
+The following sections describes some of the key features and attributes of
the Controls Architecture:
+</p>
+ <section>
+ <title>Operations and Events</title>
+ <p>
+Controls support a two-way interaction style with resource clients. The set of
operations callable by the client are defined on the base public interface for
the control, and the set of possible callbacks (events) that might be delivered
back to the client from the resource are defined, by convention, on an optional
inner Callback interface of the base public interface</p>
+<p>
+Here is a simple example that represents the client interface to a timer
service resource:
+</p>
+<source>
+
+public interface TimerControl extends Control
+{
+ public void start() throws IllegalStateException;
+ public void stop();
+ public interface Callback
+ {
+ public void onTimeout(long time);
+ }
+} </source>
+<p>In this example, TimerControl is the base public interface for timer
Control. The TimerControl supports operations related to setting and using a
timer (start, stop), as well as a single event (onTimeout) that will be
delivered when the timer fires.
+</p>
+
+
+
+ </section>
+ <section>
+ <title> Public Interface / Private Implementation /
ControlBean Wrapper </title>
+<p>The definition of a new resource type in the Control architecture is
composed of three distinct classes:
+</p>
+<ul>
+ <li>The public Control Public Interface defines the set of operations and
events that are exposed for the resource type. In the earlier TimerControl
example, TimerControl is the public resource interface for the timer service
resource.</li>
+
+ <li>The private Control Private Implementation class provides the
implementation of resource operations as well as proxy resource management. In
the TimerControl example, there would be a class (TimerControlImpl) that
provides the implementation of the timer operations using the supporting
resources of a J2EE timer service.</li>
+
+ <li>The Control Bean Wrapper class is the JavaBean wrapper around the
implementation class that provides the property accessor implementation,
per-instance storage of dynamic properties, and property resolution services.
It performs event listener routing and initialization of contextual services
and nested Controls.</li>
+</ul>
+<p>The relationship and functions of these classes is summarized in the
following diagram: </p>
+<p>todo: image</p>
+<p>
+The following picture shows how these 3 classes work together to fulfill the
runtime responsibilities shown in the earlier architecture diagram:
+</p>
+<p>image: todo</p>
+
+ </section>
+ <section>
+ <title>A Flexible Property Model </title>
+<p>A key aspect of the Controls architecture is a flexible configuration model
for how resource access attributes will be resolved. Properties can be used to
parameterize resource access, providing attributes such as JNDI names for local
resources, web service URLs, connection attributes, etc.
+</p>
+<p>
+It must be possible to introspect a bean and set the available set of
properties. Additionally, Controls need to move beyond the traditional property
setter/getter to provide some additional capabilities:</p>
+<ul>
+ <li> Enables the assignment of Control properties using JSR-175 metadata
attribute declarations on Control classes, instances, or methods.
+</li>
+
+ <li>Provides a consistent externalized property binding model, so resource
attributes can be managed without requiring changes to source code. </li>
+</ul>
+<p>The three property configuration mechanisms (programmatic property
accessors on the Control, JSR-175 metadata on Control declarations, and
external deployment descriptor-style configuration) have a well-defined
property resolution precedence that is implemented and enforced by the Control
base implementation. The precedence (from highest to lowest) is:
+</p>
+<ul>
+ <li>Programmatically set property value</li>
+
+ <li>Externally configured property value</li>
+
+ <li>Metadata-defined property value</li>
+</ul>
+<p>
+In other words, the resource client can override a value defined by either
externalized configuration or metadata, and a value defined in externalized
configuration can override a metadata-defined value.
+</p>
+<p>
+To ensure that this flexibility is not misused where it is not desirable, it
is also possible to declaratively specify the mechanisms that can be used to
set attribute values. So an attribute could be marked as 'read-only' from a
programmatic perspective, and would only have a getter and not a setter, or a
metadata-based attribute could be marked as bound in a 'final' way that
prevents override by either external configuration or programmatic mechanisms.
This is useful in the previously described collaborative scenario, where the
J2EE Systems Developer who is responsible for resource access definitions via
Controls might want to constrain the flexibility that the consumer (the
Corporate Developer) has in modifying those definitions upon use.
+</p>
+<p>In the earlier TimerControl example, an attribute might exist to set the
timeout value of the timer. For this attribute, it should be possible to set
the value programmatically, externally, or using declarative annotations.</p>
+<p>
+The declaration of the TimerControl JSR-175 attribute and member might look
something like:
+</p>
+<source>Package com.myco;
+public @interface Timer {
+
+ /** @return timeout Duration as string */
+ @AccessModes (property-style=true, external=true) String timeOut();
+...
+ }</source>
+ <p>
+This defines a metadata attribute (com.myco.Timer) that has a String member
value named 'timeOut'. The AccessModes meta-attribute specifies that the member
can be set via JavaBean property-style accessors and external configuration, as
well as using declarative metadata.
+</p>
+<p>An example of setting the timeOut member of the Timer metadata attribute
inside of client code might look like:
+</p>
+<source>@Timer(timeout="3 seconds")
+public TimerControlBean myTimerBean;
+</source>
+<p>
+Because the AccessModes attribute indicates that a property-style accessors
are enabled, the TimerControlBean will also advertise the following JavaBean
property accessor methods: </p>
+<source>Public String getTimeOut();
+public void setTimeOut(String timeout);</source>
+<p>
+This accessor could be used from client code, as in the following example:
+</p>
+<source>myTimerBean.setTimeout("3 seconds");</source>
+<p>
+Finally, there will also be a derived XML schema for external configuration of
the Control based upon the set of properties that are defined as externally
configurable. This schema is derived from the metadata attribute definition,
not authored directly.
+</p>
+<p>
+The configuration of the timeout member based upon external configuration
would look something like: </p>
+<source>…
+ <timer:timer xmlns:timer="http://openuri.org/com/myco/TimerControl">
+ <timer:timeOut>3 seconds</timer:timeOut>
+ </timer:timer>
+…</source>
+<p></p>
+
+ </section>
+ <section>
+ <title>Resource Views: Extensibility by Interface</title>
+ <p>Controls also support an extensibility model that allows
operations on a resource to be defined using a customized interface that
extends the base public resource interface, and defines metadata-annotated
operations on the resource. This enables the construction of "views" or
specific resource use cases, defining a more-specific set of resource
operations or events. </p>
+ <p>As an example, imagine there is a basic DatabaseControl
that provides simplified database access using JDBC, and hides and manages the
details of how JDBC connections are acquired and released from the client
programmer.
+</p>
+ <p>
+This Control could also define an extensibility model that allows the
execution of JDBC PreparedStatements as operations on an extended interface,
and marshals the returned ResultSet back to native Java types. When extended in
this manner, the resulting extended control presents a view of the JDBC
resource as a set of methods that result in the execution of predefined
PreparedStatements.
+</p>
+ <p>
+An example of the customized interface for this Control might look like:
+</p>
+ <source>public interface CustomerDatabase extends
ControlExtension, DatabaseControl
+{
+ @sql statement="INSERT INTO CUSTOMERDB (ID, NAME) VALUES ({id},
{name})"
+ int newCustomer(int id, String name) throws SQLException;
+
+ @sql statement="SELECT * FROM CUSTOMERDB WHERE ID = {id}"
+ Customer findCustomer(int id);
+}</source>
+ <p>
+In this simple example, each operation on the interface corresponds to a SQL
prepared statement to be executed. Metadata attributes on the methods are used
to define the additional semantics required, in this case the actual SQL
statement to invoke. </p>
+ <p>
+Support for Extensibility by Interface is optional. The Control author has
full control of whether extensibility is or is not supported, as well as the
ability to define and implement resource-specific semantics associated with
extended operations on the control type.
+</p>
+ </section>
+ <section>
+ <title>Contextual Services</title>
+<p>Given their use case (resource access), it should be possible to use
Controls from a variety of different runtime contexts: within web tier
containers (servlets, JSP, JSF), within web services, standalone Java
applications, even from within EJBs. Given this diverse set of contexts,
Controls need to have a flexible model for how they integrate with any outer
container or component model and for how services will be obtained from them.
+</p>
+<p>
+Controls may need access to contextual services to support resources. One
example of client-side contextual services might be security services to access
a credential repository or to provide data encryption/decryption services.
Services may be contextual, because the actual implementation might vary based
upon the type of container in which the Control is running. As an example, a
security contextual service might provide different implementations for
Controls running in the EJB tier (by delegating to an enclosing EJBContext) vs.
Controls running in the Servlet container vs. Controls running in a standalone
Java application.
+</p>
+<p>
+Contextual services can also define an event model, so contextual services can
also declare and fire events on Controls that have registered in interest. As
an example, a basic ControlContext contextual service is provided as part of
the base Controls architecture. This contextual service provides common
services for Controls, such as access to properties, as well as a set of
lifecycle events for Controls.
+</p>
+<p>
+The discovery and implementation model for Controls Contextual Services will
be based upon the JavaBeans Runtime Containment and Services Protocol (Glasgow)
(<link
href="http://java.sun.com/products/javabeans/glasgow/#containment">http://java.sun.com/products/javabeans/glasgow/#containment</link>)
that is already shipping as part of J2SE.
+</p>
+ </section>
+ <section>
+ <title>Resource Management</title>
+ <p>The Controls architecture defines a unique set of lifecycle
events and a resource management contract between Controls and the execution
container they are running within. There are three primary motivations for
this:</p>
+<ul>
+ <li>To enable the Control implementation to implicitly obtain supporting
client-side resources (connections, sessions, etc) on behalf of the client.</li>
+
+ <li>To enable the Control to hold these client-side resources for an
appropriate resource scope (across multiple client invocations) to achieve
optimal performance and utilization of resources
+</li>
+
+ <li>To ensure that client-side resources obtains on behalf of the client
are consistently released at the end of the appropriate resource scope.</li>
+</ul>
+<p>
+The key is that resource management should be transparent to the client. The
Control resource management design makes the Control implementation class the
responsible party, instead of the placing this burden upon the client of the
resource, which is the common approach associated with most J2EE resource
types. </p>
+<p>
+This is achieved by defining two basic lifecycle events that will be delivered
to the Control Implementation Class:
+</p>
+<ul>
+ <li>onAcquire: the onAcquire event is delivered to a resource
implementation on the first client invocation within a resource scope. This
provides an opportunity to obtain any basic client-side resources necessary to
support operations on the Control. For example, a Control that was providing
access to a JMS queue might use the onAcquire event to obtain a JMS connection,
session, and a reference to the target queue.
+</li>
+<li>onRelease: the onRelease event is guaranteed to be delivered to every
control implementation instance that has received an onAcquire event during the
current resource scope, at the end of that scope. This provides the opportunity
to release any of the resources obtained during onAcquire event processing. In
the previous example, the JMS connection and session could be appropriately
closed and the queue reference reset to null.</li>
+</ul>
+<p>
+The definition of resource scope is delegated to the outer container within
which the Control is executing. For example, if the Control is executing within
the web tier, the resource scope might be bounded by the duration of processing
of the current http request. For a Control running in the EJB tier, the
resource scope might be the current EJB method invocation or possibly even by
the current transaction context. </p>
+<p>
+The following diagram shows the basic mechanics of this contract:
+</p>
+<p>todo: image</p>
+<p>
+The Client Container has two basic responsibilities: to maintain an
accumulated list of Controls that have acquired resources, and to invoke
releaseResources API on each of them at the end of the appropriate resource
scope. The Control Bean is responsible for delivering the onAcquire event to
the Control Implementation instance, for notifying the Client Container that
resources have been obtained, and for delivering the onRelease event to the
implementation when notified by the Client Container.
+</p>
+<p>This diagram also demonstrates the transparency of resource management to
client code itself; the client is only invoking operations, and all of the
necessary underlying resource management is done by interactions between the
Client Container, Control Bean, and Control Implementation. </p>
+
+ </section>
+ <section>
+ <title>Composition Model</title>
+ <p>
+
+The Controls architecture also supports a composition model, so it is possible
to define a Control type that nests another Control type. This makes it
possible to extend a physical resource abstraction with a logical abstraction
that lives entirely on the client side. Composition is useful for the
construction of facades or to add additional client side operations, events, or
state to the nested Control abstraction. </p>
+<p>
+Composition of Controls is supported using the mechanisms defined by the
JavaBeans Runtime Containment and Services Protocol (Glasgow).
+</p>
+ </section>
+ <section>
+ <title>Packaging Model</title>
+ <p>The Controls architecture provides a simple JAR-based packaging
model that enables Controls to be packaged for distribution. The model defines
a simple manifest file that describes the set of Controls within a jar. Tools
can quickly introspect and build palettes of available controls based upon this
packaging model.</p>
+<p>
+It should be possible to place Control jar files at a variety of classloader
scopes (system, application, or module) for client use cases.
+</p>
+
+ </section>
+ </section>
+ <section>
+ <title>The Controls Client Model</title>
+ <p>The Controls architecture actually offers two related client
models with slight different characteristics:</p>
+ <ul>
+ <li>A programmatic client model, where the client explicitly
specifies Control instance attributes to factory-based constructors, and does
direct registration of event listeners and event handling.
+</li>
+
+ <li>A declarative client model, where Control instance
attributes are specified using JSR-175 metadata, and event routing is implicit
based upon a set of basic naming conventions.</li>
+ </ul>
+ <p>The two offer the same basic functionality; but in the
programmatic model the client takes explicit responsibility for construction of
Control instances and event routing; in the declarative model, the Control
container provides initialization and routing services on behalf of the client.
The programmatic model directly exposes the details of how initialization and
event handling takes place; it is likely a more comfortable environment for the
professional developer or one who is already comfortable with constructing and
handling events from JavaBeans. The declarative model hides many of these
details, making it much easier for corporate developers (and development tools)
to quickly declare and configure Control instances and create event handling
code to service events.
+</p>
+<p></p>
+ <section>
+ <title>Programmatic Client Model Example</title>
+ <p>
+The programmatic client model follows the basic pattern of JavaBeans
construction and event handling:
+</p>
+<source>TimerControlBean myTimerBean =
(TimerControlBean)ControlBean.instantiate(
+
classloader, "com.myco.TimerControlBean");
+myTimerBean.setTimeout("3 seconds");
+myTimerBeans.addTimerControlEventListener(
+ new TimerControlEventListener() // anonymous event handler class
+ {
+ public void onTimeout(long time)
+ {
+ // timer event handling code
+ }
+ }
+);</source>
+<p>
+In the example above, a factory-based instantiation API
(Controls.instantiate()) is used to construct a new instance of the
TimerControlBean. It is programmatically initialized to the desired
configuration, and then an event handler (based upon the declaration of an
anonymous inner class) is used to service events from the bean.
+</p>
+
+ </section>
+ <section>
+ <title>Declarative Programming Model Example</title>
+<p>
+The following example is equivalent to the preceding example, but uses
declarative style construction and event routing:
+</p>
+<source>@Timer(timeout="3 seconds") TimerControlBean myTimerBean;
+
+...
+
+public void myTimerBean_onTimeout(long time)
+{
+ // timer event handling code
+}</source>
+<p>In this example, the TimerControlBean instance is declared with attributes
specified using JSR-175 metadata. There is no implicit construction of the bean
instance; the client container for the ControlBean will recognize the presence
of the Control declaration and will implicitly initialize the instance.
Additionally, it (also implicitly) declares the necessary event listener class
and routing code to deliver onTimeout events on the TimerControlBean instance
to the declared event handler.</p>
+ </section>
+ </section>
+ </body>
+</document>
Added:
incubator/beehive/site/src/documentation/content/xdocs/controls/controlsProgramming.xml
==============================================================================
--- (empty file)
+++
incubator/beehive/site/src/documentation/content/xdocs/controls/controlsProgramming.xml
Tue Nov 16 15:27:21 2004
@@ -0,0 +1,1402 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V1.2//EN"
"http://forrest.apache.org/dtd/document-v13.dtd">
+<document>
+ <header>
+ <title>Beehive Controls Tutorial</title>
+ </header>
+ <body>
+ <section>
+ <title>1. Overview</title>
+ <p>The Control architecture is a lightweight component framework
based upon JavaBeans, which exposes a simple and consistent client model for
accessing a variety of resource types. Controls take the base functionality
of JavaBeans and add in the following unique new capabilities:</p>
+<ul>
+ <li>· Enhanced authoring model: uses a public interface contract and
an associated implementation class to enable generation of a supporting
JavaBean class for handling the details of property management and
initialization. </li>
+
+ <li>· Extensibility model: enables the construction of views and
custom operations (with implied semantics) on the Control using
metadata-annotated interfaces. </li>
+
+ <li>JSR-175 metadata attributes and external configuration data: provides
an enhanced configuration model for resource access.</li>
+</ul>
+<p>This document focuses on the Controls programming and configuration model
from two distinct perspectives:</p>
+<ul>
+ <li>· The authoring and extensibility model for defining a new type
of Control</li>
+
+ <li>· The client access model for declaring and using Controls</li>
+</ul>
+
+ <p>An overview of the Control architecture and toolable access models can
be found in the companion document entitled <link
href="controlsOverview.html">Control Overview: Providing Simplified and
Unified Access to J2EE Resources</link></p>
+ </section>
+
+ <section>
+ <title>2. An Example</title>
+ <p>In the course of describing the programming model for Controls,
this document builds upon an example Control that simplifies the enqueueing of
JMS messages with a specific format and set of properties. Once completed,
client code to accomplish this should be as straightforward as:</p>
+<p><strong>Enqueueing using OrderQueueBean (<em>Client Code</em>)</strong></p>
+<source>OrderQueueBean orderBean = (OrderQueueBean)
+
+java.beans.Beans.instantiate(“org.apache.beehive.controls.examples.OrderQueueBean”);
+Order order = new Order(myID, new String [ ] {“item1”, “item2”};
+OrderBean.submitOrder(order, “01-28-2004”);
+</source>
+<p>This document starts with a brief overview of the Control Authoring and
Client Programming Models to establish some basic context, eventually building
to enable the example above.</p>
+ </section>
+
+ <section>
+ <title>3. The Control Authoring Model</title>
+ <p>This section describes the basic authoring model for Controls.
This includes a description of the following elements:</p>
+ <ul>
+ <li><strong><em>Control Public Interface</em></strong>: source
file that defines the set of operations, events, extensibility model, and
properties associated with the Control type.</li>
+
+ <li><strong><em>Control Implementation Class</em></strong>:
source file that provides the implementation of the operations and
extensibility model described by the Control Public Interface.</li>
+
+ <li><strong><em>ControlBean Generated Class</em></strong>:
code-generated JavaBean class that is derived from the Control Public Interface
and the Control Implementation Class by a Control compiler.</li>
+ </ul>
+ <p>This authoring model is a departure from the traditional
JavaBeans programming model, which is largely based upon a set of conventions
that a bean author is expected to follow when constructing a new JavaBean type.
In the Controls model, the author defines operations, events, and properties
in an interface (Control Public Interface) and builds an underlying
implementation (Control Implementation Class). A Control compiler takes these
two elements and generates a specialized type of JavaBean (ControlBean
Generated Class), which represents the full client programmer’s view of the
Control.</p>
+<p> There are two primary advantages of this model:</p>
+<ul>
+ <li><strong>Simplicity.</strong> A key goal of any ease-of-use
programming model is to free the developer from worrying about plumbing.
Managing property values, event listener lists, and other basic JavaBean
functions are fairly rote from implementation to implementation. The Controls
architecture employs a unique variant of the Inversion of Control (IoC) design
pattern based on JSR-175 metadata. This enables a Control Implementation Class
to declaratively specify the events or services it requires to provide its
semantics. The ControlBean Generated Class acts as a lightweight container to
provide contextual hookup and implementation details.</li>
+ <li><strong>Consistency.</strong> Instead of trying to provide
consistency through convention, the Control compiler provides both verification
and code generation services to ensure that the resulting implementation
provides consistent APIs and behaviors for clients, tools, and application
deployers or administrators.</li>
+</ul>
+<p><strong>Diagram: Control Architecture Elements and Flow</strong></p>
+<p>todo: image</p>
+<p>The client will interact with the Control by invoking operations defined on
the Control Public Interface or dynamic property accessor methods on a
ControlBean instance. The client can also express interest in any events the
Control might generate by registering a listener to receive them.</p>
+<p>The following diagram represents the relationship between the Control
Public Interface, the Control Implementation Class, and the ControlBean
Generated Class:</p>
+<p><strong>Diagram: Relationships between Control Interface and
Classes</strong></p>
+<p>todo: image</p>
+<p>The Control Public Interface defines the operations on the Control and will
be implemented by both the Control Implementation Class and the ControlBean
Generated Class. The ControlBean Generated Class will also define property
accessor methods and internally will maintain the state of property values.
It will also maintain a reference to one (and only one) Control Implementation
instance. The Control Implementation instance, wrapped by a bean instance,
provides the actual implementation of resource semantics for the Control.</p>
+<p>The subsequent sections will outline the various characteristics of
Controls:</p>
+<ul>
+ <li>Declaration / Instantiation</li>
+ <li>Operations</li>
+ <li>Events</li>
+ <li>Contextual Services</li>
+ <li>Properties</li>
+ <li>Extensibility</li>
+ <li>Composition</li>
+ <li>Context Events</li>
+</ul>
+<p>Where applicable, the aspects of each of these characteristics will be
explored in two dimensions: from the perspective of a Control author who is
defining a new type of Control, and from the perspective of a Control client
that is using the services of an available Control type.</p>
+<p>To make the descriptions more concrete, the characteristics will be
presented within the context of a sample Control: the JmsMessageControl.
This Control will provide a simplified client access model for enqueuing
messages to a JMS queue or topic, freeing the client from having to learn the
nuances of JMS client programming.</p>
+ </section>
+
+ <section>
+ <title>4. The Control Client Models</title>
+ <p>There are actually two distinct programming models that may be
available to clients of Controls:</p>
+ <ul>
+ <li><strong>Declarative Model.</strong> Uses a
metadata-based variant of the Inversion of Control (IoC) design pattern to
allow a component author to declare Control instances, contextual services, and
event handlers using annotated fields and methods. The declarative model
simplifies client programming, because many of the details of initialization
and event routing are left to an external container supporting the model. A
declarative programming style is also more toolable, since it is much easier
for tools to manage and manipulate metadata rather than code.</li>
+ <li><strong>Programmatic Model.</strong> Uses the
traditional JavaBean-style APIs for acting as a client of a bean, including
factory-based constructor and event listeners. The programmatic model may be
more comfortable to the traditional Java programmer, who wants to see and be in
control of all the details. It also enables client use cases where there is
no supporting container for the declarative model.</li>
+ </ul>
+ <p>The programmatic client model is generally available in all
contexts where Controls might be used. It offers full generality, but leaves
many of the details up to the client programmer, such as initialization,
composition, and event handling wire-up.</p>
+<p>The declarative model hides many of these details. Based upon its use of
metadata it is also more tool friendly, allowing tools to present a view of the
client code without code analysis. </p>
+<p>The declarative model requires support of an outer container or
construction-time code that fulfills the contract implied by annotations on a
client class. </p>
+<p>The ControlBean itself provides this support, so the Control Authoring
Model is oriented towards using the declarative model, although programmatic
equivalents are generally available.</p>
+
+ </section>
+
+ <section>
+ <title>5. Defining a New Control Type</title>
+<p>Controls are designed to make it very easy for users (and tools) to define
new types of Controls. Control authors might be:</p>
+<ul>
+ <li>· System vendors exposing specific types of resources</li>
+
+ <li>· Application developers defining new types of logical resources
(possibly based upon physical ones)</li>
+
+ <li>Third-party software vendors, using Controls as a mechanism to
interface to components or subsystems they provide.</li>
+</ul>
+<p>In all instances, the goal of the Controls authoring model is to provide a
basic set of conventions and supporting tools to make it easy to author a new
Control type.</p>
+<p>To get started, a Control author would define the two basic artifacts: </p>
+<ul>
+ <li>· the Control Public Interface</li>
+
+ <li>· the Control Implementation Class</li>
+</ul>
+<p>For the JmsMessageControl, the declaration of the public interface might
look like:</p>
+<p><strong>Interface Declaration (Control Public Interface)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import org.apache.beehive.controls.api.bean.ControlInterface;
+
[EMAIL PROTECTED]
+public interface JmsMessageControl
+{
+ …
+}</source>
+ <p>The only basic rule for a Control Public Interface is that it must be
annotated by the org.apache.beehive.controls.api.bean.ControlInterface marker
interface.</p>
+ <p>The second source artifact a Control author would create to define a new
type of Control is the Control Implementation Class. This declaration of the
implementation class for our JmsMessageControl would look like:</p>
+<p><strong>Class Declaration (Control Implementation Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+public class JmsMessageControlImpl implements JmsMessageControl
+{
+ …
+}</source>
+<p>The only basic rule for a Control Implementation Class is that it must
always implement the associated Control Public Interface.</p>
+<p>From these two source files, the Control compiler will create a third
artifact, the ControlBean Generated Class. This class need not necessarily
ever appear within an application in source code form; but for the purposes of
explaining the overall architecture and client model, we will present source
examples of the derived ControlBean Generated Class. </p>
+<p>A Controls standard would focus only on the conventions for the external
attributes of ControlBean Generated Classes, not upon the internal
implementation. </p>
+<p>The ControlBean Generated Class for the JmsMessageControl would look
like:</p>
+<p><strong>Class Declaration (ControlBean Generated Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+public class JmsMessageControIBean implements JmsMessageControl
+{
+ private JmsMessageControlImpl _impl;
+
+ …
+}</source>
+<p>As shown above, the ControlBean Generated Class will also implement the
Control Public Interface. The sample also shows that the bean will hold a
private reference to an implementation instance used to support the bean.</p>
+ </section>
+
+ <section>
+ <title>6. Instantiating a Control</title>
+ <p>This section covers the client mechanisms for creating a new
instance of a Control. This can be done either programmatically or
declarative, if running inside a container that support declarative
initialization.</p>
+ <section>
+ <title>6.1 Declarative Instantiation</title>
+<p>The client model for Controls supports a declarative model for
instantiating a Control instance, when running in containers that support this
model. In this model, the client class can annotate fields on the class
using a special marker annotation
(org.apache.beehive.controls.api.bean.Control) that indicates that the fields
should be initialized to a ControlBean instance of the requested type.</p>
+<p>Here is an example of declarative instantiation:</p>
+<p><strong>Declarative Instantiation (Client Code)</strong></p>
+<source>Import org.apache.beehive.controls.api.bean.Control;
+
+public class PublisherControlImpl extends PublisherControl
+{
+ <strong>@Control
+ public JmsMessageControlBean myJmsBean;</strong>
+
+ …
+
+ public void someOperation()
+ {
+ myJmsBean.sendTextMessage(“A Text Message”);
+ }
+}</source>
+<p>This example shows a second Control Implementation Class
(PublisherControlImpl) that internally uses the services of JmsMessageControl
to enqueue a JMS message. The child Control field is not explicitly
initialized within the PublisherControl implementation class; by the time
someOperation() is called, it is guaranteed that the myJmsBean reference has
been initialized by the wrapping PublisherControlBean that contains the
implementation.</p>
+<p>It is also possible to parameterize the attributes of a Control at
construction time, again using metadata attributes. These attributes can be
placed on the field declaration (in addition to the @Control annotation) and
will be used to do construction-time initialization.</p>
+<p>The second example below shows initialization of the myJmsBean field again.
In this case, an initial value of the @Destination “name” attribute is
also provided using JSR-175 metadata:</p>
+<p><strong>Declarative Instantiation with Properties (Client Code)</strong></p>
+<source>public class PublisherControlImpl extends PublisherControl
+{
+ <strong>@Control @Destination(name=”InvoiceQueue”) </strong>
+ public JmsMessageControlBean myJmsBean;</source>
+ <p>This example performs <strong>exactly</strong> the same initialization
as the earlier declarative example, but does so using JSR-175 attribute syntax
instead of passing parameters to a factory-based constructor.</p>
+<p>The Controls architecture includes a mechanism for defining the expected
set of annotations that might appear on a Control field. This mechanism is
described in greater detail in the section on Properties.</p>
+ </section>
+ <section>
+ <title>6.2 Programmatic Instantiation</title>
+ <p>The client model for Controls supports instantiation of a
new Control instance using the same factory-based model supported by JavaBeans.
For example, the following code could be used to create a new instance of the
JmsMessageControlBean generated class:</p>
+<p><strong>Programmatic Instantiation (Client Code)</strong></p>
+<source>JmsMessageControlBean myJmsBean = (JmsMessageControlBean)
+ <strong>java.beans.Beans.instantiate(cl,
“org.apache.beehive.controls.examples.JmsMessageControlBean”);</strong></source>
+ <p>The Control runtime also provides an extended factory model that
allows metadata attributes to be passed into the factory constructor:</p>
+ <p><strong>Programmatic Instantiation with Properties (Client
Code)</strong></p>
+ <source>import org.apache.beehive.controls.api.bean.Controls;
+import org.apache.beehive.controls.api.properties.PropertyMap;
+
+PropertyMap jmsAttr = new (PropertyMap(JmsMessageControl.Destination.class);
+jmsAttr.setProperty(“name”, “InvoiceQueue”);
+JmsMessageControlBean myJmsBean = (JmsMessageControlBean)
+ <strong>Controls.instantiate(cl,
“org.apache.beehive.controls.examples.JmsMessageControlBean”,
jmsAttr);</strong> </source>
+ <p>In this example, the JmsMessageControlBean is being constructed with
the Destination “name” property set to “InvoiceQueue”. The
AttributeMap class is a simple helper class that can hold a set of name-value
pairs of a Control’s properties, which are initialized by the factory-based
constructor. More details on Controls properties are provided in a later
section.</p>
+ </section>
+ </section>
+
+ <section>
+ <title>7. Operations</title>
+ <p>Operations are actions that can be performed by a Control at
the client’s request. This section describes the authoring model for
declaring and implementing a Control operation, as well as the client model for
invoking operations on a ControlBean instance.</p>
+ <section>
+ <title>7.1 Declaring and Implementing Operations for a Control
</title>
+ <p>All methods declared or inherited (via extension) by the
Control Public Interface are considered to be Control operations. The
following example shows the definition of two operations on the
JmsMessageControl that will enqueue messages when invoked:</p>
+<p><strong>Declaring Operations (Control Public Interface)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import org.apache.beehive.controls.api.bean.ControlInterface
+
[EMAIL PROTECTED]
+public interface JmsMessageControl
+{
+ <strong>public void sendTextMessage(String text);
+ public void sendObjectMessage(Serializable object);</strong>
+
+ …
+}</source>
+<p>The Control Implementation Class implements the public interface for the
Control, defining the operation methods, and the body of these methods.</p>
+<p><strong>Implementing Operations (Control Implementation Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+public class JmsMessageControlImpl implements JmsMessageControl
+{
+ <strong>public void sendTextMessage(String text)
+ {
+ // Code to send a TextMessage to the destination
+ ….
+ }
+
+ public void sendObjectMessage(Serializable object)
+ {
+ // Code to send an ObjectMessage to the destination
+ ….
+ }</strong>
+}
+</source>
+<p>Finally, the ControlBean Generated Class will also implement all operations
(since it also implements the Control Public Interface). It will always
delegate to the implementation class for the actual implementation of the
operation; it might also perform additional container-specific pre/post
invocation processing.</p>
+<p>Here is a skeleton of what the generated ControlBean code might look like
for an operation:</p>
+<p><strong>Implemented Operations (ControlBean Generated Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+public class JmsMessageControlBean implements JmsMessageControl
+{
+ private JmsMessageControlImpl _impl;
+
+ <strong>public void sendTextMessage(String text)
+ {
+ ….
+ _impl.sendTextMessage(text);
+ ….
+ }
+
+ public void sendObjectMessage(Serializable object)
+ {
+ ….
+ _impl.sendObjectMessage(object);
+ ….
+ }</strong>
+</source>
+
+ </section>
+ <section>
+ <title>7.2 Invoking Operations on a Control</title>
+<p>The client model for invoking an operation on a Control is very
straightforward: simply call the method on a held ControlBean instance as
demonstrated by the following example:</p>
+<p><strong>Invoking an Operation (Client Code)</strong></p>
+<source> myJmsBean.sendTextMessage(“A Text Message”);</source>
+<p>The invocation model for operations is the same, whether the Control
instance was created using declarative or programmatic mechanisms.</p>
+ </section>
+ </section>
+
+ <section>
+ <title>8. Events</title>
+ <p>Events are notifications sent by the Control back to its client
whenever some condition has been met or internal event has taken place. A
client can express interest in a Control’s events by registering (either
explicitly or implicitly) to receive them, and can write event handler code to
be called when the event has taken place.</p>
+<p>This section describes the declaration model for events, how an authored
Control delivers them to a registered client, and the client code necessary to
register and receive events.</p>
+
+ <section>
+ <title>8.1 Declaring Events</title>
+<p>Events are declared on an inner interface of the Control Public Interface,
which is annotated with the org.apache.beehive.controls.api.events.EventSet
annotation. The following example shows the declaration of an event
interface for the JmsMessageControl, with a single event (onMessage):</p>
+<p><strong>Declaring Events (Control Public Interface)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import java.io.Serializable;
+import javax.jms.Message;
+import org.apache.beehive.controls.api.events.EventSet;
+import org.apache.beehive.controls.api.bean.ControlInterface;
+
[EMAIL PROTECTED]
+public interface JmsMessageControl
+{
+ public void sendTextMessage(String text);
+ public void sendObjectMessage(Serializable object);
+
+ @EventSet
+ <strong>public interface Callback
+ {
+ void onMessage(Message m);
+ }</strong>
+
+ …
+}</source>
+<p>If a Control Public Interface has defined an EventSet interface, then the
associated ControlBean Generated Class will have two public methods supporting
client listener management:</p>
+
+<p><strong>Event Listener Registration Methods (ControlBean Generated
Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import java.util.TooManyListenersException;
+
+public class JmsMessageControIBean implements JmsMessageControl
+{
+ …
+
+ /** Registers a new client listener for this bean instance */
+ <strong>public void addCallbackListener(Callback listener) throws
TooManyListenersException</strong>
+ {
+ ….
+ }
+
+ /** Deregisters a client listener for this bean instance */
+ <strong>public void removeCallbackListener(Callback listener)</strong>
+ {
+ ….
+ }
+}</source>
+<p>The name of the listener registration methods are based upon the name of
the associated EventSet interface. In the previous example, the EventSet
interface was named Callback, so the associated listener registration method
was addCallbackListener(), and the deregistration method was
removeCallbackListener().</p>
+<p>A Control Public Interface can have more than one inner interface that is
annotated as an EventSet interface. Each declared EventSet will have its own
independently managed list of registered listeners.</p>
+ </section>
+ <section>
+ <title>8.2 Firing Events</title>
+ <p>This section describes the mechanism available to a Control
author to deliver events to any registered client listener. <strong>An
initialized event proxy is created when the Control Implementation Class
declares a field of an EventSet interface type, and annotates it with the
org.apache.beehive.controls.events.Client annotation type.</strong> The
containing ControlBean will initialize this reference to a valid proxy
implementing the EventSet interface, and the Control Implementation Class can
use this proxy to fire events back to any registered client.</p>
+<p>This is demonstrated in the following sample code from the JmsControlBean
implementation class, which will fire an onMessage event back to any registered
client any time a message is enqueued:</p>
+
+<p><strong>Firing Events (Control Implementation Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import org.apache.beehive.controls.api.events.Client;
+
+public class JmsMessageControlImpl implements JmsMessageControl
+{
+ <strong>@Client Callback client;</strong>
+
+ public void sendTextMessage(String text)
+ {
+ // Code to construct and send a TextMessage to the destination
+ TextMessage m = …;
+ ….
+ <strong>client.onMessage(m);</strong>
+ }
+ …
+}</source>
+ </section>
+ <section>
+ <title>8.3 Listening for Events</title>
+ <p>The client of a Control can express an interest in
receiving events from a Control and write client event handlers to service them
once delivered. Two basic event handling mechanisms are supported: Java event
listeners or declarative event handlers (where supported by the client
container).</p>
+ <section>
+ <title>8.3.1 Declarative Implementation of Event
Handling</title>
+ <p>If the client code is implemented in a container that
supports the declarative programming model for Controls (such as the Control
Implementation Class itself), it can use a simplified convention for authoring
event handlers for a declared Control instance.</p>
+<p>If a Control is declared using the @Control marker interface, then
<strong>the user can declare event handlers for the Control by using the
EventHandler annotation type</strong>. These annotated methods will be
considered an event handler for the Control event, and the container will
automatically register for events and deliver them to this handler.</p>
+<p>The previous example could be rewritten using the declarative event
handling style as:</p>
+
+<p><strong>Declarative Handling of Events (Client Code)</strong></p>
+<source>
+import org.apache.beehive.controls.api.events.EventHandler
+
+public class PublisherControlImpl extends PublisherControl
+{
+ @Control
+ public JmsMessageControlBean myJmsBean;
+
+ <strong>@EventHandler (field=”myJmsBean”, evenSet=
JmsMessageControl.Callback.class,
+ eventName=”onMessage”)
+ public void myJmsBeanMessageHandler(Message m)
+ {
+ // Code implementing onMessage event handler
+ }</strong>
+ …
+}</source>
+
+ </section>
+ <section>
+ <title>8.3.2 Programmatic Implementation of Event
Handling</title>
+ <p>The programmatic style follows the tradition Java event
listener pattern. The client expresses its interest in receiving the event and
also authors a (often anonymous inner) class that implements the event
interface to receive events when delivered.</p>
+<p>This is shown by the following sample code:</p>
+
+<p><strong>Programmatic Handling of Events (Client Code)</strong></p>
+<source> myJmsBean.addCallbackListener(
+ new JmsMessageControl.Callback()
+ {
+ public void onMessage(Message m)
+ {
+ // Code implementing on Message event handler
+ }
+ });</source>
+<p>There is no requirement that an anonymous inner class be used. One
alternative would be to delegate to an instance of another class (as long as
that class implements the Callback interface). In the preceding example, if
event listening was implemented for the purposes of logging sent messages, and
MessageLogger class could be declared (implementing the Callback interface),
multiple beans could delegate to a single instance of this logging listener.</p>
+ </section>
+ </section>
+ </section>
+
+ <section>
+ <title>9. Contextual Services</title>
+ <p>The Control authoring model makes use of contextual services to
provide access to services from the current runtime environment of the
ControlBean. The model for contextual services is based upon the existing
standards for services in JavaBeans: The JavaBeans Runtime Containment and
Services Protocol. This protocol provides a base mechanism for a JavaBean to
locate and use services from the runtime environment, as well as an extensible
service provider model to enable new (or environment-specific) types of
services to be authored and made available to JavaBeans/Controls.</p>
+<p>A key aspect of this service model is that it can be contextual; for
example, it might be possible to write a basic security service interface that
provides logical role-checking functionality. The actual implementation of
this interface might vary for different runtime contexts: for example, the
role check might be done differently for a Control running within the context
of an EJB container (by delegating to the containing EJBContext) vs. a Control
running within the Web tier (by delegating to ServletHttpRequest services).</p>
+<p>Having an extensibility and service provider location model is important to
enable the following scenarios:</p>
+<ul>
+ <li>· The Control’s implementation is designed to run in a wide
variety of environments. It uses the contextual service mechanism to declare
its prerequisites and receive a provider implementation that is appropriate to
the current runtime context.</li>
+ <li>· The Control’s implementation is designed to run in a very
specific context (for example, only in the http servlet tier) and wants access
to services that are very specific to that context (for example, session state
or request query parameters). It should not be possible to instantiate this
Control in other contexts (for example, from within an EJB).</li>
+</ul>
+<p><strong>One key contextual service for Controls that is guaranteed to be
available in all contexts is the
org.apache.beehive.controls.api.context.ControlBeanContext service interface.
</strong>This service provides a common set of generic services that are
available to Control authors, such as the ability to query property values on
the current instance, or to receive a set of basic lifecycle or resource
management events. The ControlBeanContext interface extends the
java.beans.beancontext.BeanContextServices interface, so it also provides
access to services provided by the JavaBeans bean context APIs. Later
sections describe an overview of the internal architecture for contextual
services, APIs to support property resolution, and lifecycle events.</p>
+ <section>
+ <title>9.1 Declarative Access to Contextual Services</title>
+ <p>To signal the desire to access a contextual service, a
Control author only needs to declare a field of the desired context interface
and annotate it with the org.apache.beehive.controls.api.context.Context marker
annotation. The following example shows how the JmsMessageControlImpl class
would use the declarative model to access its ControlBeanContext:</p>
+
+<p><strong>Declarative Access to Context Services (Control Implementation
Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import org.apache.beehive.controls.api.context.Context;
+import org.apache.beehive.controls.api.context.ControlBeanContext;
+
+public class JmsMessageControlImpl implements JmsMessageControl
+{
+ <strong>@Context ControlBeanContext context;</strong>
+
+ public void sendTextMessage(String text)
+ {
+ JmsMessageControl.Destination =
+
<strong>context.getControlPropertySet(JmsMessageControl.Destination.class);</strong>
+
+ …
+ }
+}</source>
+<p>In this example, the JmsMessageControl implementation class expresses its
desire to access ControlBeanContext services via the annotated declaration of
the context field; when code in sendTextMessage operation is invoked, this
contextual service has already been initialized by the containing ControlBean
instance.</p>
+<p>The ControlBeanContext for an authored Control is always accessed using the
declarative mechanism. Other contextual services may be accessed
declaratively, or using the programmatic mechanisms described in the following
section.</p>
+
+ </section>
+ <section>
+ <title>9.2 Programmatic Access to Contextual Services</title>
+<p>The ControlBeanContext service also provides the base mechanism to discover
and use other services programmatically. The following code fragment shows an
example of how to use this API to obtain access to a service provider that
provides the javax.servlet.ServletContext interface.</p>
+
+<p><strong>Programmatic Access to Context Services (Control Implementation
Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import javax.servlet.ServletContext;
+import org.apache.beehive.controls.api.context.Context;
+import org.apache.beehive.controls.api.context.ControlBeanContext;
+
+public class JmsMessageControlImpl implements JmsMessageControl
+{
+ <strong>@Context ControlBeanContext context;</strong>
+
+ public void sendTextMessage(String text)
+ {
+ <strong>ServletContext servletContext =
context.getService(ServletContext.class, null);</strong>
+ if (servletContext == null)
+ {
+ // no ServletContext provider is available
+ }
+
+ …
+ }
+}</source>
+<p>The code in the sample uses the ControlBeanContext.getService API to
request that it provide a ServletContext service. The parameters to this
method are the Class of the requested service, and an (optional)
service-specific selector that can be used to parameterize the service. </p>
+<p>The ServletContext service is contextual because it is available only to
controls running in the web tier. If the above sample control was running
anywhere else, the call to ControlBeanContext.getService() would return
null.</p>
+
+ </section>
+ <section>
+ <title>9.3 Tradeoffs between Declarative and Programmatic
Access</title>
+<p>Declarative access to context services is always available to a Control
Implementation Class, and generally results in less code associated with
accessing services. Why then, would using programmatic access ever be useful?
There is a key difference between the two:</p>
+
+<ul>
+ <li>· When using the declarative model for accessing a contextual
service, the Control is effectively saying that the service is required for it
to function; if not available in a particular runtime environment, then
construction of an instance of the Control will fail. Essentially, the
annotated context acts as a notification to the runtime factory that this
prerequisite must be satisfied.</li>
+
+ <li>· Use of the programmatic model allows a Control Implementation
Class to implement conditional behavior based upon whether a contextual service
is or is not available. The Control Implementation Class can use the
programmatic accessor, and then make a decision how to proceed based upon
whether the requested service is available.</li>
+</ul>
+ </section>
+ </section>
+
+ <section>
+ <title>10. Properties</title>
+ <p>This section describes Control properties. Properties provide the
basic mechanism for parameterizing the behavior of a Control instance.</p>
+ <p>The Controls architecture takes the basic JavaBeans notion of
properties and extends it to support two new capabilities:</p>
+ <ul>
+ <li>· A declarative annotation model where properties can be
preconfigured on a ControlBean using JSR-175 annotations</li>
+
+ <li>· An administrative model where the value of ControlBean
properties can be externally defined or overridden.</li>
+ </ul>
+ <p>The external configuration and administrative model for Controls
will be described in a separate document.</p>
+ <section>
+ <title>10.1 Declaring Properties for a Control Type</title>
+ <p>For Controls, the set of properties is explicitly declared
on the Control Public Interface. This makes the available parameterization of
a Control type readily visible to both code and tools.</p>
+<p>Properties are grouped together into related groups called PropertySets.
All Properties within a PropertySet will have a common set of attributes (such
as where they can be declared, the access model for JavaBean accessors, etc)
and will have property names based upon a common naming convention.</p>
+<p>A PropertySet is declared as a JSR-175 attribute interface within the
Control Public Interface, which is also decorated with the
org.apache.beehive.controls.api.properties.PropertySet meta-attribute. Each of
the members within a PropertySet will refer to a distinct property within the
set, and the return value of the member defines the property type.</p>
+<p>Here is a sample declaration of the Destination PropertySet for the
JmsMessageControl, which can be used to configure the target JMS destination
for the Control:</p>
+
+<p><strong>Declaring Properties (Control Public Interface)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import org.apache.beehive.controls.api.bean.ControlInterface
+import org.javacontrols.api.properties.PropertySet;
+import java.lang.annotations.Retention;
+import java.lang.annotations.RetentionPolicy;
+import java.lang.annotations.Target;
+
[EMAIL PROTECTED]
+public interface JmsMessageControl
+{
+ …
+
+ public enum DestinationType { QUEUE, TOPIC }
+
+ <strong>@PropertySet(prefix=”Destination”)
+ @Target({FIELD, TYPE})
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface Destination
+ {
+ public DestinationType type() default QUEUE;
+ public String name();
+ }</strong>
+ …
+}</source>
+<p>This declaration defines the PropertySet named ‘Destination’ that
includes two properties: type and name. The type property is based upon
the DestinationType enumerated type, which is also defined in the public
interface. The name attribute is a simple String property.</p>
+<p>Meta-attributes on a PropertySet or property declaration can be used to
provide additional details about the properties and how they may be used. In
the above example, the standard java.lang.annotations.Target annotation is used
to define the places where the @Destination property set can appear (in this
case in either an extension class or field declaration). </p>
+<p>The full set of meta-attributes that can decorate PropertySet or Property
declarations are TBD. They can be used to define constraint models for
property values, or relationships between properties (such as exclusive or,
where one is set or the other, but never both). These meta-attributes can be
read and used by development or administrative tools to aid in the selection of
property values. They can also be used by the runtime for runtime validation
of property values when set dynamically.</p>
+
+ </section>
+ <section>
+ <title>10.2 Accessing Properties from Client Code</title>
+<p>The properties defined in the Control Public Interface will be exposed to
the client programmer using traditional JavaBean setter/getter methods on the
ControlBean Generated Class. These methods will follow a simple naming
pattern based upon the PropertySet interface name, and optional PropertySet
prefix, and property member name. </p>
+<p>The basic pattern for these accessors is:</p>
+
+<p><strong>Property Accessor Generation (Conventions)</strong></p>
+<source> public void set<PropertySetPrefix><MemberName>(<MemberType>);
+ public <MemberType> get<PropertySetPrefix><MemberName>();</source>
+ <p>The PropertySetPrefix refers to the optional prefix attribute of the
PropertySet annotation. If unspecified, it will default to an empty string (no
prefix). The MemberName refers to the PropertySet method name that declares
the property, with the first character converted to uppercase, and the
MemberType refers to the return value type of this method declaration.</p>
+<p>So for the Destination PropertySet interface shown in the example above,
the resulting ControlBean Generated Class would expose the following
accessors:</p>
+
+<p><strong>Property Accessors (ControlBean Generated Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import java.util.TooManyListenersException;
+
+public class JmsMessageControIBean implements JmsMessageControl
+{
+ …
+ public void setDestinationType(DestinationType type) { … }
+ public DestinationType getDestinationType() { …}
+ public void setDestinationName(String name) { …}
+ public String getDestinationName();
+}</source>
+<p>Client code to set the Destination properties on a JmsMessageControlBean
instance would look like:</p>
+
+<p><strong>Using Property Accessors (Client Code)</strong></p>
+<source>@Control JmsMessageControlBean jmsBean;
+
+…
+
+ <strong>jmsBean.setDestinationType(Destination.QUEUE);
+ jmsBean.setDestinationName(“myTargetQueue”);</strong></source>
+
+ </section>
+ <section>
+ <title>10.3 Accessing Properties from Control Implementation
code</title>
+ <p>The Control Implementation class contains code that
executes from within the context of the Control JavaBean that is generated to
host the control. The generated bean will automatically manage the resolution
of properties values from annotations, external configuration, or dynamic
values set by the client.</p>
+<p>Access to these properties is provided by the ControlBeanContext instance
associated with the Control Implementation Class. This interface provides a
set of property accessors that allow the implementation to query for property
values:</p>
+
+<p><strong>ControlBeanContext APIs for Property Access</strong></p>
+<source>package org.apache.beehive.controls.api.context;
+
+public interface ControlBeanContext extends
java.beans.beancontext.BeanContextServices
+{
+ ….
+ public <T extends Annotation> T getControlPropertySet(Class<T>
propertySet);
+ public <T extends Annotation> T getMethodPropertySet(Method m,
Class<T> propertySet);
+ public <T extends Annotation> T getParameterPropertySet(Method m, index
I, Class<T> propertySet);
+ …
+}</source>
+ <p>The propertySet argument passed to these methods must be a valid
PropertySet interface associated with the ControlInterface. The
ControlBeanContext will return the current value for properties in the
PropertySet, or will return null if no PropertySet value has been associated
with this control instance.</p>
+<p>Here is a simple example of using
ControlBeanContext.getControlPropertySet() to query a property set:</p>
+
+<p><strong>Acccessing Control Properties (Client Implementation
Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import org.apache.beehive.controls.api.context.Context;
+import org.apache.beehive.controls.api.context.ControlBeanContext;
+
+public class JmsMessageControlImpl implements JmsMessageControl
+{
+ <strong>@Context ControlBeanContext context;</strong>
+
+ …
+
+ @EventHandler(field=”context”,
eventSet=ControlBeanContext.Lifecycle.class, eventName=”onAcquire”)
+ public void onBeanAcquire()
+ {
+ //
+ // Acquire the property values needed for initialization
+ //
+ <strong>Destination destProp =
+
(Destination)context.getControlPropertySet(JmsMessageControl.Destination.class);</strong>
+ if (destProp == null)
+ {
+ // No destination property set for the control
+ …
+ }</source>
+ <p>This code above queries for the value of the
JmsMessageControl.Destination PropertySet on the current JmsMessageControl
instance.</p>
+ <p>These query methods will return the value of resolved properties
for the Control instance, method, or method argument, respectively. Control
implementations should never use Java reflection metadata accessors directly
on Control classes or methods; these accessors won’t reflect any property
values that have been set dynamically by ControlBean client accessor methods or
externally using administrative configuration mechanisms. The
ControlBeanContext provides a consistent resolution of source annotation,
client-provided, and external values.</p>
+<p>A simple example of using the ControlBeanContext property accessor methods
for accessing Method and Parameter properties is provided in the section on
Extensibility.</p>
+ </section>
+ <section>
+ <title>10.4 External Configuration of Control
Properties</title>
+ <p>Controls also support an administrative model that allows
Control property values to be bound using external configuration syntax. The
enables Control behavior to be parameterized externally to the code, and using
a consistent mechanism that is well-defined and structured to enable
tooling.</p>
+<p>The specifics of this administrative model are not covered within this
document.</p>
+
+ </section>
+ </section>
+
+ <section>
+ <title>11. Extensibility</title>
+<p>The Controls architecture supports an extensibility model that enables the
declarations of user-defined operations or events, based upon a predefined set
of semantics defined by the author of the Control type. The extensibility
mechanism enables the definition of an interface to the resource where
operations (or events) have very specific context. </p>
+<p>For example, in the JmsMessageControl sample, the extensibility mechanism
will be used to raise the level of abstraction: instead of a low-level
mechanism to enqueue messages to a topic or queue, the Control enables
extensibility where operations can be defined that correspond to enqueuing
messages with a very specific format and set of properties, and where message
or property content is derived from method parameters. This creates a
logical view of the resource (in this case a queue or topic) where the
operations available on it have very specific (and constrained) semantics.</p>
+<p>For this section, we’ll start with the how an extension is defined, look
at the authoring model for defining an extensible Control type, and finally
show the client view of using an extended type.</p>
+ <section>
+ <title>11.1 Defining an Extended Interface for a Control
Type</title>
+ <p>An extension to a base Control type that defines a specific
resource use case is created by defining a new Control type that derives from
the original type and is annotated with the ControlExtension annotation
type:</p>
+
+<p><strong>Declaring a Control Extension (Control Extension
Interface)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import org.apache.beehive.controls.api.bean.ControlExtension;
+
+<strong>@ControlExtension</strong>
[EMAIL PROTECTED](type=JmsMessageControl.QUEUE, name=”queue.orders”)
+<strong>public interface OrderQueue extends JmsMessageControl</strong>
+{
+ …
+}</source>
+<p>This example shows that this interface shows that property values can be
configured on the extended interface to further parameterize the use case. In
this case, the InvoiceQueue interface is being designed for a very specific
use case: to enable orders to be enqueued to a JMS queue named
“queue.orders”.</p>
+<p>Once defined, the Control extension author can now begin to define
additional operations on it, in this case the ability to enqueue messages to
the OrderQueue by calling methods on it.</p>
+
+<p><strong>Declaring Extended Operations with Properties (Control Extension
Interface)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import org.apache.beehive.controls.api.bean.ControlExtension;
+
[EMAIL PROTECTED]
[EMAIL PROTECTED](type=JmsMessageControl.QUEUE, name=”queue.orders”)
+<strong>public interface OrderQueue extends JmsMessageControl</strong>
+{
+ public class Order implements java.io.Serializable
+ {
+ public Order(int buyer, String list) { buyerID = buyer; itemList
list; }
+ int buyerID;
+ String [ ] itemList;
+ }
+
+ <strong>@Message (OBJECT)
+ public void submitOrder(
+ @Body Order order,
+ @Property ( name=“DeliverBy”) String
deliverBy);</strong>
+}</source>
+<p>This interface defines a single operation, submitOrder, that enqueues an
ObjectMessage containing a new order. The body of the message will be a
single instance of the Order class, and it will have a single StringProperty
with the expected delivery date (enabling message selector-based queries for
orders that are past due).</p>
+<p>The message format (in this case an ObjectMessage) and the mapping of
operation parameters to message content and/or properties are all defined using
JSR-175 metadata on the method or its parameters. This format makes it very
easy for tools to assist in the creation and presentation of extension
interfaces.</p>
+<p>How does the extension author (or tool) know about the set of annotations
that can be used on the extension interface? This is the topic of the next
section.</p>
+ </section>
+ <section>
+ <title>11.2 Defining Extension Semantics for a Control
Type</title>
+ <p>A Control author is responsible for defining the
extensibility semantics for a particular type, since ultimately they are
responsible for providing the implementation that fulfills the semantics. </p>
+<p>The extension semantics for a Control are part of the public contract for
the Control, and thus are defined on the Control Public Interface as well. As
with Control properties, these are defined in the form of JSR-175 annotation
interfaces, as show in the following sample code from the JmsMessageControl
Public Interface:</p>
+
+<p><strong>Declaring Extension Semantics (Control Public
Interface)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import java.io.Serializable;
+import javax.jms.Message;
+import org.apache.beehive.controls.api.bean.ControlInterface;
+
[EMAIL PROTECTED]
+public interface JmsMessageControl
+{
+ …
+
+ public enum MessageType { BYTES, MAP, OBJECT, STREAM, TEXT }
+
+ <strong>@Target({METHOD})
+ @Retention(RUNTIME)
+ public @interface Message
+ {
+ public MessageType value() default TEXT;
+ }
+
+ @Target({PARAMETER}
+ @Retention(RUNTIME)
+ public interface Body {}
+
+ @Target({PARAMETER})
+ @Retention(RUNTIME)
+ public @interface Property
+ {
+ public String name();
+ }</strong>
+}</source>
+<p>The JmsMessageMessageControl defines three annotation types: Message, Body,
and Property. The @Target annotation on the Message declaration specifies
that Message can be placed on the method declaration to indicate the type of
JMS message that will be enqueued by the operation. The Body annotation is
used to indicate the method parameter that contains the contents of the message
(and must have a type that is compatible with the specified MessageType). The
Property annotation on a method parameter indicates that the parameter’s
value should be stored as a property on the enqueue message, with the property
name coming from the value of the annotation and the property type derived from
the type of the method parameter.</p>
+<p>The key is that the Control Public Interface contains sufficient details
about the expected annotations that a tool can support the construction. It
also makes it possible for the Control compiler (that converts the extended
interface to an associated bean implementation) to perform validation of
interface and method annotations.</p>
+<p>More details on how these extension semantics are implemented are described
in the next section.</p>
+ </section>
+ <section>
+ <title>11.3 Authoring an Extensible Control Type</title>
+ <p>The author of a Control type is responsible for providing
the code that implements the extension semantics for the Control. Support for
extensibility is optional; so a Control author indicates extensibility of a
type by declaring that that the Control Implementation Class implements the
org.apache.beehive.controls.api.bean.Extensible interface. This interface has
a single method named invoke(). </p>
+<p>The skeleton of this code for the JmsMessageControlImpl class is shown
below:</p>
+<p><strong>Implementing Extended Operations (Control Implementation
Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import org.apache.beehive.controls.api.context/.Context;
+import org.apache.beehive.controls.api.context.ControlBeanContext;
+import org.apache.beehive.controls.api.bean.Extensible;
+
+public class JmsMessageControlImpl implements JmsMessageControl, Extensible
+{
+ @Context ControlBeanContext context;
+
+ <strong>public Object invoke(Method m, Object [] args) throws Throwable
+ {
+ // Extensibility implementation
+ …
+ }</strong>
+}
+</source>
+<p>The invoke() method on the Control Implementation Class will be called any
time an operation defined on an extension interface is called on the Control by
its client. The implementation of this method has responsibility for examining
the current set of properties for the Control instance, methods, and parameters
and using them to parameterize the behavior of the Control.</p>
+<p>This is demonstrated by the code below, which shows a portion of the
implementation of invoke() for the JmsMessageControlImpl class:</p>
+<p><strong>Accessing Method Properties Using the Context (Control
Implementation)</strong></p>
+<source>Object invoke(Method m, Object [] args) throws Throwable
+{
+ …
+
+ int bodyIndex = 1;
+ for (int i= 0; i < args.length; i++)
+ if (context.getArgumentPropertySet(m, i, JMMessageControl.Body.class)
!= null)
+ bodyIndex = i;
+
+ //
+ // Create a message of the appropriate type
+ //
+ Message msg = null;
+ JMSMessageControl.Message msgProp =
<strong>context.getMethodPropertySet(m,
+
JMSMessageControl.Message.class);</strong>
+ switch(msgProp.value())
+ {
+ case MessageType.OBJECT:
+ msg = session.createObjectMessage(args[bodyIndex]);
+ break;
+ …
+ }
+
+ //
+ // Decorate the message with properties defined by any arguments
+ //
+ for (int i= 0; i < args.length; i++)
+ {
+ JMSMessageControl.Property jmsProp =
+ <strong>context.getParameterPropertySet(m,i,
JmsMessageControl.Property.class);</strong>
+ if (jmsgProp != null)
+ {
+ String name = jmsProp.value();
+ if (args[I] instanceof String)
+ msg.setStringProperty(name, ((String)args[i]);
+ else if (args[I] instanceof Integer)
+ …
+ else
+ msg.setObjectProperty(name, args[I);
+ }
+}</source>
+<p>In the sample code above, the Control Implementation Class uses the
ControlBeanContext getMethodProperty and getParameterProperty APIs to query
properties of the invoked method and its argument. These query methods will
return null if the property is not found and no default was defined for the
attribute member.</p>
+
+ </section>
+ <section>
+ <title>11.4 Client Model for Using an Extended Control
Type</title>
+ <p>The client model for using an extended Control type is
exactly the same as the model for using a base Control type. The same set of
declarative and programmatic instantiation mechanisms (described in the
previous section) will be used, and operations or events are handled the same
way.</p>
+<p>Below is sample code that uses the OrderQueue extended type (using
declarative client model):</p>
+<p><strong>Using a Control Extension (Client Code)</strong></p>
+<source><strong>@Control org.apache.beehive.controls.examples.OrderQueueBean
orderBean;</strong>
+
+…
+ Order order = new OrderQueue.Order();
+ order.buyerID = myID;
+ order.itemList = new String [] {“item1”, “item2”};
+ orderBean.submitOrder(order, “12-31-2004”);
+</source>
+<p>Looking closely at the example, you’ll notice that a derived ControlBean
type (OrderQueueBean) is generated by the Control compiler, just as it is for a
base Control type.
+The skeleton of this ControlBean Generated Class is shown below:
+</p>
+<p><strong>Implementation of Extended Operations (ControlBean Generated
Class)</strong></p>
+<source>Package org.apache.beehive.controls.examples;
+
+public class OrderQueueBean extends JmsMessageControlBean
+ implements OrderQueue
+{
+ JmsMessageControlImpl _impl;
+ ….
+ Public void submitOrder(Object order, String deliveryBy)
+ {
+ …
+ _impl.invoke(submitOrderMethod, new Object [] {order, deliveryBy};
+ …
+ }
+
+}</source>
+ <p>There are several attributes worth noting about the extended ControlBean
Generated Class:</p>
+ <ul>
+ <li>· Its implementation will be a subclass of the base type
ControlBean, so implementation of base type operations is inherited.</li>
+
+ <li>· The extended bean will implement the extended Control
interface, meaning all extended operations will be implemented by the bean.</li>
+</ul>
+<p>The implementation of these extended operations will always delegate down
to the base Control Implementation Class by calling the Extensible.invoke()
method.</p>
+ </section>
+ </section>
+
+ <section>
+ <title>12. Composition</title>
+ <p>The Controls architecture supports a composition model, based
upon the JavaBeans Runtime Containment and Services Protocol. This means that
it is possible for new types of ControlBeans to be defined that are built
through composition of one or more other types.</p>
+ <section>
+ <title>12.1 Composition Using Declarative Instantiation</title>
+ <p>Additionally, the ControlBeans authoring model makes
composition very simple based upon the declarative instantiation model.
Within any ControlBean implementation, any @Control fields will automatically
be initialized as children of the local bean’s context.</p>
+<p>Here’s a simple example based upon our previous OrderQueue example.
Let’s say that we want to create a logical Control that can be used to submit
orders. This Control will submit to one of two different queues, depending
upon whether the order needs to ship in less than 30 days, or greater than 30
days.</p>
+<p>The implementation of this Control could look like:</p>
+ <p><strong>Composition Using Declarative Instantiation
(Control Implementation Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+public class OrderRouterImpl
+{
+ @Control @Destination(Name=”RushOrders”)
+ OrderQueueBean rushOrders;
+
+ @Control @Destination(Name=”Orders”)
+ OrderQueueBean orders;
+
+ …
+
+ public void submitOrder(Order order, String deliverBy)
+ {
+ if (needsRushDelivery(deliveryBy))
+ rushOrders.submitOrder(order, deliverBy);
+ else
+ orders.submitOrder(order, deliverBy);
+ }
+}
+</source>
+<p>In this example, the OrderRouterImpl Control itself uses the services of
two different OrderQueue Controls referencing two different queues, and uses a
helper method (needsRushDelivery) to decide where to enqueue a particular
order. The new Control has the same operations exposed as the original
Controls; but now uses the services of one or the other of its children to
satisfy the request.</p>
+<p>The next section describes doing an equivalent composition using mechanisms
to instantiate and build the Control hierarchy.</p>
+ <section>
+ <title>12.1.1 Composition using Programmatic
Mechanisms</title>
+<p>Because the ControlBeans architecture is built using the JavaBeans Runtime
Containment protocol, which defines a base composition model for JavaBeans, it
is also possible to manually instantiate and Controls using the APIs it
defines. The ControlBeanContext API extends the
java.beans.beancontext.BeanContext API, which provides support for adding
children to the current bean’s context.</p>
+<p>Here’s the previous sample, rewritten to use programmatic composition:</p>
+<p><strong>Composition Using Programmatic Instantiation (Control
Implementation Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+public class OrderRouterImpl
+{
+ OrderQueueBean rushOrders; // no @Control annotation, so no auto-init
+ OrderQueueBean orders; // no @Control annotation, so no auto-init
+ <strong>@Context ControlBeanContext context;</strong>
+ …
+
+ public void context_onCreate()
+ {
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ rushOrders = (OrderQueueBean)Beans.instantiate(cl,
“org.apache.beehive.controls.examples.OrderQueueBean”);
+ rushOrders.setDestinationName(“RushOrders”);
+ <strong>context.add(rushOrders);</strong>
+ orders = (OrderQueueBean)Beans.instantiate(cl,
“org.apache.beehive.controls.examples.OrderQueueBean”);
+ orders.setDestinationName(“RushOrders”);
+ <strong>context.add(orders);</strong>
+ }
+
+ public void submitOrder(Order order, String deliverBy)
+ {
+ ….
+ }
+}</source>
+
+ </section>
+ </section>
+ <section>
+ <title>12.2 Internal Architecture for Composition and
Services</title>
+ <p>The JavaBeans Runtime Containment and Services Protocol
provides the base composition model for Control composition and containment.
In this model, JavaBeans are associated with a BeanContext that manages the
composition hierarchy and also manages any contextual services requested by the
contained beans.</p>
+<p>In the Control architecture, a ControlBean will potentially be related to
two different BeanContexts: a parent context that represents the outer
container for the bean, and a peer context that provides containment and
services to other beans nested within that Control.</p>
+<p>These context relationships from the previous sample are shown in the
following diagram:</p>
+<p>todo: image</p>
+<p>In the diagram, the two OrderQueueBean instances created by OrderRouterBean
are nested within the ControlBeanContext; while not shown, these two beans
would also have a peer ControlBeanContext providing them with contextual
services.</p>
+<p>The peer ControlBeanContext provides localized generic services to the
associated Control Implementation instance, such as ability to resolve property
values from the local bean instance or externalized configuration, and the
delivery of lifecycle events. The ControlBean architecture uses a delegation
model for service discovery. If an implementation instance requests a service
that is not implemented by the peer BeanContext, it will delegate up to the
parent context to find a provider for the service.</p>
+<p>At the root of the bean composition hierarchy is an instance of a
ContainerBeanContext. This context represents the external runtime
environment, within which the ControlBean is running. This might represent an
EJB, servlet, web service, Java application, or any ControlBean-capable
container. The ContainerBeanContext is responsible for the initialization and
provisioning of service providers that are specific to runtime environment with
which it is associated.</p>
+<p>Whether ContainerBeanContext or ControlBeanContext, the BeanContext
instances also provide the basic hierarchy of composition, as shown by the
parent-child relationships above.</p>
+ </section>
+ </section>
+
+ <section>
+ <title>13. Context Events</title>
+ <p>The Control programming model also exposes a basic set of
lifecycle events to enable the Control to perform efficient initialization and
resource management. These events are delivered by the peer
ControlBeanContext associated with a ControlBean instance. A listener can
register to receive these events using the addCallbackListener API on
ControlBeanContext; the actual Callback event interface itself is defined there
as well:</p>
+<p><strong>Context Life Cycle Events</strong></p>
+<source>import org.apache.beehive.controls.api.context;
+
+public interface ControlBeanContext extends
java.beans.beancontext.BeanContextServices
+{
+ …
+ <strong>public interface Callback extends java.util.EventListener
+ {
+ public void onCreate();
+ public void onAcquire();
+ public void onRelease();
+ }
+
+ public void addCallbackListener(Callback lifecycleListener);
+ public void removeCallbackListener(Callback lifecycleListener); </strong>
+}</source>
+<p>The specific life cycle events are described in the following section:</p>
+ <section>
+ <title>13.1 Life Cycle Events</title>
+ <p>The ControlBeanContext life cycle events provide
notification to the associated ControlBean derived class and Control
Implementation Class (and potentially other interested listeners) of
significant events related to the peer bean instance.</p>
+ <section>
+ <title>13.1.1 The onCreate Event</title>
+ <p>The onCreate event is delivered when the Control
Implementation instance associated with the ControlBean has been constructed
and all declarative initialization has been completed. This provides an
opportunity for the implementation instance to perform any additional
initialization required; implementation instances should generally use the
onCreate event instead of writing constructor code.</p>
+ </section>
+ <section>
+ <title>13.1.2 The onAcquire Event</title>
+ <p>The onAcquire event is delivered to a registered
listener the first time a ControlBean operation is invoked within a particular
resource context. It provides an opportunity for the Control Implementation
instance (or other related entities, such as a contextual service provider) to
acquire any short-term resources (connections, sessions, etc) needed by the
ControlBean.</p>
+<p>The onAcquire event is guaranteed to be delivered once (and only once)
prior to invocation of any operation within a resource context; it is also
guaranteed that a paired onRelease event will be delivered when the resource
context ends.</p>
+<p>For more details on resource management, refer to the <link
href="controlsOverview.html">Control Overview</link> document.</p>
+ </section>
+ <section>
+ <title>13.1.3 The onRelease Event</title>
+ <p>The onRelease event is the companion event to
onAcquire. It is guaranteed to be called once (and only once) on any bean
instance that has received an onAcquire event, when its associated resource
context has ended. It acts as the signal that any short-term resources
(connections, sessions, etc) acquired by the Control should be released.</p>
+
+ </section>
+ </section>
+ <section>
+ <title>13.2 Receiving Life Cycle Events</title>
+<p>For a Control Implementation Class, the model for receiving context life
cycle events is consistent with the general client model for event registration
and delivery. Both declarative and programmatic mechanisms are supported.</p>
+ <section>
+ <title>13.2.1 Declarative Access to Life Cycle
Events</title>
+ <p>A Control Implementation Class can receive Life Cycle
Events simply by declaring the annotated @Context ControlBeanContext and then
defining event handlers that follow the <contextFieldName>_<eventName>
convention.</p>
+<p>The following sample code shows the JmsMessageControl registering to
receive onAcquire and onRelease events:</p>
+<p><strong>Declarative Handling of Life Cycle Events (Control Implementation
Class)</strong></p>
+<source>package org.apache.beehive.controls.examples;
+
+import org.apache.beehive.controls.api.context.Context;
+import org.apache.beehive.controls.api.context.ControlBeanContext;
+import org.apache.beehive.controls.api.events.EventHandler;
+
+Public class JmsMessageControlImpl implements JmsMessageControl
+{
+ <strong>@Context ControlBeanContext context;
+
+ @EventHandler(field=”context”,
eventSet=ControlBeanContext.LifeCycle.class,
+ eventName=”onAcquire”)
+ public void onAcquire()
+ {
+ // Code to acquire JMS connection/session/destination/writers
+ …
+ }
+
+ @EventHandler(field=”context”,
eventSet=ControlBeanContext.LifeCycle.class,
+ eventName=”onRelease”)
+ public void onRelease()
+ {
+ // Code to release JMS connection/session/destination/writer
+ …
+ }</strong>
+}</source>
+<p>When using the declarative mechanism, a Control Implementation Class is
free to implement only a subset of the life cycle listeners; it is not
necessary that it provide a handler for all events.</p>
+ </section>
+ <section>
+ <title>13.2.2 Programmatic Access to Life Cycle
Events</title>
+ <p>An external entity (such as contextual service provider
or even a client) is also able to register for life cycle events on a
ControlBean instance as well. This is done by obtaining a reference to the
peer ControlBeanContext for the instance using the getPeerContext API, and then
using the addCallbackListener API to register a lifecycle event listener.</p>
+<p>This is shown by the following code:</p>
+<p><strong>Programmatic Handling of Life Cycle Events (Control Implementation
Class) </strong></p>
+<source> JmsMessageControlBean myJmsBean = …;
+
+ ControlBeanContext peerContext = myBean.getControlBeanContext();
+ peerContext.addCallbackListener(
+ new ControlBeanContext.LifeCycle()
+ {
+ public void onCreate() { …. };
+ public void onAcquire() { … };
+ public void onRelease() { … };
+ });</source>
+ </section>
+ </section>
+ <section>
+ <title>13.3 JavaBean Context Events</title>
+ <p>The
org.apache.beehive.controls.api.context.ControlBeanContext API extends the
following standard JavaBean context APIs:</p>
+ <ul>
+ <li>· java.beans.BeanContextChild</li>
+ <li>· java.beans.BeanContext</li>
+ <li>· java.beans.BeanContextServices</li>
+ </ul>
+ <p>These APIs provide access to a standard set of JavaBean
events that the Control Implementation Class can register an interest in. </p>
+ <p><em>[Issue: there is not a declarative mechanism for
receiving these events, but probably should be.]</em></p>
+ <section>
+ <title>13.3.1 PropertyChange Events</title>
+ <p>The java.beans.BeanContextChild interface provides the
addPropertyChangeListener() and addVetoableChangeListener() APIs to register
for notification when a property is modified.</p>
+ </section>
+ <section>
+ <title>13.3.2 Membership Events</title>
+ <p>The java.beans.BeanContext interface provides the
addMembershipChangeListener() API to register for notification whenever a child
is added or removed from the BeanContext.</p>
+ </section>
+ <section>
+ <title>13.3.3 Context Services Events</title>
+ <p>The java.beans.BeanContextServices interface provides
the addBeanContextServicesListener API to register for notification when new
contextual services become available or are revoked.</p>
+ </section>
+ </section>
+ </section>
+
+ <section>
+ <title>14. Appendix A: The JmsMessageControl Public
Interface</title>
+ <source>package org.apache.beehive.controls.examples;
+
+import java.io.*;
+import java.lang.annotation.*;
+import javax.jms.*;
+
+import org.apache.beehive.controls.api.bean.ControlInterface;
+import org.apache.beehive.controls.api.events.EventSet;
+import org.apache.beehive.controls.api.properties.PropertySet;
+
+/**
+ * The JmsMessageControl defines a basic Control to enable messages to be
enqueued to a JMS
+ * queue or topic. Using Control properties, you can configure the
connection, session, and
+ * destination attributes that should be used to connect to the JMS provider.
The Control
+ * will transparently connect to the JMS provider and obtain any necessary
resources to
+ * enqueue the messages. The Control will also sure that the resources are
properly released
+ * at the end of the current resource scope associated with the Control’s
runtime environment.
+ *
+ * The Control provides a basic set of operations that allow a simple text or
object message to
+ * be written to the configured destination. It also provides an
extensibility mechanism
+ * that allows new operations to be defined by extending this interface.
Extended operations
+ * define the enqueueing of message with a specific type (TextMessage,
ObjectMessage, ...)
+ * where operation parameters can be mapped to message properties or content.
+ */
[EMAIL PROTECTED]
+public interface JmsMessageControl
+{
+ // OPERATIONS
+
+ /**
+ * Sends a simple TextMessage to the Control’s destination
+ * @param text the contents of the TextMessage
+ */
+ public void sendTextMessage(String text);
+
+ /**
+ * Sends a simple ObjectMessage to the Control’s destination
+ * @param object the object to use as the contents of the message
+ */
+ public void sendObjectMessage(java.io.Serializable object);
+
+
+
+ // EVENTS
+
+ /**
+ * The Callback interface defines the events for the JmsMessageControl.
+ */
+ @EventSet
+ public interface Callback
+ {
+ /**
+ * The onSend event is delivered to a registered client listener
whenever a
+ * a message has been sent by the Control.
+ * @param msg the message that was sent
+ */
+ public void onMessage(javax.jms.Message msg);
+ }
+
+ // PROPERTIES
+
+ /**
+ * The Connection property defines the attributes of the connection and
session used
+ * to enqueue the message. This annotation can appear on both class
and Control
+ * field declarations.
+ */
+ @PropertySet
+ @Target({FIELD, TYPE})
+ public @interface Connection
+ {
+ public String factoryName();
+ public boolean transacted() default true;
+ public int acknowledgeMode() default Session.CLIENT_ACKNOWLEDGE;
+ }
+
+ /** An enumeration that defines the value set of destination types */
+ public enum DestinationType { QUEUE, TOPIC }
+
+ /**
+ * The Destination property defines the attributes of the JMS destination
that should
+ * be the target of any enqueued messages.
+ */
+ @PropertySet
+ @Target({FIELD, TYPE})
+ public @interface Destination
+ {
+ public DestinationType type() default QUEUE;
+ public String name();
+ }
+
+
+
+ // EXTENSIBILITY ATTRIBUTES
+
+ /**
+ * The set of supported message types for extended operations
+ */
+ public enum MessageType { TEXT, OBJECT, BYTES }
+
+ /**
+ * The Message attribute can be placed on an extended operation to
describe the format of the
+ * message that should be enqueued when the operation is invoked. The
method is expected to
+ * have a least parameter annotated with the Body attribute, and zero or
more parameters with
+ * the Property attribute defining message properties.
+ */
+ @Target({METHOD})
+ public @interface Message
+ {
+ public MessageType value() default TEXT;
+ }
+
+ /** The Body attribute indicates that the associated method parameter on
an extended operation
+ * contains the message body.
+ */
+ @Target({PARAMETER}
+ public interface Body {}
+
+ /**
+ * The Property attribute can be used to define operation parameters that
should be used to
+ * set properties on the message. The type of property to set will be
inferred based upon
+ * the type of the parameter.
+ */
+ @Target({PARAMETER})
+ public @interface Property
+ {
+ public String name();
+ }
+}</source>
+ </section>
+
+ <section>
+ <title>15. Appendix B: The JmsMessageControl Implementation
Class</title>
+ <source>package org.apache.beehive.controls.examples;
+
+import org.apache.beehive.controls.api.bean.ControlImplementation;
+import org.apache.beehive.controls.api.bean.Extensible;
+import org.apache.beehive.controls.api.context.ControlBeanContext;
+import org.apache.beehive.controls.api.events.Client;
+import org.apache.beehive.controls.api.events.EventHandler;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.jms.QueueConnectionFactory
+import javax.jms.QueueConnection;
+import javax.jms.QueueSession;
+import javax.jms.QueueSender;
+import javax.jms.TopicConnectionFactory
+import javax.jms.TopicConnection;
+import javax.jms.TopicSession;
+import javax.jms.TopicPublisher;
+import javax.jms.Message;
+
+/**
+ * The JmsMessageControlImpl class is the Control Implementation Class for the
JmsMessageControl.
+ * It implements two basic operations (sendTextMessage and sendObjectMessage)
as well as an
+ * extensibility model that enables custom message formats to be defined and
associated with
+ * extended method signatures.
+ */
[EMAIL PROTECTED]
+public class JmsMessageControlImpl implements JmsMessageControl, Extensible
+{
+ /**
+ * The peer BeanContext instance associated with the Control
+ */
+ @Context ControlBeanContext context;
+
+ /**
+ * The client callback event router for this Control
+ */
+ @Client Callback client;
+
+ /**
+ * The fields are used to hold transient JMS resources that are acquired
and held for
+ * the resource scope associated with the Control
+ */
+ transient javax.jms.Connection _connection;
+ transient javax.jms.Session _session;
+ transient javax.jms.MessageProduction _producer;
+
+
+
+ /*
+ * The onAcquire event handler
+ * This method will be called prior to any operation with a given resource
scope. It is
+ * responsible for obtaining the connection, session, destination, and
appropriate
+ * writer instance, for use within the operation.
+ */
+ @EventHandler(field=”context”,
eventSet=ControlBeanContext.Lifecycle.class, eventName=”onAcquire”)
+ public void onBeanAcquire()
+ {
+ //
+ // Acquire the property values needed for initialization
+ //
+ Destination destProp =
(Destination)context.getControlPropertySet(Destination.class);
+ Connection connProp =
(Connection)context.getControlPropertySet(Connection.class);
+
+ try
+ {
+ //
+ // Obtain the JMS Destination instance based upon the Destination
property
+ //
+ InitialContext jndiContext = new InitialContext();
+ _dest = (javax.jms.Destination)initContext.lookup(destProp.name());
+
+ //
+ // Obtain Connection, Session, and MessageProducer resources based
upon the
+ // destination type and the values in the Connection PropertySet
+ //
+ if (destProp.type() = JmsControl.QUEUE)
+ {
+ javax.jms.QueueConnectionFactory connFactory =
+
(QueueConnectionFactory)jndiContext.lookup(connProp.factoryName());
+ _connection = connFactory.createQueueConnection();
+ _session = (QueueConnection)_connection).createQueueConnection(
+
connProp.transacted(),
+
connProp.acknowledgeMode());
+ _producer = (QueueSession)_session).createSender((Queue)_dest);
+ }
+ else
+ {
+ javax.jms.TopicConnectionFactory connFactory =
+
(TopicConnectionFactory)jndiContext.lookup(connProp.factoryName());
+ _connection = connFactory.createTopicConnection();
+ _session =
((TopicConnection)_connection).createTopicConnection(
+
connProp.transacted(),
+
connProp.acknowledgeMode());
+ _producer =
((TopicSession)_session).createPublisher((Topic)_dest);
+
+ }
+ }
+ catch (javax.naming.NamingException ne)
+ {
+ throw new ControlException("Unable to locate JNDI object", ne);
+ }
+ catch (ClassCastException ce)
+ {
+ throw new ControlException("JNDI object did not match expected
type", ce);
+ }
+ catch (JMSException jmse)
+ {
+ throw new ControlException("Unable to acquire JMS resources",
jmse);
+ }
+ }
+
+ /*
+ * The onRelease event handler for the associated context
+ * This method will release all resource acquired by onAcquire.
+ */
+ @EventHandler (field=”context”,
eventSet=ControlBeanContext.Lifecycle.class , eventName=”onRelease”)
+ public void onRelease()
+ {
+ try
+ {
+ if (_producer != null)
+ {
+ _producer.close();
+ _producer = null;
+ }
+ if (_session != null)
+ {
+ _session.close();
+ _session = null;
+ }
+ if (_connection != null)
+ {
+ _connection.close();
+ _connection = null;
+ }
+ }
+ catch (JMSException jmse)
+ {
+ throw new ControlException("Unable to release JMS resource", jmse);
+ }
+ }
+
+ /**
+ * Helper method used to send a message once constructed
+ */
+ private void sendMessage(Message msg) throws JMSException
+ {
+ client.onMessage(msg);
+ if (_producer instanceof java.jms.QueueSender)
+ ((QueueSender)_producer).send(msg);
+ else
+ ((TopicPublisher)_producer).publish(msg);
+ }
+
+
+ /**
+ * Sends a simple TextMessage to the Control’s destination
+ * @param text the contents of the TextMessage
+ */
+ public void sendTextMessage(String text) throws JMSException
+ {
+ javax.jms.TextMessage msg = _session.createTextMessage(text);
+ sendMessage(msg);
+ }
+
+ /**
+ * Sends a simple ObjectMessage to the Control’s destination
+ * @param object the object to use as the contents of the message
+ */
+ public void sendObjectMessage(java.io.Serializable object)
+ {
+ javax.jms.ObjectMessage msg = _session.createObjectMessage(object);
+ sendMessage(msg);
+ }
+
+ /**
+ * Implements the Extensible.invoke() interface for this Control
+ * This method uses the Message property to determine the type of message
to construct,
+ * and then uses the Body and Property attributes of method parameters to
supply message
+ * content and properties.
+ */
+ public Object invoke(Method m, Object [] args) throws Throwable
+ {
+ int bodyIndex = -1;
+ for (int i= 0; i< args.length; i++)
+ {
+ if (context.getParametertPropertySet(m, I,
JmsMessageControl.Body.class) != null)
+ {
+ bodyIndex = i;
+ break;
+ }
+ }
+ if (bodyIndex == -1)
+ throw new ControlException("No @Body argument defined for
operation: " + m.getName());
+
+ //
+ // Create a message based upon the value of the Message property of
the method
+ //
+ javax.jms.Message msg = null;
+ Message msgProp =
context.getMethodPropertySet(m.JmsMessageControl.Message.class);
+ try
+ {
+ switch(msgProp.value())
+ {
+ case MessageType.TEXT:
+ msg = session.createTextMessage((String)args[bodyIndex]);
+ break;
+
+ case MessageType.OBJECT:
+ msg = session.createObjectMessage(args[bodyIndex]);
+ break;
+ case MessageType.BYTES:
+ msg = session.createBytesMessage()
+ msg.writeBytes((byte []) args[bodyIndex]);
+ break;
+ }
+ }
+ catch (ClassCastException)
+ {
+ throw new ControlException("Invalid type for Body parameter", cce);
+ }
+
+ //
+ // Now decorate the message with any Property-annotated parameters
+ //
+ for (int i= 0; i< args.length; i++)
+ {
+ JMSMessageControl.Property prop =
+ context.getParameterPropertySet(m,
i,.JmsMessageControl.Property.class);
+ if (prop != null)
+ {
+ String propName = prop.name();
+ if (args[i] instanceof String)
+ msg.setStringProperty((String)args[i]);
+ else if (args[i] instanceof Integer)
+ msg.setStringProperty(((Integer)args[i])intValue());
+ else if (args[i] instanceof Short)
+ msg.setStringProperty(((Short)args[i]).shortValue());
+ else if (args[i] instanceof Boolean)
+ msg.setBooleanProperty(((Boolean)args[i]).booleanValue());
+ else if (args[i] instanceof Float)
+ msg.setFloatProperty(((Float)args[i]).floatValue());
+ else if (args[i] instanceof Double)
+ msg.setDoubleProperty(((Double)args[i]).doubleValue());
+ else
+ msg.setObjectProperty(args[i]);
+ }
+ }
+
+ //
+ // Send it
+ //
+ sendMessage(msg);
+ }
+}</source>
+ </section>
+
+ </body>
+</document>