Saturday, May 27, 2017

JBoss DataSource Configuration

1. Install a JDBC Driver

1.1. Install a JDBC Driver as a Core Module

A JDBC driver installed as a core module provides better start up server behavior.


·        Create a directory under $JBOSS_HOME/modules. e.g.: "$JBOSS_HOME/modules/com/oracle/jdbc/main".
·        Put the the JDBC driver jar (ojdbc6.jar) in this directory.
·        Create a module configuration file module.xml:



<?xml version="1.0" ?>
<module xmlns="urn:jboss:module:1.1" name="com.oracle">
    <resources>
        <resource-root path="ojdbc6.jar"/>
    </resources>
    <dependencies>
        <module name="javax.api"/>
        <module name="javax.transaction.api"/>
    </dependencies>
</module>



1.2.    As a regular JAR deployment

A JDBC-4 compliant JDBC driver also could be installed as a regular JAR. If an application server runs in domain mode, deployments are automatically propagated to all servers to which the deployment applies.

Any JDBC 4-compliant driver will automatically be recognized and installed into the system by name and version. A JDBC JAR is identified using the Java service provider mechanism. Such JARs will contain a text a file named META-INF/services/java.sql.Driver.

1.3. How to make a JDBC driver Jar to be JDBC4-compaliant

Create a META-INF directory, then a META-INF/services subdirectory.
Create a META-INF/services/java.sql.Driver file
In the java.sql.Driver file should contain: the fully-qualified class name(s) of the JDBC driver(s).
Add the java.sql.Driver file to the JAR:



jar -uf jdbc-driver.jar META-INF/services/java.sql.Driver



2. Configure DataSource

In standalone.xml




<datasources>
  <datasource jndi-name="java:jboss/OracleDS" pool-name="OracleDS">
    <connection-url>jdbc:oracle:thin:@localhost:1521:XE</connection-url>
    <driver>oracle</driver>
    <pool>
        <min-pool-size>10</min-pool-size>
        <max-pool-size>20</max-pool-size>
        <prefill>true</prefill>
    </pool>
    <security>
        <user-name>admin</user-name>
        <password>admin</password>
    </security>
    <validation>
        <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker"/>
        <validate-on-match>true</validate-on-match>
        <background-validation>false</background-validation>
        <stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleStaleConnectionChecker"/>
        <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleExceptionSorter"/>
    </validation>
    <!-- use this in dev/qa to find out connection leaking     
                    <statement>
                           <track-statements>true</track-statements>
                    </statement>
    -->
  </datasource>
  <drivers>
    <driver name="oracle" module="com.oracle">
        <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
    </driver>
  </drivers>
</datasources>



3. Configuring the Connection Pool


Here is a table from JBoss document that lists available parameters and their defaulta values for JBoss EAP 6.x



Connection Pool Properties


Name
Key
Default Value
Description
Connection Pool Enabled
ConnectionPoolEnabled
Explicitly enables or disables connection pooling.
Data Source Test Connect Interval (seconds)
SourceConnectionTestInterval
600
How often (in seconds) to create test connections to the underlying source to see if it is available.
Pool Maximum Connections
com.metamatrix.data. ~pool.max_connections
20
Maximum number of connections total in the pool.  This value should be greater than 0.
Pool Maximum Connections for Each ID
com.metamatrix.data. ~pool.max_connections_for_each_id
20
Maximum number of connections per ConnectorIdentity object.  This value should be greater than 0.
Pool Connection Idle Time (seconds)
com.metamatrix.data. ~pool.live_and_unused_time
60
Maximum idle time (in seconds) before a connection is closed if shrinking is enabled.
Pool Connection Waiting Time (milliseconds)
com.metamatrix.data. ~pool.wait_for_source_time
120000
Maximum time to wait (in milliseconds) for a connection to become available.
Pool cleaning Interval (seconds)
com.metamatrix.data. ~pool.cleaning_interval
60
Interval (in seconds) between checking for idle connections if shrinking is enabled.
Enable Pool Shrinking
com.metamatrix.data. ~pool.enable_shrinking
true
Indicate whether the pool is allowed to shrink.


4. Connection Validation

4.1 Validation Methods

4.1.1. <validate-on-match>true</validate-on-match>

The database connection is validated every time it is checked out from the connection pool using the validation class specified by one of the validation mechanisms.
  • If a connection is not valid, a warning is written to the log and it retrieves the next connection in the pool. This process continues until a valid connection is found. 
  • If <use-fast-fail> option is used then if a valid connection is not found in the pool, a new connection is created. 
  • If the connection creation fails, an exception is returned to the requesting application.
According to JBoss document, "this setting results in the quickest recovery but creates the highest load on the database. However, this is the safest selection if the minimal performance hit is not a concern."

4.1.2. <background-validation>true</background-validation>

This option is used in combination with the <background-validation-millis> value to determine how often background validation runs in a separate thread. 

The default value for the <background-validation-millis> parameter is 0, so it is disabled by default. This value should not be set to the same value as your <idle-timeout-minutes> setting.

The lower the <background-validation-millis> value, the pool is validated and the sooner and invalid connections are removed from the pool sooner. But the lower values take more database resources. Higher values is used then dead connections are undetected for longer periods of time.

Note:

The <validate-on-match> option and <background-validation> option should not be set true at the same time.

4.2. Validation Mechanisms


One of the following mechanism should be chosen.

4.2.1. <valid-connection-checker>

There are checkers provided by JBoss EAP 6.x and they are optimized for the particular RDBMS.



org.jboss.jca.adapters.jdbc.extensions.db2.DB2ValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.mssql.MSSQLValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLReplicationValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.novendor.JDBC4ValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.novendor.NullValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.sybase.SybaseValidConnectionChecker


4.2.2. <check-valid-connection-sql>

A SQL statement is used to validate the connection.

5. Exception Handling

5.1. <exception-sorter>


According to JBoss document:


When an exception is marked as fatal, the connection is closed immediately, even if the connection is participating in a transaction. Use the exception sorter class option to properly detect and clean up after fatal connection exceptions. 

JBoss EAP 6 provides the following exception sorters:



org.jboss.jca.adapters.jdbc.extensions.db2.DB2ValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.mssql.MSSQLValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLReplicationValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.novendor.JDBC4ValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.novendor.NullValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker
org.jboss.jca.adapters.jdbc.extensions.sybase.SybaseValidConnectionChecker


6. DataSource Parameters

6.1. Common Datasource Parameters

Original JBoss Document.


<datasource jndi-name="java:jboss/datasources/postgresDB" pool-name="postgresDSPOOL"
enabled="true" jta="false" use-java-context="true" use-ccm="false">



<mbean>
A standard JBoss MBean deployment.

<depends>
The ObjectName of an MBean service this ConnectionFactory or DataSource deployment depends upon.

<jndi-name>
The JNDI name under which the Datasource should be bound.

<use-java-context>
Boolean value indicating whether the jndi-name should be prefixed with java:. This prefix causes the Datasource to only be accessible from within the JBoss Enterprise Platform virtual machine. Defaults to TRUE.

<user-name>
The user name used to create the connection to the datasource.
Note
Not used when security is configured.

<password>
The password used to create the connection to the datasource.
Note
Not used when security is configured.

<transaction-isolation>
The default transaction isolation of the connection. If not specified, the database-provided default is used.

Possible values for <transaction-isolation>

TRANSACTION_READ_UNCOMMITTED
TRANSACTION_READ_COMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE
TRANSACTION_NONE

<new-connection-sql>
An SQL statement that is executed against each new connection. This can be used to set up the connection schema, for instance.

<check-valid-connection-sql>
An SQL statement that is executed before the connection is checked out from the pool to make sure it is still valid. If the SQL statement fails, the connection is closed and a new one is created.

<valid-connection-checker-class-name>
A class that checks whether a connection is valid using a vendor-specific mechanism.

<exception-sorter-class-name>
A class that parses vendor-specific messages to determine whether SQL errors are fatal, and destroys the connection if so. If empty, no errors are treated as fatal.

<track-statements>
Whether to monitor for unclosed Statements and ResultSets and issue warnings when they haven't been closed. The default value is NOWARN.

<prepared-statement-cach-size>
The number of prepared statements per connection to be kept open and reused in subsequent requests. They are stored in a Least Recently Used (LRU) cache. The default value is 0, meaning that no cache is kept.

<share-prepared-statements>
When the <prepared-statement-cache-size> is non-zero, determines whether two requests in the same transaction should return the same statement. Defaults to FALSE.

Example of Using <share-prepared-statements>

The goal is to work around questionable driver behavior, where the driver applies auto-commit semantics to local transactions.
       Connection c = dataSource.getConnection(); // auto-commit == false
       PreparedStatement ps1 = c.prepareStatement(...);
       ResultSet rs1 = ps1.executeQuery();
       PreparedStatement ps2 = c.prepareStatement(...);
       ResultSet rs2 = ps2.executeQuery();
This assumes that the prepared statements are the same. For some drivers, ps2.executeQuery() automatically closes rs1, so you actually need two real prepared statements behind the scenes. This only applies to the auto-commit semantic, where re-running the query starts a new transaction automatically. For drivers that follow the specification, you can set it to TRUE to share the same real prepared statement.

<set-tx-query-timeout>
Whether to enable query timeout based on the length of time remaining until the transaction times out. Defaults to FALSE.

<query-timeout>
The maximum time, in seconds, before a query times out. You can override this value by setting <set-tx-query-timeout> to TRUE.

<validate-on-match>
Whether to validate the connection when the JCA layer matches a managed connection, such as when the connection is checked out of the pool. With the addition of <background-validation> this is not required. It is usually not necessary to specify TRUE for <validate-on-match> in conjunction with specifying TRUE for <background-validation>. Defaults to TRUE.

<prefill>
Whether to attempt to prefill the connection pool to the minimum number of connections. Only supporting pools (OnePool) support this feature. A warning is logged if the pool does not support prefilling. Defaults to TRUE.

<background-validation>
Background connection validation reduces the overall load on the RDBMS system when validating a connection. When using this feature, EAP checks whether the current connection in the pool a seperate thread (ConnectionValidator). <background-validation-millis> depends on this value also being set to TRUE. Defaults to FALSE.

<background-validation-millis>
Background connection validation reduces the overall load on the RDBMS system when validating a connection. Setting this parameter means that JBoss will attempt to validate the current connections in the pool as a separate thread (ConnectionValidator). This parameter's value defines the interval, in milliseconds, for which the ConnectionValidator will run. (This value should not be the same as your <idle-timeout-minutes value.)

<idle-timeout-minutes>
The maximum time, in minutes, before an idle connection is closed. A value of 0 disables timeout. Defaults to 15 minutes.

<track-connection-by-tx>
Whether the connection should be locked to the transaction, instead of returning it to the pool at the end of the transaction. In previous releases, this was true for local connection factories and false for XA connection factories. The default is now true for both local and XA connection factories, and the element has been deprecated.

<interleaving>
Enables interleaving for XA connection factories.

<background-validation-millis>
How often, in minutes, the ConnectionValidator runs. Defaults to 10 minutes.

Note
You should set this to a smaller value than <idle-timeout-minutes>, unless you have specified <min-pool-size> a minimum pool size set.

<url-delimiter>, <url-property>, <url-selector-strategy-class-name>
Parameters dealing with database failover. As of JBoss Enterprise Platform 5.1, these are configured as part of the main datasource configuration. In previous versions, <url-delimiter> appeared as <url-delimeter>.

<stale-connection-checker-class-name>
An implementation of org.jboss.resource.adapter.jdbc.StateConnectionChecker that decides whether SQLExceptions that notify of bad connections throw the org.jboss.resource.adapter.jdbc.StateConnectionException exception.

<max-pool-size>
The maximum number of connections allowed in the pool. Defaults to 20.

<min-pool-size>
The minimum number of connections maintained in the pool. Unless <prefill> is TRUE, the pool remains empty until the first use, at which point the pool is filled to the <min-pool-size>. When the pool size drops below the <min-pool-size> due to idle timeouts, the pool is refilled to the <min-pool-size>. Defaults to 0.

<blocking-timeout-millis>
The length of time, in milliseconds, to wait for a connection to become available when all the connections are checked out. Defaults to 30000, which is 30 seconds.

<use-fast-fail>
Whether to continue trying to acquire a connection from the pool even if the previous attempt has failed, or begin failover. This is to address performance issues where validation SQL takes significant time and resources to execute. Defaults to FALSE.

Parameters for javax.sql.XADataSource Usage

<connection-url>
The JDBC driver connection URL string

<driver-class>
The JDBC driver class implementing the java.sql.Driver

<connection-property>
Used to configure the connections retrieved from the java.sql.Driver.

Example <connection-property>

<connection-property name="char.encoding">UTF-8</connection-property>

Parameters for javax.sql.XADataSource Usage

<xa-datasource-class>
The class implementing the XADataSource

<xa-datasource-property>
Properties used to configure the XADataSource.

Example <xa-datasource-property> Declarations

<xa-datasource-property name="IfxWAITTIME">10</xa-datasource-property>
<xa-datasource-property name="IfxIFXHOST">myhost.mydomain.com</xa-datasource-property>
<xa-datasource-property name="PortNumber">1557</xa-datasource-property>
<xa-datasource-property name="DatabaseName">mydb</xa-datasource-property>
<xa-datasource-property name="ServerName">myserver</xa-datasource-property>

<xa-resource-timeout>
The number of seconds passed to XAResource.setTransactionTimeout() when not zero.

<isSameRM-override-value>
When set to FALSE, fixes some problems with Oracle databases.

<no-tx-separate-pools>
Pool transactional and non-transactinal connections separately

Warning
Using this option will cause your total pool size to be twice max-pool-size, because two actual pools will be created.
Used to fix problems with Oracle.
Security Parameters

<application-managed-security>
Uses the username and password passed on the getConnection or createConnection request by the application.

<security-domain>
Uses the identified login module configured in conf/login-module.xml.

<security-domain-and-application>
Uses the identified login module configured in conf/login-module.xml and other connection request information supplied by the application, for example JMS Queues and Topics.

Parameters for XA Recovery in the JCA Layer

<recover-user-name>
The user with credentials to perform a recovery operation.

<recover-password>
Password of the user with credentials to perform a recovery operation.

<recover-security-domain>
Security domain for recovery.

<no-recover>
Excludes a datasource from recovery.

The fields in Parameters for XA Recovery in the JCA Layershould have a fall back value of their non-recover counterparts: <user-name>,< password> and <security-domain>.



Another sample:



<subsystem xmlns="urn:jboss:domain:datasources:1.0">
       <datasources>
             <datasource enabled="true"
                    jndi-name="java:jboss/datasources/bookingDatasource" jta="true"
                    pool-name="bookingDatasource" use-ccm="true" use-java-context="true">
                    <connection-url>jdbc:hsqldb:.</connection-url>
                    <transaction-isolation>TRANSACTION_NONE</transaction-isolation>
                    <pool>
                           <prefill>false</prefill>
                           <use-strict-min>false</use-strict-min>
                           <flush-strategy>FailingConnectionOnly</flush-strategy>
                    </pool>
                    <security>
                           <user-name>sa</user-name>
                           <password />
                    </security>
                    <validation>
                           <validate-on-match>false</validate-on-match>
                           <background-validation>false</background-validation>
                           <use-fast-fail>false</use-fast-fail>
                    </validation>
                    <timeout />
                    <statement>
                           <track-statements>true</track-statements>
                    </statement>
             </datasource>
             <!-- The following drivers element was not in the generated XML snippet.
                    We added this manually. -->
             <drivers>
                    <driver name="h2" module="com.h2database.h2">
                           <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
                    </driver>
             </drivers>
       </datasources>
</subsystem>



JBoss EAP 6.4



  • allocation-retry The allocation retry element indicates the number of times that allocating a connection should be tried before throwing an exception
  • allocation-retry-wait-millis The allocation retry wait millis element specifies the amount of time, in milliseconds, to wait between retrying to allocate a connection
  • allow-multiple-users Specifies if multiple users will access the datasource through the getConnection(user, password) method and hence if the internal pool type should account for that
  • background-validation An element to specify that connections should be validated on a background thread versus being validated prior to use. Changing this value can be done only on disabled datasource, requires a server restart otherwise.
  • background-validation-millis The background-validation-millis element specifies the amount of time, in milliseconds, that background validation will run. Changing this value can be done only on disabled datasource, requires a server restart otherwise
  • blocking-timeout-wait-millis The blocking-timeout-millis element specifies the maximum time, in milliseconds, to block while waiting for a connection before throwing an exception. Note that this blocks only while waiting for locking a connection, and will never throw an exception if creating a new connection takes an inordinately long time
  • check-valid-connection-sql Specify an SQL statement to check validity of a pool connection. This may be called when managed connection is obtained from the pool
  • connectable Enable the use of CMR. This feature means that a local resource can reliably participate in an XA transaction.
  • connection-url The JDBC driver connection URL
  • datasource-class The fully qualified name of the JDBC datasource class
  • driver-class The fully qualified name of the JDBC driver class
  • driver-name Defines the JDBC driver the datasource should use. It is a symbolic name matching the the name of installed driver. In case the driver is deployed as jar, the name is the name of deployment unit
  • enabled Specifies if the datasource should be enabled. Note this attribute will not be supported runtime in next versions.
  • exception-sorter-class-name An org.jboss.jca.adapters.jdbc.ExceptionSorter that provides an isExceptionFatal(SQLException) method to validate if an exception should broadcast an error
  • exception-sorter-properties The exception sorter properties
  • flush-strategy Specifies how the pool should be flush in case of an error. Valid values are: FailingConnectionOnly (default), IdleConnections and EntirePool
  • idle-timeout-minutes The idle-timeout-minutes elements specifies the maximum time, in minutes, a connection may be idle before being closed. The actual maximum time depends also on the IdleRemover scan time, which is half of the smallest idle-timeout-minutes value of any pool. Changing this value can be done only on disabled datasource, requires a server restart otherwise.
  • jndi-name Specifies the JNDI name for the datasource
  • jta Enable JTA integration
  • max-pool-size The max-pool-size element specifies the maximum number of connections for a pool. No more connections will be created in each sub-pool
  • min-pool-size The min-pool-size element specifies the minimum number of connections for a pool
  • new-connection-sql Specifies an SQL statement to execute whenever a connection is added to the connection pool
  • password Specifies the password used when creating a new connection
  • pool-prefill Should the pool be prefilled. Changing this value can be done only on disabled datasource, requires a server restart otherwise.
  • pool-use-strict-min Specifies if the min-pool-size should be considered strictly
  • prepared-statements-cache-size The number of prepared statements per connection in an LRU cache
  • query-timeout Any configured query timeout in seconds. If not provided no timeout will be set
  • reauth-plugin-class-name The fully qualified class name of the reauthentication plugin implementation
  • reauth-plugin-properties The properties for the reauthentication plugin
  • security-domain Specifies the security domain which defines the javax.security.auth.Subject that are used to distinguish connections in the pool
  • set-tx-query-timeout Whether to set the query timeout based on the time remaining until transaction timeout. Any configured query timeout will be used if there is no transaction
  • share-prepared-statements Whether to share prepared statements, i.e. whether asking for same statement twice without closing uses the same underlying prepared statement
  • spy Enable spying of SQL statements
  • stale-connection-checker-class-name An org.jboss.jca.adapters.jdbc.StaleConnectionChecker that provides an isStaleConnection(SQLException) method which if it returns true will wrap the exception in an org.jboss.jca.adapters.jdbc.StaleConnectionException
  • stale-connection-checker-properties The stale connection checker properties
  • statistics Runtime statistics provided by the resource adapter.
  • statistics-enabled define if runtime statistics is enabled or not.
  • track-statements Whether to check for unclosed statements when a connection is returned to the pool, result sets are closed, a statement is closed or return to the prepared statement cache. Valid values are: "false" - do not track statements, "true" - track statements and result sets and warn when they are not closed, "nowarn" - track statements but do not warn about them being unclosed
  • transaction-isolation Set the java.sql.Connection transaction isolation level. Valid values are: TRANSACTION_READ_UNCOMMITTED, TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ, TRANSACTION_SERIALIZABLE and TRANSACTION_NONE
  • url-delimiter Specifies the delimiter for URLs in connection-url for HA datasources
  • url-selector-strategy-class-name A class that implements org.jboss.jca.adapters.jdbc.URLSelectorStrategy
  • use-ccm Enable the use of a cached connection manager
  • use-fast-fail Whether to fail a connection allocation on the first try if it is invalid (true) or keep trying until the pool is exhausted of all potential connections (false)
  • use-java-context Setting this to false will bind the datasource into global JNDI
  • use-try-lock Any configured timeout for internal locks on the resource adapter objects in seconds
  • user-name Specify the user name used when creating a new connection
  • valid-connection-checker-class-name An org.jboss.jca.adapters.jdbc.ValidConnectionChecker that provides an isValidConnection(Connection) method to validate a connection. If an exception is returned that means the connection is invalid. This overrides the check-valid-connection-sql element
  • valid-connection-checker-properties The valid connection checker properties
  • validate-on-match The validate-on-match element specifies if connection validation should be done when a connection factory attempts to match a managed connection. This is typically exclusive to the use of background validation


jboss-as-datasources_1_2.xsd


    1 <?xml version="1.0" encoding="UTF-8"?>
    2 <!--
    3   ~ JBoss, Home of Professional Open Source.
    4   ~ Copyright 2011, Red Hat, Inc., and individual contributors
    5   ~ as indicated by the @author tags. See the copyright.txt file in the
    6   ~ distribution for a full listing of individual contributors.
    7   ~
    8   ~ This is free software; you can redistribute it and/or modify it
    9   ~ under the terms of the GNU Lesser General Public License as
   10   ~ published by the Free Software Foundation; either version 2.1 of
   11   ~ the License, or (at your option) any later version.
   12   ~
   13   ~ This software is distributed in the hope that it will be useful,
   14   ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
   15   ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
   16   ~ Lesser General Public License for more details.
   17   ~
   18   ~ You should have received a copy of the GNU Lesser General Public
   19   ~ License along with this software; if not, write to the Free
   20   ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
   21   ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
   22   -->
   23 
   24 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
   25            targetNamespace="urn:jboss:domain:datasources:1.2" xmlns="urn:jboss:domain:datasources:1.2"
   26            elementFormDefault="qualified" attributeFormDefault="unqualified">
   27 
   28   <xs:element name="subsystem" type="subsystemType"/>
   29 
   30   <xs:complexType name="subsystemType">
   31     <xs:all>
   32       <xs:element name="datasources" type="datasourcesType" minOccurs="1" maxOccurs="1"/>
   33     </xs:all>
   34   </xs:complexType>
   35 
   36   <xs:complexType name="datasourcesType">
   37     <xs:sequence>
   38       <xs:choice minOccurs="0" maxOccurs="unbounded">
   39         <xs:element name="datasource" type="datasourceType">
   40           <xs:annotation>
   41             <xs:documentation>
   42               <![CDATA[[
   43                 Specifies a non-XA datasource, using local transactions
   44                ]]>
   45             </xs:documentation>
   46           </xs:annotation>
   47         </xs:element>
   48         <xs:element name="xa-datasource" type="xa-datasourceType">
   49           <xs:annotation>
   50             <xs:documentation>
   51               <![CDATA[[
   52                 Specifies a XA datasource
   53                 ]]>
   54             </xs:documentation>
   55           </xs:annotation>
   56         </xs:element>
   57       </xs:choice>
   58       <xs:element name="drivers" type="driversType" maxOccurs="1" minOccurs="0"></xs:element>
   59     </xs:sequence>
   60   </xs:complexType>
   61   <xs:complexType name="datasourceType" mixed="false">
   62     <xs:sequence>
   63       <xs:element name="connection-url" type="xs:token">
   64         <xs:annotation>
   65           <xs:documentation>
   66             <![CDATA[[
   67               The JDBC driver connection URL Ex: <connection-url>jdbc:hsqldb:hsql://localhost:1701</connection-url>
   68              ]]>
   69           </xs:documentation>
   70         </xs:annotation>
   71       </xs:element>
   72       <xs:element name="driver-class" type="xs:token" maxOccurs="1" minOccurs="0">
   73         <xs:annotation>
   74           <xs:documentation>
   75             <![CDATA[[
   76               The fully qualifed name of the JDBC driver class Ex: <driver-class>org.hsqldb.jdbcDriver</driver-class>
   77              ]]>
   78           </xs:documentation>
   79         </xs:annotation>
   80       </xs:element>
   81       <xs:element name="datasource-class" type="xs:token" maxOccurs="1" minOccurs="0">
   82         <xs:annotation>
   83           <xs:documentation>
   84             <![CDATA[[
   85               The fully qualifed name of the JDBC datasource class Ex: <datasource-class>org.h2.jdbcx.JdbcDataSource</datasource-class>
   86              ]]>
   87           </xs:documentation>
   88         </xs:annotation>
   89       </xs:element>
   90       <xs:element name="driver" type="xs:token" minOccurs="0">
   91         <xs:annotation>
   92           <xs:documentation>
   93             <![CDATA[[
   94               An unique reference to the classloader module which contains the JDBC driver
   95               The accepted format is driverName#majorVersion.minorVersion
   96              ]]>
   97           </xs:documentation>
   98         </xs:annotation>
   99       </xs:element>
  100       <xs:element name="connection-property" type="connection-propertyType" minOccurs="0" maxOccurs="unbounded">
  101         <xs:annotation>
  102           <xs:documentation>
  103             <![CDATA[[
  104               The connection-property element allows you to pass in arbitrary connection
  105               properties to the Driver.connect(url, props) method. Each connection-property
  106               specifies a string name/value pair with the property name coming from the
  107               name attribute and the value coming from the element content. Ex:
  108               <connection-property name="char.encoding">UTF-8</connection-property>
  109              ]]>
  110           </xs:documentation>
  111         </xs:annotation>
  112       </xs:element>
  113       <xs:element name="new-connection-sql" type="xs:string" minOccurs="0">
  114         <xs:annotation>
  115           <xs:documentation>
  116             <![CDATA[[
  117               Specify an SQL statement to execute whenever a connection is added
  118               to the connection pool.
  119               ]]>
  120           </xs:documentation>
  121         </xs:annotation>
  122       </xs:element>
  123       <xs:element name="transaction-isolation" type="transaction-isolationType" minOccurs="0">
  124         <xs:annotation>
  125           <xs:documentation>
  126             <![CDATA[[
  127               Set java.sql.Connection transaction isolation level to use. The constants
  128               defined by transaction-isolation-values are the possible transaction isolation
  129               levels and include: TRANSACTION_READ_UNCOMMITTED TRANSACTION_READ_COMMITTED
  130               TRANSACTION_REPEATABLE_READ TRANSACTION_SERIALIZABLE TRANSACTION_NONE
  131              ]]>
  132           </xs:documentation>
  133         </xs:annotation>
  134       </xs:element>
  135       <xs:element name="url-delimiter" type="xs:token" minOccurs="0">
  136         <xs:annotation>
  137           <xs:documentation>
  138             <![CDATA[[
  139               Specifies the delimeter for URLs in connection-url for HA datasources
  140              ]]>
  141           </xs:documentation>
  142         </xs:annotation>
  143       </xs:element>
  144       <xs:element name="url-selector-strategy-class-name" type="xs:token" minOccurs="0">
  145         <xs:annotation>
  146           <xs:documentation>
  147             <![CDATA[[
  148               A class that implements org.jboss.jca.adapters.jdbc.URLSelectorStrategy
  149              ]]>
  150           </xs:documentation>
  151         </xs:annotation>
  152       </xs:element>
  153       <xs:element name="pool" type="poolType" minOccurs="0" maxOccurs="1">
  154         <xs:annotation>
  155           <xs:documentation>
  156             <![CDATA[[
  157               Specifies the pooling settings
  158              ]]>
  159           </xs:documentation>
  160         </xs:annotation>
  161       </xs:element>
  162       <xs:element name="security" type="dsSecurityType" minOccurs="0">
  163         <xs:annotation>
  164           <xs:documentation>
  165             <![CDATA[[
  166               Specifies the security settings
  167              ]]>
  168           </xs:documentation>
  169         </xs:annotation>
  170       </xs:element>
  171       <xs:element name="validation" type="validationType" minOccurs="0">
  172         <xs:annotation>
  173           <xs:documentation>
  174             <![CDATA[[
  175               Specifies the validation settings
  176              ]]>
  177           </xs:documentation>
  178         </xs:annotation>
  179       </xs:element>
  180       <xs:element name="timeout" type="timeoutType" minOccurs="0">
  181         <xs:annotation>
  182           <xs:documentation>
  183             <![CDATA[[
  184               Specifies the time out settings
  185              ]]>
  186           </xs:documentation>
  187         </xs:annotation>
  188       </xs:element>
  189       <xs:element name="statement" type="statementType" minOccurs="0">
  190         <xs:annotation>
  191           <xs:documentation>
  192             <![CDATA[[
  193               Specifies the statement settings
  194              ]]>
  195           </xs:documentation>
  196         </xs:annotation>
  197       </xs:element>
  198     </xs:sequence>
  199     <xs:attribute name="jta" type="xs:boolean" default="true" use="optional">
  200       <xs:annotation>
  201         <xs:documentation>
  202           <![CDATA[[
  203             Enable JTA integration
  204            ]]>
  205         </xs:documentation>
  206       </xs:annotation>
  207     </xs:attribute>
  208     <xs:attribute default="false" name="connectable" type="xs:boolean">
  209         <xs:annotation>
  210             <xs:documentation>
  211                 <![CDATA[[
  212                           Enable cmr functionality on this datsource's connections
  213                          ]]>
  214             </xs:documentation>
  215         </xs:annotation>
  216     </xs:attribute>
  217       <xs:attributeGroup ref="common-datasourceAttributes" />
  218   </xs:complexType>
  219   <xs:complexType name="xa-datasourceType">
  220     <xs:sequence>
  221       <xs:element name="xa-datasource-property" type="xa-datasource-propertyType" minOccurs="1" maxOccurs="unbounded">
  222         <xs:annotation>
  223           <xs:documentation>
  224             <![CDATA[[
  225               Specifies a property to assign to the XADataSource implementation class.
  226               Each property is identified by the name attribute and the property value
  227               is given by the xa-datasource-property element content. The property is mapped
  228               onto the XADataSource implementation by looking for a JavaBeans style getter
  229               method for the property name. If found, the value of the property is set
  230               using the JavaBeans setter with the element text translated to the true property
  231               type using the java.beans.PropertyEditor for the type. Ex:
  232               <xa-datasource-property name="IfxWAITTIME">10</xa-datasource-property>
  233               <xa-datasource-property name="IfxIFXHOST">myhost.mydomain.com</xa-datasource-property>
  234               <xa-datasource-property name="PortNumber">1557</xa-datasource-property>
  235               <xa-datasource-property name="DatabaseName">mydb</xa-datasource-property>
  236               <xa-datasource-property name="ServerName">myserver</xa-datasource-property>
  237              ]]>
  238           </xs:documentation>
  239         </xs:annotation>
  240       </xs:element>
  241       <xs:element name="xa-datasource-class" type="xs:token" maxOccurs="1" minOccurs="0">
  242         <xs:annotation>
  243           <xs:documentation>
  244             <![CDATA[[
  245               The fully qualifed name of the javax.sql.XADataSource implementation
  246               class. Ex: <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
  247              ]]>
  248           </xs:documentation>
  249         </xs:annotation>
  250       </xs:element>
  251       <xs:element name="driver" type="xs:token" minOccurs="0">
  252         <xs:annotation>
  253           <xs:documentation>
  254             <![CDATA[[
  255               An unique reference to the classloader module which contains the JDBC driver
  256               The accepted format is driverName#majorVersion.minorVersion
  257              ]]>
  258           </xs:documentation>
  259         </xs:annotation>
  260       </xs:element>
  261       <xs:element name="url-delimiter" type="xs:token" minOccurs="0">
  262         <xs:annotation>
  263           <xs:documentation>
  264             <![CDATA[[
  265                Specifies the delimeter for URLs in the connection url for HA datasources
  266               ]]>
  267           </xs:documentation>
  268         </xs:annotation>
  269       </xs:element>
  270       <xs:element name="url-selector-strategy-class-name" type="xs:token" minOccurs="0">
  271         <xs:annotation>
  272           <xs:documentation>
  273             <![CDATA[[
  274                A class that implements org.jboss.jca.adapters.jdbc.URLSelectorStrategy
  275              ]]>
  276           </xs:documentation>
  277         </xs:annotation>
  278       </xs:element>
  279       <xs:element name="new-connection-sql" type="xs:string" minOccurs="0">
  280         <xs:annotation>
  281           <xs:documentation>
  282             <![CDATA[[
  283                Specifies an SQL statement to execute whenever a connection is added
  284                to the connection pool.
  285              ]]>
  286           </xs:documentation>
  287         </xs:annotation>
  288       </xs:element>
  289       <xs:element name="transaction-isolation" type="transaction-isolationType" minOccurs="0">
  290         <xs:annotation>
  291           <xs:documentation>
  292             <![CDATA[[
  293               Set java.sql.Connection transaction isolation level to use. The constants
  294               defined by transaction-isolation-values are the possible transaction isolation
  295               levels and include: TRANSACTION_READ_UNCOMMITTED TRANSACTION_READ_COMMITTED
  296               TRANSACTION_REPEATABLE_READ TRANSACTION_SERIALIZABLE TRANSACTION_NONE
  297              ]]>
  298           </xs:documentation>
  299         </xs:annotation>
  300       </xs:element>
  301       <xs:element name="xa-pool" type="xa-poolType" minOccurs="0" maxOccurs="1">
  302         <xs:annotation>
  303           <xs:documentation>
  304             <![CDATA[[
  305               Specifies the pooling settings
  306              ]]>
  307           </xs:documentation>
  308         </xs:annotation>
  309       </xs:element>
  310       <xs:element name="security" type="dsSecurityType" minOccurs="0">
  311         <xs:annotation>
  312           <xs:documentation>
  313             <![CDATA[[
  314               Specifies the security settings
  315              ]]>
  316           </xs:documentation>
  317         </xs:annotation>
  318       </xs:element>
  319       <xs:element name="validation" type="validationType" minOccurs="0">
  320         <xs:annotation>
  321           <xs:documentation>
  322             <![CDATA[[
  323               Specifies the validation settings
  324              ]]>
  325           </xs:documentation>
  326         </xs:annotation>
  327       </xs:element>
  328       <xs:element name="timeout" type="timeoutType" minOccurs="0">
  329         <xs:annotation>
  330           <xs:documentation>
  331             <![CDATA[[
  332               Specifies the time out settings
  333              ]]>
  334           </xs:documentation>
  335         </xs:annotation>
  336       </xs:element>
  337       <xs:element name="statement" type="statementType" minOccurs="0">
  338         <xs:annotation>
  339           <xs:documentation>
  340             <![CDATA[[
  341               Specifies the statement settings
  342              ]]>
  343           </xs:documentation>
  344         </xs:annotation>
  345       </xs:element>
  346       <xs:element name="recovery" type="recoverType" minOccurs="0" maxOccurs="1"></xs:element>
  347     </xs:sequence>
  348     <xs:attributeGroup ref="common-datasourceAttributes" />
  349   </xs:complexType>
  350   <xs:complexType name="boolean-presenceType" />
  351   <xs:attributeGroup name="common-datasourceAttributes">
  352     <xs:attribute name="jndi-name" type="xs:token" use="required">
  353       <xs:annotation>
  354         <xs:documentation>
  355           <![CDATA[[
  356             Specifies the JNDI name for the datasource
  357            ]]>
  358         </xs:documentation>
  359       </xs:annotation>
  360     </xs:attribute>
  361     <xs:attribute name="pool-name" type="xs:token" use="required">
  362       <xs:annotation>
  363         <xs:documentation>
  364           <![CDATA[[
  365             Specifies the pool name for the datasource used for management
  366            ]]>
  367         </xs:documentation>
  368       </xs:annotation>
  369     </xs:attribute>
  370     <xs:attribute name="enabled" type="xs:boolean" default="true" form="unqualified" use="optional">
  371       <xs:annotation>
  372         <xs:documentation>
  373           <![CDATA[[
  374             Specifies if the datasource should be enabled
  375            ]]>
  376         </xs:documentation>
  377       </xs:annotation>
  378     </xs:attribute>
  379     <xs:attribute default="true" name="use-java-context" type="xs:boolean">
  380       <xs:annotation>
  381         <xs:documentation>
  382           <![CDATA[[
  383             Setting this to false will bind the DataSource into global JNDI
  384             Ex: use-java-context="true"
  385            ]]>
  386         </xs:documentation>
  387       </xs:annotation>
  388     </xs:attribute>
  389     <xs:attribute default="false" name="spy" type="xs:boolean">
  390       <xs:annotation>
  391         <xs:documentation>
  392           <![CDATA[[
  393             Enable spy functionality on the JDBC layer - e.g. log all JDBC traffic to the datasource.
  394             Remember to enable the logging category (org.jboss.jdbc) too.
  395             Ex: spy="true"
  396            ]]>
  397         </xs:documentation>
  398       </xs:annotation>
  399     </xs:attribute>
  400     <xs:attribute default="true" name="use-ccm" type="xs:boolean">
  401       <xs:annotation>
  402         <xs:documentation>
  403           <![CDATA[[
  404             Enable the use of a cached connection manager
  405             Ex: use-ccm="true"
  406            ]]>
  407         </xs:documentation>
  408       </xs:annotation>
  409     </xs:attribute>
  410   </xs:attributeGroup>
  411   <xs:simpleType name="transaction-isolationType">
  412     <xs:annotation>
  413       <xs:documentation>
  414         <![CDATA[[
  415           Define constants used as the possible transaction isolation levels in transaction-isolation
  416           type. Include: TRANSACTION_READ_UNCOMMITTED, TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ,
  417           TRANSACTION_SERIALIZABLE, TRANSACTION_NONE
  418          ]]>
  419       </xs:documentation>
  420     </xs:annotation>
  421     <xs:restriction base="xs:token">
  422       <xs:enumeration value="TRANSACTION_READ_UNCOMMITTED" />
  423       <xs:enumeration value="TRANSACTION_READ_COMMITTED" />
  424       <xs:enumeration value="TRANSACTION_REPEATABLE_READ" />
  425       <xs:enumeration value="TRANSACTION_SERIALIZABLE" />
  426       <xs:enumeration value="TRANSACTION_NONE" />
  427     </xs:restriction>
  428   </xs:simpleType>
  429   <xs:complexType name="xa-datasource-propertyType" mixed="true">
  430     <xs:attribute name="name" use="required" type="xs:token" />
  431   </xs:complexType>
  432   <xs:complexType name="connection-propertyType" mixed="true">
  433     <xs:attribute name="name" use="required" type="xs:token" />
  434   </xs:complexType>
  435   <xs:complexType name="validationType">
  436     <xs:sequence>
  437       <xs:element name="valid-connection-checker" type="extensionType" minOccurs="0">
  438         <xs:annotation>
  439           <xs:documentation>
  440             <![CDATA[[
  441               An org.jboss.jca.adapters.jdbc.ValidConnectionChecker that provides
  442               a SQLException isValidConnection(Connection e) method to validate is a connection
  443               is valid. An exception means the connection is destroyed. This overrides
  444               the check-valid-connection-sql when present. Ex:
  445               <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.vendor.OracleValidConnectionChecker"/>
  446              ]]>
  447           </xs:documentation>
  448         </xs:annotation>
  449       </xs:element>
  450 
  451       <xs:element name="check-valid-connection-sql" type="xs:string" minOccurs="0">
  452         <xs:annotation>
  453           <xs:documentation>
  454             <![CDATA[[
  455               Specify an SQL statement to check validity of a pool connection. This
  456               may be called when managed connection is taken from pool for use.
  457              ]]>
  458           </xs:documentation>
  459         </xs:annotation>
  460       </xs:element>
  461       <xs:element name="validate-on-match" type="xs:boolean" minOccurs="0">
  462         <xs:annotation>
  463           <xs:documentation>
  464             <![CDATA[[
  465               The validate-on-match element indicates whether or not connection
  466               level validation should be done when a connection factory attempts to match
  467               a managed connection for a given set. This is typically exclusive to the
  468               use of background validation
  469              ]]>
  470           </xs:documentation>
  471         </xs:annotation>
  472       </xs:element>
  473       <xs:element name="background-validation" type="xs:boolean" minOccurs="0">
  474         <xs:annotation>
  475           <xs:documentation>
  476             <![CDATA[[
  477               An element to specify that connections should be validated on a background
  478               thread versus being validated prior to use
  479              ]]>
  480           </xs:documentation>
  481         </xs:annotation>
  482       </xs:element>
  483       <xs:element name="background-validation-millis" type="xs:nonNegativeInteger" minOccurs="0">
  484         <xs:annotation>
  485           <xs:documentation>
  486             <![CDATA[[
  487               The background-validation-millis element specifies the amount of
  488               time, in millis, that background validation will run.
  489              ]]>
  490           </xs:documentation>
  491         </xs:annotation>
  492       </xs:element>
  493       <xs:element name="use-fast-fail" type="xs:boolean" minOccurs="0">
  494         <xs:annotation>
  495           <xs:documentation>
  496             <![CDATA[[
  497               Whether fail a connection allocation on the first connection if it
  498               is invalid (true) or keep trying until the pool is exhausted of all potential
  499               connections (false) default false. e.g. <use-fast-fail>true</use-fast-fail>
  500              ]]>
  501           </xs:documentation>
  502         </xs:annotation>
  503       </xs:element>
  504       <xs:element minOccurs="0" name="stale-connection-checker" type="extensionType">
  505         <xs:annotation>
  506           <xs:documentation>
  507             <![CDATA[[
  508               An org.jboss.jca.adapters.jdbc.StaleConnectionChecker that provides
  509               a boolean isStaleConnection(SQLException e) method which if it it returns
  510               true will wrap the exception in an org.jboss.jca.adapters.jdbc.StaleConnectionException
  511               which is a subclass of SQLException. Ex:
  512               <stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.vendor.OracleStaleConnectionChecker"/>
  513              ]]>
  514           </xs:documentation>
  515         </xs:annotation>
  516       </xs:element>
  517       <xs:element name="exception-sorter" type="extensionType" minOccurs="0">
  518         <xs:annotation>
  519           <xs:documentation>
  520             <![CDATA[[
  521               An org.jboss.jca.adapters.jdbc.ExceptionSorter that provides a
  522               boolean isExceptionFatal(SQLException e) method to validate is an exception
  523               should be broadcast to all javax.resource.spi.ConnectionEventListener as
  524               a connectionErrorOccurred message. Ex:
  525               <exception-sorter class-name="org.jboss.jca.adapters.jdbc.vendor.OracleExceptionSorter"/>
  526              ]]>
  527           </xs:documentation>
  528         </xs:annotation>
  529       </xs:element>
  530     </xs:sequence>
  531   </xs:complexType>
  532   <xs:complexType name="timeoutType">
  533     <xs:sequence>
  534       <xs:element name="blocking-timeout-millis" type="xs:nonNegativeInteger" minOccurs="0">
  535         <xs:annotation>
  536           <xs:documentation>
  537             <![CDATA[[
  538               The blocking-timeout-millis element indicates the maximum time in
  539               milliseconds to block while waiting for a connection before throwing an exception.
  540               Note that this blocks only while waiting for a permit for a connection, and
  541               will never throw an exception if creating a new connection takes an inordinately
  542               long time. The default is 30000 (30 seconds).
  543              ]]>
  544           </xs:documentation>
  545         </xs:annotation>
  546       </xs:element>
  547       <xs:element name="idle-timeout-minutes" type="xs:nonNegativeInteger" minOccurs="0">
  548         <xs:annotation>
  549           <xs:documentation>
  550             <![CDATA[[
  551               The idle-timeout-minutes elements indicates the maximum time in minutes
  552               a connection may be idle before being closed. The actual maximum time depends
  553               also on the IdleRemover scan time, which is 1/2 the smallest idle-timeout-minutes
  554               of any pool.
  555              ]]>
  556           </xs:documentation>
  557         </xs:annotation>
  558       </xs:element>
  559       <xs:element name="set-tx-query-timeout" type="boolean-presenceType" minOccurs="0">
  560         <xs:annotation>
  561           <xs:documentation>
  562             <![CDATA[[
  563               Whether to set the query timeout based on the time remaining until
  564               transaction timeout, any configured query timeout will be used if there is
  565               no transaction. The default is false. e.g. <set-tx-query-timeout/>
  566              ]]>
  567           </xs:documentation>
  568         </xs:annotation>
  569       </xs:element>
  570       <xs:element name="query-timeout" type="xs:nonNegativeInteger" minOccurs="0">
  571         <xs:annotation>
  572           <xs:documentation>
  573             <![CDATA[[
  574               Any configured query timeout in seconds The default is no timeout
  575               e.g. 5 minutes <query-timeout>300</query-timeout>
  576              ]]>
  577           </xs:documentation>
  578         </xs:annotation>
  579       </xs:element>
  580       <xs:element name="use-try-lock" type="xs:nonNegativeInteger" minOccurs="0">
  581         <xs:annotation>
  582           <xs:documentation>
  583             <![CDATA[[
  584               Any configured timeout for internal locks on the resource adapter
  585               objects in seconds The default is a 60 second timeout e.g. 5 minutes <use-try-lock>300</use-try-lock>
  586              ]]>
  587           </xs:documentation>
  588         </xs:annotation>
  589       </xs:element>
  590       <xs:element name="allocation-retry" type="xs:nonNegativeInteger" minOccurs="0">
  591         <xs:annotation>
  592           <xs:documentation>
  593             <![CDATA[[
  594               The allocation retry element indicates the number of times that allocating
  595               a connection should be tried before throwing an exception. The default is 0.
  596              ]]>
  597           </xs:documentation>
  598         </xs:annotation>
  599       </xs:element>
  600       <xs:element name="allocation-retry-wait-millis" type="xs:nonNegativeInteger" minOccurs="0">
  601         <xs:annotation>
  602           <xs:documentation>
  603             <![CDATA[[
  604               The allocation retry wait millis element indicates the time in milliseconds
  605               to wait between retrying to allocate a connection. The default is 5000 (5 seconds).
  606              ]]>
  607           </xs:documentation>
  608         </xs:annotation>
  609       </xs:element>
  610       <xs:element name="xa-resource-timeout" type="xs:token" minOccurs="0">
  611         <xs:annotation>
  612           <xs:documentation>
  613             <![CDATA[[
  614               Passed to XAResource.setTransactionTimeout() Default is zero which
  615               does not invoke the setter. In seconds e.g. 5 minutes <xa-resource-timeout>300</xa-resource-timeout>
  616              ]]>
  617           </xs:documentation>
  618         </xs:annotation>
  619       </xs:element>
  620     </xs:sequence>
  621   </xs:complexType>
  622   <xs:simpleType name="track-statementsType">
  623     <xs:restriction base="xs:token">
  624       <xs:enumeration value="true" />
  625       <xs:enumeration value="false" />
  626       <xs:enumeration value="nowarn" />
  627     </xs:restriction>
  628   </xs:simpleType>
  629   <xs:complexType name="statementType">
  630     <xs:sequence>
  631       <xs:element name="track-statements" type="track-statementsType" minOccurs="0">
  632         <xs:annotation>
  633           <xs:documentation>
  634             <![CDATA[[
  635               Whether to check for unclosed statements when a connection is returned
  636               to the pool and result sets are closed when a statement is closed/return
  637               to the prepared statement cache. valid values are: false - do not track statements
  638               and results true - track statements and result sets and warn when they are
  639               not closed nowarn - track statements but do no warn about them being unclosed
  640               (the default) e.g. <track-statements>nowarn</track-statements>
  641             ]]>
  642           </xs:documentation>
  643         </xs:annotation>
  644       </xs:element>
  645       <xs:element name="prepared-statement-cache-size" type="xs:nonNegativeInteger" minOccurs="0">
  646         <xs:annotation>
  647           <xs:documentation>
  648             <![CDATA[[
  649               The number of prepared statements per connection in an LRU cache
  650             ]]>
  651           </xs:documentation>
  652         </xs:annotation>
  653       </xs:element>
  654       <xs:element name="share-prepared-statements" type="boolean-presenceType" minOccurs="0">
  655         <xs:annotation>
  656           <xs:documentation>
  657             <![CDATA[[
  658               Whether to share prepare statements, i.e. whether asking for same
  659               statement twice without closing uses the same underlying prepared statement.
  660               The default is false. e.g. <share-prepared-statements/>
  661             ]]>
  662           </xs:documentation>
  663         </xs:annotation>
  664       </xs:element>
  665     </xs:sequence>
  666   </xs:complexType>
  667   <xs:complexType name="poolType">
  668     <xs:sequence>
  669       <xs:element name="min-pool-size" type="xs:nonNegativeInteger" minOccurs="0">
  670         <xs:annotation>
  671           <xs:documentation>
  672             <![CDATA[[
  673               The min-pool-size element indicates the minimum number of connections
  674               a pool should hold. These are not created until a Subject is known from a
  675               request for a connection. This default to 0. Ex: <min-pool-size>1</min-pool-size>
  676              ]]>
  677           </xs:documentation>
  678         </xs:annotation>
  679       </xs:element>
  680       <xs:element name="max-pool-size" type="xs:nonNegativeInteger" minOccurs="0">
  681         <xs:annotation>
  682           <xs:documentation>
  683             <![CDATA[[
  684               The max-pool-size element indicates the maximum number of connections
  685               for a pool. No more connections will be created in each sub-pool.
  686               This defaults to 20.
  687              ]]>
  688           </xs:documentation>
  689         </xs:annotation>
  690       </xs:element>
  691       <xs:element name="prefill" type="xs:boolean" minOccurs="0">
  692         <xs:annotation>
  693           <xs:documentation>
  694             <![CDATA[[
  695               Whether to attempt to prefill the connection pool. Empty element denotes
  696               a true value. e.g. <prefill>true</prefill>.
  697               Default is false
  698              ]]>
  699           </xs:documentation>
  700         </xs:annotation>
  701       </xs:element>
  702       <xs:element name="use-strict-min" type="xs:boolean" minOccurs="0" maxOccurs="1">
  703         <xs:annotation>
  704           <xs:documentation>
  705             <![CDATA[[
  706               Define if the min-pool-size should be considered a strictly.
  707               Default false
  708              ]]>
  709           </xs:documentation>
  710         </xs:annotation>
  711       </xs:element>
  712       <xs:element name="flush-strategy" type="xs:token" minOccurs="0" maxOccurs="1">
  713         <xs:annotation>
  714           <xs:documentation>
  715             <![CDATA[[
  716               Specifies how the pool should be flush in case of an error.
  717               Valid values are: FailingConnectionOnly (default), IdleConnections, EntirePool
  718              ]]>
  719           </xs:documentation>
  720         </xs:annotation>
  721       </xs:element>
  722       <xs:element name="allow-multiple-users" type="boolean-presenceType" minOccurs="0" maxOccurs="1">
  723         <xs:annotation>
  724           <xs:documentation>
  725             <![CDATA[[
  726               Specifies if multiple users will access the datasource through the getConnection(user, password)
  727               method and hence if the internal pool type should account for that
  728              ]]>
  729           </xs:documentation>
  730         </xs:annotation>
  731       </xs:element>
  732     </xs:sequence>
  733   </xs:complexType>
  734   <xs:complexType name="xa-poolType">
  735     <xs:complexContent>
  736       <xs:extension base="poolType">
  737         <xs:sequence>
  738           <xs:element name="is-same-rm-override" type="xs:boolean" minOccurs="0">
  739             <xs:annotation>
  740               <xs:documentation>
  741                 <![CDATA[[
  742                   The is-same-rm-override element allows one to unconditionally
  743                   set whether the javax.transaction.xa.XAResource.isSameRM(XAResource) returns
  744                   true or false. Ex: <is-same-rm-override>true</is-same-rm-override>
  745                  ]]>
  746               </xs:documentation>
  747             </xs:annotation>
  748           </xs:element>
  749           <xs:element name="interleaving" type="boolean-presenceType" minOccurs="0">
  750             <xs:annotation>
  751               <xs:documentation>
  752                 <![CDATA[[
  753                   An element to enable interleaving for XA connection factories
  754                   Ex: <interleaving/>
  755                  ]]>
  756               </xs:documentation>
  757             </xs:annotation>
  758           </xs:element>
  759           <xs:element name="no-tx-separate-pools" type="boolean-presenceType" minOccurs="0">
  760             <xs:annotation>
  761               <xs:documentation>
  762                 <![CDATA[[
  763                   Oracle does not like XA connections getting used both inside and outside a JTA transaction.
  764                   To workaround the problem you can create separate sub-pools for the different contexts
  765                   using <no-tx-separate-pools/>
  766                   Ex: <no-tx-separate-pools/>
  767                  ]]>
  768               </xs:documentation>
  769             </xs:annotation>
  770           </xs:element>
  771           <xs:element name="pad-xid" type="xs:boolean" default="false" minOccurs="0">
  772             <xs:annotation>
  773               <xs:documentation>
  774                 <![CDATA[[
  775                    Should the Xid be padded
  776                    Ex: <pad-xid>true</pad-xid>
  777                  ]]>
  778               </xs:documentation>
  779             </xs:annotation>
  780           </xs:element>
  781           <xs:element name="wrap-xa-resource" type="xs:boolean" default="false" minOccurs="0">
  782             <xs:annotation>
  783               <xs:documentation>
  784                 <![CDATA[[
  785                    Should the XAResource instances be wrapped in a org.jboss.tm.XAResourceWrapper
  786                    instance
  787                    Ex: <wrap-xa-resource>true</wrap-xa-resource>
  788                  ]]>
  789               </xs:documentation>
  790             </xs:annotation>
  791           </xs:element>
  792         </xs:sequence>
  793       </xs:extension>
  794     </xs:complexContent>
  795   </xs:complexType>
  796   <xs:complexType name="dsSecurityType">
  797     <xs:sequence>
  798       <xs:element name="user-name" type="xs:token" minOccurs="0">
  799         <xs:annotation>
  800           <xs:documentation>
  801             <![CDATA[[
  802                 Specify the username used when creating a new connection.
  803                 Ex: <user-name>sa</user-name>
  804                ]]>
  805           </xs:documentation>
  806         </xs:annotation>
  807       </xs:element>
  808       <xs:element name="password" type="xs:token" minOccurs="0">
  809         <xs:annotation>
  810           <xs:documentation>
  811             <![CDATA[[
  812                 Specify the password used when creating a new connection.
  813                 Ex: <password>sa-pass</password>
  814                ]]>
  815           </xs:documentation>
  816         </xs:annotation>
  817       </xs:element>
  818       <xs:element name="security-domain" type="xs:token" minOccurs="0" maxOccurs="1">
  819         <xs:annotation>
  820           <xs:documentation>
  821             <![CDATA[[
  822               Indicates Subject (from security domain) are used to distinguish connections in the pool.
  823               The content of the security-domain is the name of the JAAS security manager that will handle
  824               authentication. This name correlates to the JAAS login-config.xml descriptor
  825               application-policy/name attribute.
  826               Ex:
  827               <security-domain>HsqlDbRealm</security-domain>
  828             ]]>
  829           </xs:documentation>
  830         </xs:annotation>
  831       </xs:element>
  832       <xs:element name="reauth-plugin" type="extensionType" minOccurs="0" maxOccurs="1"></xs:element>
  833     </xs:sequence>
  834   </xs:complexType>
  835 
  836   <xs:complexType name="extensionType">
  837     <xs:sequence>
  838       <xs:element name="config-property" type="config-propertyType" minOccurs="0" maxOccurs="unbounded"></xs:element>
  839     </xs:sequence>
  840     <xs:attribute name="class-name" type="xs:token" use="required"></xs:attribute>
  841   </xs:complexType>
  842 
  843   <xs:complexType name="config-propertyType" mixed="true">
  844     <xs:annotation>
  845       <xs:documentation>
  846         <![CDATA[[
  847           Specifies a Java bean property value
  848          ]]>
  849       </xs:documentation>
  850     </xs:annotation>
  851     <xs:simpleContent>
  852       <xs:extension base="xs:token">
  853         <xs:attribute use="required" name="name" type="xs:token">
  854           <xs:annotation>
  855             <xs:documentation>
  856               <![CDATA[[
  857                 Specifies the name of the config-property
  858                ]]>
  859             </xs:documentation>
  860           </xs:annotation>
  861         </xs:attribute>
  862       </xs:extension>
  863     </xs:simpleContent>
  864   </xs:complexType>
  865   <xs:complexType name="recoverType">
  866     <xs:sequence>
  867       <xs:element name="recover-credential" type="dsSecurityType" minOccurs="0" maxOccurs="1">
  868         <xs:annotation>
  869           <xs:documentation>
  870             <![CDATA[[
  871               Specifies the security options used when creating a connection during recovery.
  872               Note: if this credential are not specified the security credential are used for recover too
  873              ]]>
  874           </xs:documentation>
  875         </xs:annotation>
  876       </xs:element>
  877       <xs:element name="recover-plugin" type="extensionType" minOccurs="0" maxOccurs="1">
  878         <xs:annotation>
  879           <xs:documentation>
  880             <![CDATA[[
  881               Specifies the extension plugin used in spi (core.spi.xa)
  882               which can be implemented by various plugins to provide better feedback to the XA recovery system.
  883              ]]>
  884           </xs:documentation>
  885         </xs:annotation>
  886       </xs:element>
  887     </xs:sequence>
  888     <xs:attribute name="no-recovery" type="xs:boolean" default="false" use="optional">
  889       <xs:annotation>
  890         <xs:documentation>
  891           <![CDATA[[
  892             Specify if the xa-datasource should be excluded from recovery.
  893             Default false.
  894            ]]>
  895         </xs:documentation>
  896       </xs:annotation>
  897     </xs:attribute>
  898   </xs:complexType>
  899 
  900   <xs:complexType name="driverType">
  901     <xs:sequence>
  902       <xs:element name="driver-class" type="xs:token" maxOccurs="1" minOccurs="0">
  903       <xs:annotation>
  904           <xs:documentation>
  905             <![CDATA[[
  906               The fully qualifed name of the JDBC driver class Ex: <driver-class>org.hsqldb.jdbcDriver</driver-class>
  907              ]]>
  908           </xs:documentation>
  909         </xs:annotation>
  910       </xs:element>
  911       <xs:element name="datasource-class" type="xs:token" maxOccurs="1" minOccurs="0">
  912       <xs:annotation>
  913           <xs:documentation>
  914            <![CDATA[[
  915               The fully qualifed name of the javax.sql.DataSource implementation
  916               class.
  917              ]]>
  918           </xs:documentation>
  919         </xs:annotation></xs:element>
  920       <xs:element name="xa-datasource-class" type="xs:token" maxOccurs="1" minOccurs="0">
  921       <xs:annotation>
  922           <xs:documentation>
  923            <![CDATA[[
  924               The fully qualifed name of the javax.sql.XADataSource implementation
  925               class. Ex: <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
  926              ]]>
  927           </xs:documentation>
  928         </xs:annotation></xs:element>
  929     </xs:sequence>
  930     <xs:attribute name="name" type="xs:token" use="required">
  931       <xs:annotation>
  932         <xs:documentation>
  933           <![CDATA[[
  934             Specifies the symbolic name of this driver used to reference this driver
  935            ]]>
  936         </xs:documentation>
  937       </xs:annotation>
  938     </xs:attribute>
  939     <xs:attribute name="module" type="xs:token" use="optional">
  940       <xs:annotation>
  941         <xs:documentation>
  942           <![CDATA[[
  943             Specifies the name of AS7 module providing this driver.
  944             Thios tag is not used in IronJacamar standalone container.
  945            ]]>
  946         </xs:documentation>
  947       </xs:annotation>
  948     </xs:attribute>
  949     <xs:attribute name="major-version" type="xs:int" use="optional">
  950       <xs:annotation>
  951         <xs:documentation>
  952           <![CDATA[[
  953             Specifies the major version of this driver. If the major and minor version is obmitted the fist availabe
  954             Driver in module will be used.
  955            ]]>
  956         </xs:documentation>
  957       </xs:annotation>
  958     </xs:attribute>
  959     <xs:attribute name="minor-verion" type="xs:int" use="optional">
  960     <xs:annotation>
  961         <xs:documentation>
  962           <![CDATA[[
  963             Specifies the minor version of this driver. If the major and minor version is obmitted the fist availabe
  964             Driver in module will be used.
  965            ]]>
  966         </xs:documentation>
  967       </xs:annotation>
  968     </xs:attribute>
  969   </xs:complexType>
  970 
  971   <xs:complexType name="driversType">
  972     <xs:sequence>
  973       <xs:element name="driver" type="driverType" maxOccurs="unbounded" minOccurs="1"></xs:element>
  974     </xs:sequence>
  975   </xs:complexType>
  976 </xs:schema>



Sunday, May 21, 2017

Springframework Async annotation and ThreadExcutor's AbortPolicy

The Springframework has @Async annotation.

it simplifies the asynchronous method execution and hides the implementation details. In order to have a dependable asynchronous execution mechanism, few more factors need our attention.

First, the sample of the usage of the Async annotation:

@Async
void doSomething() {
    // activities will be executed asynchronously
}

@Async("anExecutor")
Future<String> doThenReturnSomething(String id) {
    // will be executed asynchronously
}

Other possible return types:

JDK 8’s java.util.concurrent.CompletableFuture

boolean cancel(boolean mayInterruptIfRunning)
boolean complete(T value)

Spring’s org.springframework.util.concurrent.ListenableFuture 

void      addCallback(ListenableFutureCallback<? super T> callback)
void      addCallback(SuccessCallback<? super T> successCallback, FailureCallback failureCallback)

JBoss’s org.jboss.threads.AsyncFuture

Void asyncCancel(boolean interruptionDesired)
AsyncFuture.Status getStatus()

ThreadPoolTaskExecutor This implementation is the most commonly used one.

<task:executor
        id="executorWithCallerRunsPolicy"
        pool-size="5-25"
        queue-capacity="100"
        keep-alive="120"
        rejection-policy="CALLER_RUNS"/>
From Springframework document:
By default, the queue is unbounded, but this is rarely the desired configuration, because it can lead to OutOfMemoryErrors if enough tasks are added to that queue while all pool threads are busy.

TaskRejectedExceptionAbortPolicyDiscardPolicy or DiscardOldestPolicyCallerRunsPolicy

First, let’s consider the case, as mentioned above, when a task is rejected. By default, when a task is rejected, a thread pool executor will throw a TaskRejectedException. However, the rejection policy is actually configurable. The exception is thrown when using the default rejection policy which is the AbortPolicy implementation. For applications where some tasks can be skipped under heavy load, either the DiscardPolicy or DiscardOldestPolicy may be configured instead. Another option that works well for applications that need to throttle the submitted tasks under heavy load is the CallerRunsPolicy. Instead of throwing an exception or discarding tasks, that policy will simply force the thread that is calling the submit method to run the task itself. The idea is that such a caller will be busy while running that task and not able to submit other tasks immediately. Therefore it provides a simple way to throttle the incoming load while maintaining the limits of the thread pool and queue. Typically this allows the executor to "catch up" on the tasks it is handling and thereby frees up some capacity on the queue, in the pool, or both. Any of these options can be chosen from an enumeration of values available for the 'rejection-policy' attribute on the 'executor' element.
The keep-alive setting determines the time limit (in seconds) for which threads may remain idle before being terminated. If there are more than the core number of threads currently in the pool, after waiting this amount of time without processing a task, excess threads will get terminated.
Finally,
When actions are enclosed in tasks (such as FutureTask) either explicitly or via methods such as submit, these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method. Please make sure that the calling method handles the exception properly.
Inside the asynchronous task, most likely, a remote service call or database access will be invoked. Please configure proper timeout so that thread will not be blocked or thread will not hang.

Saturday, May 20, 2017

HttpRoutePlanner Usage Sample

HttpRoutePlanner:

From its Java doc:
Encapsulates logic to compute a HttpRoute to a target host. Implementations may for example be based on parameters, or on the standard Java system properties.
Implementations of this interface must be thread-safe. Access to shared data must be synchronized as methods of this interface may be executed from multiple threads.

Not tested yet.


import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.conn.routing.RouteInfo.LayerType;
import org.apache.http.conn.routing.RouteInfo.TunnelType;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;

public class CustomHttpRoutePlanner implements HttpRoutePlanner {

       @Override
       public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {
             final String hostname = target.getHostName();
             final HttpRoute httpRoute;
             if (this.isMovedAddress(hostname)) {
                    httpRoute = new HttpRoute(target, null, new HttpHost("x.x.x.x", 9191, "https"), true, TunnelType.PLAIN,
                                 LayerType.PLAIN);
             } else {
                    httpRoute = new HttpRoute(target, null, target, true, TunnelType.PLAIN, LayerType.PLAIN);
             }
             return httpRoute;
       }

       private boolean isMovedAddress(String hostname) {
             Pattern pattern = Pattern.compile(".+odd.addr$");
             Matcher matcher = pattern.matcher(hostname);
             boolean result = matcher.matches();
             return result;
       }


       public static void main(String[] args) {
             final DefaultHttpClient defaultHttpClient = new DefaultHttpClient();

             final HttpHost proxy = new HttpHost("x.x.x.x", 9090, "https");
              defaultHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

             SchemeSocketFactory factory = null;
              try {
                     factory = new SSLSocketFactory(new SimpleTrustStrategy()); //Trus All
              } catch (GeneralSecurityException ex) {
                     Logger.error("failed to create SSL Socket Factory.", ex);
              }

             final Scheme https = new Scheme("https", 443, factory);
              defaultHttpClient.getConnectionManager().getSchemeRegistry().register(https);
             defaultHttpClient.setRoutePlanner(new CustomHttpRoutePlanner());

             final HttpGet request = new HttpGet("http://www.google.com");

             try {
                    defaultHttpClient.execute(request);
             } catch (ClientProtocolException e) {
                    logger.error("protocol exception.", e);
             } catch (IOException e) {
                    logger.error("io exception.", e);
             }

       }

}

Jackson PropertyNamingStrategy

If a special JSON property mapping is required for a Jackson Mapper, a PropertyNamingStrategy class sample is here, the class should be used like the following:

new ObjectMapper().setPropertyNamingStrategy(new CstyleStrategy());



import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;

public class CstyleStrategy extends PropertyNamingStrategy {
       private static final long serialVersionUID = 1L;

       @Override
       public String nameForField(final MapperConfig<?> config, final AnnotatedField field, final String defaultName) {
             return field.getName();
       }

       @Override
       public String nameForGetterMethod(final MapperConfig<?> config, final AnnotatedMethod method, final String defaultName) {
             return convert(method, defaultName);
       }

       @Override
       public String nameForSetterMethod(final MapperConfig<?> config, final AnnotatedMethod method, final String defaultName) {
             return convert(method, defaultName);
       }

       private String convert(final AnnotatedMethod method, final String input) {
             final Class<?> clazz = method.getDeclaringClass();
             final String className = clazz.getCanonicalName();
             String result = null;
             if (className.contains("mySpecialType")) {
                    StringBuilder resultBuffer = new StringBuilder();
                    for (int i = 0, len = input.length(); i < len; ++i) {
                           char c = input.charAt(i);
                           if (Character.isUpperCase(c)) {
                                 resultBuffer.append('_');
                                 c = Character.toLowerCase(c);
                           }
                           resultBuffer.append(c);
                    }
                    result = resultBuffer.toString();
             } else {
                    result = input;
             }
             return result.toString();
       }
}