Class DataSourceResourceLoader
java.lang.Object
org.apache.velocity.runtime.resource.loader.ResourceLoader
org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader
This is a simple template file loader that loads templates from a DataSource instead of plain files.
It can be configured with a datasource name, a table name, id column (name), content column (the template body) and a datetime column (for last modification info).
Example configuration snippet for velocity.properties:
resource.loaders = file, ds
resource.loader.ds.description = Velocity DataSource Resource Loader
resource.loader.ds.class = org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader
resource.loader.ds.resource.datasource_url = java:comp/env/jdbc/Velocity
resource.loader.ds.resource.table = tb_velocity_template
resource.loader.ds.resource.key_column = id_template
resource.loader.ds.resource.template_column = template_definition
resource.loader.ds.resource.timestamp_column = template_timestamp
resource.loader.ds.cache = false
resource.loader.ds.modification_check_interval = 60
Optionally, the developer can instantiate the DataSourceResourceLoader and set the DataSource via code in a manner similar to the following:
DataSourceResourceLoader ds = new DataSourceResourceLoader();
ds.setDataSource(DATASOURCE);
Velocity.setProperty("resource.loader.ds.instance",ds);
The property resource.loader.ds.class should be left out, otherwise all the other
properties in velocity.properties would remain the same.
Example WEB-INF/web.xml:
<resource-ref>
<description>Velocity template DataSource</description>
<res-ref-name>jdbc/Velocity</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
and Tomcat 4 server.xml file:
[...]
<Context path="/exampleVelocity" docBase="exampleVelocity" debug="0">
[...]
<ResourceParams name="jdbc/Velocity">
<parameter>
<name>driverClassName</name>
<value>org.hsql.jdbcDriver</value>
</parameter>
<parameter>
<name>driverName</name>
<value>jdbc:HypersonicSQL:database</value>
</parameter>
<parameter>
<name>user</name>
<value>database_username</value>
</parameter>
<parameter>
<name>password</name>
<value>database_password</value>
</parameter>
</ResourceParams>
[...]
</Context>
[...]
Example sql script:
CREATE TABLE tb_velocity_template (
id_template varchar (40) NOT NULL ,
template_definition text (16) NOT NULL ,
template_timestamp datetime NOT NULL
);
- Since:
- 1.5
- Version:
- $Id$
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static class -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate Connectionprivate InitialContextprivate DataSourceprivate Stringprivate Stringprivate Stringprivate Stringprivate PreparedStatementprivate Stringprivate PreparedStatementFields inherited from class org.apache.velocity.runtime.resource.loader.ResourceLoader
className, isCachingOn, log, modificationCheckInterval, rsvc -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate voidChecks the connection is validprivate voidCloses the prepared statements and the connection to the datasourceprivate voidCloses the result set.protected ResultSetfetchResult(PreparedStatement ps, String templateName) Fetches the result for a given template name.protected voidfinalize()Close DB connection on finalizationlonggetLastModified(Resource resource) Get the last modified time of the InputStream source that was used to create the template.protected ReaderGets a reader from a result set's columngetResourceReader(String name, String encoding) Get an InputStream so that the Runtime can build a template with it.voidinit(ExtProperties configuration) Initialize the template loader with a a resources class.booleanisSourceModified(Resource resource) Given a template, check to see if the source of InputStream has been modified.private voidGets connection to the datasource specified through the configuration parameters.protected PreparedStatementprepareStatement(Connection conn, String columnNames, String tableName, String keyColumn) Creates the following PreparedStatement query :
SELECT columnNames FROM tableName WHERE keyColumn = 'templateName'
where keyColumn is a class member set in init()private longreadLastModified(Resource resource, String operation) Fetches the last modification time of the resourcevoidsetDataSource(DataSource dataSource) Set the DataSource used by this resource loader.Methods inherited from class org.apache.velocity.runtime.resource.loader.ResourceLoader
buildReader, commonInit, getClassName, getModificationCheckInterval, isCachingOn, resourceExists, setCachingOn, setModificationCheckInterval
-
Field Details
-
dataSourceName
-
tableName
-
keyColumn
-
templateColumn
-
timestampColumn
-
ctx
-
dataSource
-
connection
-
templatePrepStatement
-
timestampPrepStatement
-
-
Constructor Details
-
DataSourceResourceLoader
public DataSourceResourceLoader()
-
-
Method Details
-
init
Description copied from class:ResourceLoaderInitialize the template loader with a a resources class.- Specified by:
initin classResourceLoader- Parameters:
configuration-- See Also:
-
setDataSource
Set the DataSource used by this resource loader. Call this as an alternative to specifying the data source name via properties.- Parameters:
dataSource- The data source for this ResourceLoader.
-
isSourceModified
Description copied from class:ResourceLoaderGiven a template, check to see if the source of InputStream has been modified.- Specified by:
isSourceModifiedin classResourceLoader- Parameters:
resource-- Returns:
- True if the resource has been modified.
- See Also:
-
getLastModified
Description copied from class:ResourceLoaderGet the last modified time of the InputStream source that was used to create the template. We need the template here because we have to extract the name of the template in order to locate the InputStream source.- Specified by:
getLastModifiedin classResourceLoader- Parameters:
resource-- Returns:
- Time in millis when the resource has been modified.
- See Also:
-
getResourceReader
Get an InputStream so that the Runtime can build a template with it.- Specified by:
getResourceReaderin classResourceLoader- Parameters:
name- name of templateencoding- asked encoding- Returns:
- InputStream containing template
- Throws:
ResourceNotFoundException- Since:
- 2.0
-
readLastModified
Fetches the last modification time of the resource- Parameters:
resource- Resource object we are finding timestamp ofoperation- string for logging, indicating caller's intention- Returns:
- timestamp as long
-
openDBConnection
Gets connection to the datasource specified through the configuration parameters.- Throws:
NamingExceptionSQLException
-
checkDBConnection
Checks the connection is valid- Throws:
NamingExceptionSQLException
-
finalize
Close DB connection on finalization -
closeDBConnection
private void closeDBConnection()Closes the prepared statements and the connection to the datasource -
closeResultSet
Closes the result set. -
prepareStatement
protected PreparedStatement prepareStatement(Connection conn, String columnNames, String tableName, String keyColumn) throws SQLException Creates the following PreparedStatement query :
SELECT columnNames FROM tableName WHERE keyColumn = 'templateName'
where keyColumn is a class member set in init()- Parameters:
conn- connection to datasourcecolumnNames- columns to fetch from datasourcetableName- table to fetch fromkeyColumn- column whose value should match templateName- Returns:
- PreparedStatement
- Throws:
SQLException
-
fetchResult
Fetches the result for a given template name. Inherit this method if there is any calculation to perform on the template name.- Parameters:
ps- target prepared statementtemplateName- input template name- Returns:
- result set
- Throws:
SQLException
-
getReader
Gets a reader from a result set's column- Parameters:
resultSet-column-encoding-- Returns:
- reader
- Throws:
SQLException
-