com.boylesoftware.cb2
Class ApplicationContext

java.lang.Object
  extended bycom.boylesoftware.cb2.ApplicationContext
All Implemented Interfaces:
BroadcastMessagingTerminal, java.util.EventListener, StatusProvider

public final class ApplicationContext
extends java.lang.Object
implements StatusProvider, BroadcastMessagingTerminal

ApplicationContext class provides low-level application-wide services available to all application parts at all times. The services include access to database connections, transaction management, access to the application configuration and logging facilities, broadcast messaging. Application context object is an application-wide "singleton", that is there is only one instance per application.

During initialization the application context reads a configuration file called cb2app.properties, which contains application properties, available to the user application code, as well as a set of special properties configuring the application context itself. The file should be in a format very similar to the standard Java properties file format, except that it does not support multiline properies (the backslash syntax) and adds some extensions such as conditional inclusion tags and macros (see below). Also, the set of application properties can be supplemented by values loaded from a database, however there are some basic properties, including those configuring the database connections, that can be specified only in the cb2app.properties file.

Standard Application Properties

The following properties in cb2app.properties configure application context's operation:

Transaction Contexts

There are several standard transaction context implementations included in CB2. Each of them has a different set of features and is more suitable for this or that particular application. Here is their description:

Appliaction Properties File Extended Syntax

The cb2app.properties file allows some extensions to the basic properties syntax. One extension allows you to conditionally include or exclude different parts of the file basing on values of other properties in the same file or system properties. A single line in the file can contain a condition tag in one of the following three forms:

Another extention allows macros. If you put ${name} construct in a property value it will be replaced with the value of another property named name. If there is no such property the tag will be left intact. Note, that you can use only properties defined above the place the macro appears, or system properties.

Internal Log Messages

Application context logs debug messages under com.boylesoftware.cb2.APPCTX channel.

Version:
$Id: ApplicationContext.java,v 1.21 2004/04/30 18:54:08 levahim Exp $
Author:
Lev Himmelfarb

Field Summary
 
Fields inherited from interface com.boylesoftware.cb2.StatusProvider
TIMESTAMP_FORMAT
 
Constructor Summary
ApplicationContext(java.lang.String appName, java.lang.String configDirPath)
          Create an application context instance and initializes it.
 
Method Summary
 void beginTransaction()
          Starts new transaction and binds its transaction context to the calling thread.
 TransactionContext beginTransaction(boolean bindToThread)
          Starts new transaction.
 void broadcastBCMMessage(java.lang.String channelName, java.io.Serializable messageParam)
          Sends a message to all cluster members through the CB2 Broadcast Messaging subsystem (the BCM).
 void cancelAllStatements()
          Tries to cancel all currently active database statements.
 void cancelStatement(java.lang.Long id)
          Tries to cancel an active database statement.
static void commitTransaction()
          Commits transaction associated with the calling thread.
static void commitTransaction(TransactionContext txCtx)
          Commits transaction associated with the specified transaction context.
 void destroy()
          Destroy the application context.
 java.lang.String getAppName()
          Gets the application name originally set through appName parameter of the application context constructor.
 java.lang.String getBasicProperty(java.lang.String name)
          Gets value of an application property defined in the cb2app.properties file.
 boolean getCloseJNDIContexts()
          Convenience method returning value of com.boylesoftware.cb2.closeJNDIContexts application property as a boolean.
 java.lang.String getConfigDirPath()
          Returns filesystem path to the directory that contains application configuration files including cb2app.properties.
 java.sql.Connection getConnection()
          Convenience method, which calls getConnection("default", true) internally.
 java.sql.Connection getConnection(boolean forUpdate)
          Convenience method, which calls getConnection("default", forUpdate) internally.
 java.sql.Connection getConnection(java.lang.String dataSourceName, boolean forUpdate)
          Gets database connection.
static java.sql.Connection getConnection(TransactionContext txCtx)
          Convenience method, which calls getConnection(txCtx, "default") internally.
static java.sql.Connection getConnection(TransactionContext txCtx, java.lang.String dataSourceName)
          Gets database connection enrolled in the specified transaction context.
 EventStatistics getEventStats(java.lang.String eventName)
          Gets event statistics for various events.
 org.apache.commons.logging.Log getLog(java.lang.String subsystem)
          Returns log for the specified channel.
 java.sql.Connection getNoTXConnection()
          Convenience method, which calls getNoTXConnection("default") internally.
 java.sql.Connection getNoTXConnection(java.lang.String dataSourceName)
          Gets database connection directly from the data source.
 java.util.Properties getProperties()
          Gets all application properties.
 java.lang.String getProperty(java.lang.String name)
          Gets an application property value.
 byte[] getStats()
          Retrieves application context information and returns it as XML.
 boolean isBCMEnabled()
          Tells if the CB2 Broadcast Messaging subsystem (the BCM) is enabled.
 boolean isDatabaseAvailable()
          Tells if the database subsystem is enabled for this application context.
static boolean isRollbackOnly()
          Tells if transaction associated with the calling thread is marked for rollback only.
static boolean isRollbackOnly(TransactionContext txCtx)
          Tells if transaction associated with the specified transaction context is marked for rollback only.
 void processBCMMessage(java.lang.String channelName, java.lang.String source, java.io.Serializable messageParam)
          Processes a received through the CB2 Broadcast Messaging subsystem message by calling processMessage method on the appropriate terminal.
 void processMessage(java.lang.String channelName, java.lang.String source, java.io.Serializable messageParam)
          Processes an internal application context BCM message.
 void reconfigure(java.lang.String configDirPath)
          Re/configure the context.
 void registerBCMTerminal(java.lang.String channelName, BroadcastMessagingTerminal bcmTerminal)
          Registers a BCM terminal on the specified channel.
static void rollbackTransaction()
          Rolls back transaction associated with the calling thread.
static void rollbackTransaction(TransactionContext txCtx)
          Rolls back transaction associated with the specified transaction context.
 void setProperty(java.lang.String name, java.lang.String value)
          Changes value of an existing application property or sets up a new application property.
static void setRollbackOnly()
          Marks transaction associated with the calling thread for rollback only.
static void setRollbackOnly(TransactionContext txCtx)
          Marks transaction associated with the specified transaction context as for rollback only.
 void unregisterBCMTerminal(java.lang.String channelName)
          Unregisters the BCM terminal set on the specified channel.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ApplicationContext

public ApplicationContext(java.lang.String appName,
                          java.lang.String configDirPath)
                   throws ApplicationException
Create an application context instance and initializes it. There should be only one instance of application context in the application, which has to be created during the application startup before any other subsystem starts using it. Later, in the runtime, you can call reconfigure to have the context reload application properties and reinitialize itself.

Parameters:
appName - the application name, should be unique within the JVM. When you have multiple logical applications in the same JVM, such as for example multiple CB2 web-applications running under the same servlet container, it is necessary to assign different names to them.
configDirPath - points to the directory which contains application configuration files including cb2app.properties.
Throws:
ApplicationException - there was a fatal error during context initialization. The context, and thus the whole application, is unavailable.
Method Detail

reconfigure

public void reconfigure(java.lang.String configDirPath)
                 throws ApplicationException
Re/configure the context. This method reloads all application properties and reinitializes all internal services.

Parameters:
configDirPath - points to the directory which contains application configuration files including cb2app.properties.
Throws:
ApplicationException - there was a fatal error during context configuration. The context, and thus the whole application, is unavailable and has to be shut down immediately.

destroy

public void destroy()
Destroy the application context. This method is usually called as the last thing when the application is shutting down. The application context becomes unusable after this call.


getAppName

public java.lang.String getAppName()
Gets the application name originally set through appName parameter of the application context constructor.

Returns:
the application name.

getConfigDirPath

public java.lang.String getConfigDirPath()
Returns filesystem path to the directory that contains application configuration files including cb2app.properties. Your application may use the directory to store its own specific configuration files and then find them in the runtime using this method.

Returns:
path to the configuration directory.

getProperty

public java.lang.String getProperty(java.lang.String name)
Gets an application property value. Application properties are read from the cb2app.properties configuration file and optionally from the database during application context configuration. The properties then are cached in the application context so this method is fast. If this method cannot find named property among the application properties, it tries to find it among system properties. Note, that sometimes looking up some system property can be disallowed by the security manager (see java.security.AccessController), in which case this method throws a java.security.AccessControlException.

Parameters:
name - the property name.
Returns:
the property value or null if there is no such property.
See Also:
getProperties()

getProperties

public java.util.Properties getProperties()
Gets all application properties. The returned Properties object is backed up by the system properties, so if some application property is not specified, the default value for it can be provided by a system property with the same name.

Note, that sometimes getting all system properties at once, required to back up application properties with system properties, is prohibited by the security manager (see java.security.AccessController), in which case the Properties object returned by this method is not becked up by system properties.

Returns:
application properties.
See Also:
getProperty(String)

getBasicProperty

public java.lang.String getBasicProperty(java.lang.String name)
Gets value of an application property defined in the cb2app.properties file. This method does not return values of properties loaded from the database (see com.boylesoftware.cb2.appProperties.query application property), only those defined in the file. Also, it always returns the original value of the property even if it was redefined later via a setProperty call. If a property is defined in both the file and the database, the value from the file is returned by this method.

This method is not supposed to be used by the application code, however it can be useful for a subsystem, which manages application properties, such as PropertySharedBLO from com.boylesoftware.cb2.commons.property package.

Parameters:
name - the basic application property's name.
Returns:
the original value as it is specified in the cb2app.properties file, or null if the property is not defined there.

setProperty

public void setProperty(java.lang.String name,
                        java.lang.String value)
Changes value of an existing application property or sets up a new application property. This method does not update any underlying property storages - neither the cb2app.property file, nor the database. It merely sets value for a cached in the application context's memory property. It also means that a property, set by this method, does not survive a reconfigure call, unless it was changed in the underlying storage as well.

If the specified value is null, the method removes the property from the set of application properties.

This method, after the property has been successfully set, sends a message via BCM to all cluster members, so they set their cached properties too.

Parameters:
name - the property name.
value - new property value.

processMessage

public void processMessage(java.lang.String channelName,
                           java.lang.String source,
                           java.io.Serializable messageParam)
Processes an internal application context BCM message. Do not call this method.

Specified by:
processMessage in interface BroadcastMessagingTerminal
Parameters:
channelName - name of the BCM channel, on which the message was received.
source - a string, which identifies in a specific to the BCM provider implementation way the JVM that sent the message.
messageParam - optional general purpose parameter sent along with the message, may be null.

getLog

public org.apache.commons.logging.Log getLog(java.lang.String subsystem)
Returns log for the specified channel. Application context uses Apache Commons Logging as a generic interface to different supported log kits. This method, in fact, results in a call to org.apache.commons.logging.LogFactory configured and maintained inside the application context.

Parameters:
subsystem - name of the log channel (or log category name in terms of some log kit implementations).
Returns:
reference to the log object or null if logging is not supported by the context.

getCloseJNDIContexts

public boolean getCloseJNDIContexts()
Convenience method returning value of com.boylesoftware.cb2.closeJNDIContexts application property as a boolean. If the property is not specified, this method returns the default value, which is true.

Well-written applications that work with JNDI should consult this method when they don't need InitialContext object anymore and have to decide whether to call close method on it.

Returns:
true if InitialContext objects should be closed explicitely after use.

beginTransaction

public TransactionContext beginTransaction(boolean bindToThread)
                                    throws ApplicationException
Starts new transaction. In CB2 transaction is represented by a transaction context instance, which is the interface to manage the transaction. One transaction context can represent only one active top-level transaction, however, depending on the implementation, nested transactions within one transaction context may be supported.

Optionally, by setting bindToThread parameter to true, you can associate new transaction context with the current thread, which enables calling other transaction management methods from within this thread without specifying transaction context instance. This, in fact, is the most common use case, so there is a version of this method which takes no bindToThread parameter assuming it's true provided for conevnience.

Parameters:
bindToThread - tells whether the new transaction context should be associated with the calling thread. The context is bound to the thread if this parameter is true.
Returns:
transaction context instance, which represents the transaction and can be passed to other transaction management methods to identify on which transaction they should perform their actions.
Throws:
ApplicationException - if transaction cannot be started.
See Also:
beginTransaction()

beginTransaction

public void beginTransaction()
                      throws ApplicationException
Starts new transaction and binds its transaction context to the calling thread. This is a convenience method, which calls beginTransaction(true) internally.

Throws:
ApplicationException - if transaction cannot be started.
See Also:
beginTransaction(boolean)

commitTransaction

public static void commitTransaction(TransactionContext txCtx)
                              throws ApplicationException
Commits transaction associated with the specified transaction context.

Parameters:
txCtx - the trnasaction context.
Throws:
ApplicationException - if underlying subsystem error happens.

commitTransaction

public static void commitTransaction()
                              throws ApplicationException
Commits transaction associated with the calling thread.

Throws:
ApplicationException - if underlying subsystem error happens.
java.lang.IllegalStateException - if there is no transaction context associated with the thread.

rollbackTransaction

public static void rollbackTransaction(TransactionContext txCtx)
                                throws ApplicationException
Rolls back transaction associated with the specified transaction context.

Parameters:
txCtx - the transaction context.
Throws:
ApplicationException - if underlying subsystem error happens.

rollbackTransaction

public static void rollbackTransaction()
                                throws ApplicationException
Rolls back transaction associated with the calling thread.

Throws:
ApplicationException - if underlying subsystem error happens.
java.lang.IllegalStateException - if there is no transaction context associated with the thread.

setRollbackOnly

public static void setRollbackOnly(TransactionContext txCtx)
                            throws ApplicationException
Marks transaction associated with the specified transaction context as for rollback only. If a transaction is marked as for rollback only, when commit is requested it actually gets rolled back instead. It is useful when at some point an error happens, but you want to continue operation, so you don't throw an exception, while the transaction has to be rolled back anyway when the processing finishes.

Parameters:
txCtx - the trnasaction context.
Throws:
ApplicationException - if underlying transaction manager error happens.

setRollbackOnly

public static void setRollbackOnly()
                            throws ApplicationException
Marks transaction associated with the calling thread for rollback only. Does nothing if there is no transaction context for the thread.

Throws:
ApplicationException - if underlying subsystem error happens.

isRollbackOnly

public static boolean isRollbackOnly(TransactionContext txCtx)
                              throws ApplicationException
Tells if transaction associated with the specified transaction context is marked for rollback only.

Parameters:
txCtx - the trnasaction context.
Returns:
true if the transaction is marked for rollback only.
Throws:
ApplicationException - if underlying subsystem error happens.
See Also:
setRollbackOnly(TransactionContext)

isRollbackOnly

public static boolean isRollbackOnly()
                              throws ApplicationException
Tells if transaction associated with the calling thread is marked for rollback only. Always returns false if there is no transaction context for the thread.

Returns:
true if the transaction exists and is marked for rollback only.
Throws:
ApplicationException - if underlying subsystem error happens.
See Also:
setRollbackOnly()

getConnection

public static java.sql.Connection getConnection(TransactionContext txCtx,
                                                java.lang.String dataSourceName)
                                         throws java.sql.SQLException
Gets database connection enrolled in the specified transaction context.

Never call any transaction management methods on the connection returned by this method - the transaction is managed automatically by the transaction context. Use getNoTXConnection low-level method whenever you need a connection, which is not managed by the application context's transaction management subsystem.

Note, that depending on the transaction context implementation, you may not be allowed to call this method to get connections from different data sources within the same transaction.

Parameters:
txCtx - the transaction context.
dataSourceName - name of the data source as defined in the cb2app.properties configuration file. If null, "default" is assumed.
Returns:
database connection enrolled in the specified transaction context.
Throws:
java.sql.SQLException - if connection cannnot be retrieved due to the underlying data source error.
See Also:
getNoTXConnection(String)

getConnection

public java.sql.Connection getConnection(java.lang.String dataSourceName,
                                         boolean forUpdate)
                                  throws java.sql.SQLException
Gets database connection.

When this method is called and there is an active transaction associated with the calling thread, that is beginTransaction was called to start transaction and bind the transaction context to the thread, the returned connection is enrolled in the transaction context. If there is no active transaction context for the thread, then the behaviour of this method is determined by the configured transaction control mode (see description of com.boylesoftware.cb2.txControlMode application property) and forUpdate parameter: it may return a raw connection directly from the underlying data source, like getNoTXConnection does, or it may throw an exception.

Parameters:
dataSourceName - name of the data source as defined in the cb2app.properties configuration file. If null, "default" is assumed.
forUpdate - should be set to true if the requested connection is going to be used for database updates, that is any operations that modify data in the database and thus better be performed in a transaction. If the connection is going to be used only to read data from the database, this parameter should be false.
Returns:
connection to the database, possibly enrolled in the current transaction.
Throws:
java.sql.SQLException - if the connection cannot be retrieved due to the underlying data source error.
java.lang.IllegalStateException - if there is no transaction context associated with the thread and the current transaction control mode requires the method to throw an error.
See Also:
getConnection(TransactionContext, String)

getConnection

public static java.sql.Connection getConnection(TransactionContext txCtx)
                                         throws java.sql.SQLException
Convenience method, which calls getConnection(txCtx, "default") internally.

Parameters:
txCtx - the transaction context.
Returns:
connection to the default database enrolled in the specified transaction context.
Throws:
java.sql.SQLException - if the connection cannot be retrieved due to the underlying data source error.
See Also:
getConnection(TransactionContext, String)

getConnection

public java.sql.Connection getConnection(boolean forUpdate)
                                  throws java.sql.SQLException
Convenience method, which calls getConnection("default", forUpdate) internally.

Parameters:
forUpdate - tells if the connection is going to be used for modifying data in the database.
Returns:
connection to the default database enrolled in the current transaction if there is any.
Throws:
java.sql.SQLException - if the connection cannot be retrieved due to the underlying data source error.
java.lang.IllegalStateException - if there is no transaction context associated with the thread and the current transaction control mode requires the method to throw an error.
See Also:
getConnection(String, boolean)

getConnection

public java.sql.Connection getConnection()
                                  throws java.sql.SQLException
Convenience method, which calls getConnection("default", true) internally.

Returns:
connection to the default database enrolled in the current transaction if there is any.
Throws:
java.sql.SQLException - if the connection cannot be retrieved due to the underlying data source error.
java.lang.IllegalStateException - if there is no transaction context associated with the thread and the current transaction control mode requires the method to throw an error.
See Also:
getConnection(String, boolean)

isDatabaseAvailable

public boolean isDatabaseAvailable()
Tells if the database subsystem is enabled for this application context. This method returns false if no data sources are configured in the cb2app.properties file.

Returns:
true if the database services are supported.

getNoTXConnection

public java.sql.Connection getNoTXConnection(java.lang.String dataSourceName)
                                      throws java.sql.SQLException
Gets database connection directly from the data source. Connection returned by this method is not managed by the application context's transaction management subsystem, as opposed to connection returned by getConnection methods. Usually there is no reason to call this method from the application code unless it is really necessary to manage transactions in some specific way, which is not supported by the framework.

Parameters:
dataSourceName - name of the data source as defined in the cb2app.properties configuration file. If null, "default" is assumed.
Returns:
database connection or null if the database access subsystem is turned off for this application context (see isDatabaseAvailable method).
Throws:
java.sql.SQLException - if error happens in the undelying data source object.
java.lang.IllegalArgumentException - if there is no data source with the specified name.

getNoTXConnection

public java.sql.Connection getNoTXConnection()
                                      throws java.sql.SQLException
Convenience method, which calls getNoTXConnection("default") internally.

Returns:
connection to the default database or null if the database access subsystem is turned off for this application context.
Throws:
java.sql.SQLException - if error happens in the undelying data source object.
java.lang.IllegalArgumentException - if there is no default data source.
See Also:
getNoTXConnection(String)

isBCMEnabled

public boolean isBCMEnabled()
Tells if the CB2 Broadcast Messaging subsystem (the BCM) is enabled. The BCM is disabled if no com.boylesoftware.cb2.broadcastMessaging.provider.class application property is provided. If the BCM is disabled, the broadcastBCMMessage method does nothing and returns immediately.

Returns:
true if the BCM is enabled and the broadcastBCMMessage method can be used to deliver broadcast messages to the cluster members.

registerBCMTerminal

public void registerBCMTerminal(java.lang.String channelName,
                                BroadcastMessagingTerminal bcmTerminal)
Registers a BCM terminal on the specified channel. Application context will call the terminal's processMessage method each time a message is received on the channel.

If there was already a terminal registered on the channel, it is overwritten by the new one. ?nly one terminal can be subscribed to a channel at a time.

Parameters:
channelName - name of the BCM channel, to which the terminal will be subscribed.
bcmTerminal - the terminal object.
See Also:
broadcastBCMMessage(java.lang.String, java.io.Serializable)

unregisterBCMTerminal

public void unregisterBCMTerminal(java.lang.String channelName)
Unregisters the BCM terminal set on the specified channel. Does nothing if no terminal is registered on the channel.

Parameters:
channelName - the BCM channel name.

broadcastBCMMessage

public void broadcastBCMMessage(java.lang.String channelName,
                                java.io.Serializable messageParam)
Sends a message to all cluster members through the CB2 Broadcast Messaging subsystem (the BCM). BCM terminals registered on the specified channel in all CB2 application instances that are members of the cluster will receive the message. This includes the local instance, which sends the message. Note, however, that depending on the BCM provider imlementation, it is possible that this method returns before the message is received and processed by the BCM terminal on the local instance (and any remote instance as well).

Parameters:
channelName - BCM channel, to which the method sends the message.
messageParam - optional general purpose message parameter, may be null.

processBCMMessage

public void processBCMMessage(java.lang.String channelName,
                              java.lang.String source,
                              java.io.Serializable messageParam)
                       throws ApplicationException
Processes a received through the CB2 Broadcast Messaging subsystem message by calling processMessage method on the appropriate terminal. This method is a part of SPI, there is no need for the user application code to call this method. Instead, Broadcast Messaging provider implementations call this method when they receive a message to deliver it to the appropriate terminal.

Parameters:
channelName - channel on which the message is received.
source - identifier, specific to the Broadcast Messaging provider implementation, which identifies the JVM that sent the message.
messageParam - optional parameter received with the message, may be null.
Throws:
ApplicationException - if an unexpected error happens while processing the message in the terminal. The provider implementation should log the error and continue operation.

cancelStatement

public void cancelStatement(java.lang.Long id)
Tries to cancel an active database statement. Application context keeps track of all statements executed on any database connection aquired through the application context. List of currently active statements with their ids can be retrieved from the output of getStats method.

This method does nothing if there is no statement with the specified id.

If an error happens cancelling the statement the method logs the error message to the application log but does not throw any exception. If the statement is cancelled successfully, the thread, which was executing it, will most likely get an exception. The exact behaviour depends on the JDBC driver implementation.

Parameters:
id - the statement's id.

cancelAllStatements

public void cancelAllStatements()
Tries to cancel all currently active database statements.

See Also:
cancelStatement(java.lang.Long)

getStats

public byte[] getStats()
                throws java.lang.Exception
Retrieves application context information and returns it as XML. The data inlcudes basic JVM information, application and system properties, class loader chain, contents of JNDI, information on the data sources, active database statements.

Specified by:
getStats in interface StatusProvider
Returns:
complete application context information XML.
Throws:
java.lang.Exception - if an unexpected error happens.

getEventStats

public EventStatistics getEventStats(java.lang.String eventName)
Gets event statistics for various events. This method understands the following eventName values:

Specified by:
getEventStats in interface StatusProvider
Parameters:
eventName - implementation specific event name, for which current statistics are requested.
Returns:
statistics information for the specified event or null if the event is unknown.


Copyright © 2002,2003,2004 - Boyle Software, Inc.