You are viewing a plain text version of this content. The canonical link for it is here.
Posted to cvs@avalon.apache.org by le...@apache.org on 2002/02/07 08:15:42 UTC
cvs commit: jakarta-avalon-excalibur/examples/jdbcdatasource/src/java/org/apache/avalon/examples/jdbcdatasource DefaultHelloDBService.java HelloDBService.java Main.java
leif 02/02/06 23:15:42
Added: examples build.bat build.sh build.xml
examples/commonlib .cvsignore hsqldb.jar
examples/jdbcdatasource .cvsignore build.bat build.sh
build.xml
examples/jdbcdatasource/bin cpappend.bat hsqldbmgr.bat
run.bat
examples/jdbcdatasource/conf components.xml logkit.xml
roles.xml
examples/jdbcdatasource/src/java/org/apache/avalon/examples/jdbcdatasource
DefaultHelloDBService.java HelloDBService.java
Main.java
Log:
Add new jdbcdatasource example.
Revision Changes Path
1.1 jakarta-avalon-excalibur/examples/build.bat
Index: build.bat
===================================================================
@echo off
if exist "..\..\jakarta-avalon\tools\bin\ant.bat" set LOCAL_AVALON_TOOLS=..\..\jakarta-avalon\tools
if not "%AVALON_TOOLS%"=="" set LOCAL_AVALON_TOOLS=%AVALON_TOOLS%
if not "%LOCAL_AVALON_TOOLS%"=="" goto runAnt
echo "Unable to locate tools directory at "
echo "../../jakarta-avalon/tools/ "
echo "Aborting."
goto end
:runAnt
set OLD_ANT_HOME=%ANT_HOME%
set ANT_HOME=%LOCAL_AVALON_TOOLS%
%LOCAL_AVALON_TOOLS%\bin\ant.bat -logger org.apache.tools.ant.NoBannerLogger -emacs -Dtools.dir=%LOCAL_AVALON_TOOLS% %1 %2 %3 %4 %5 %6 %7 %8
set ANT_HOME=%OLD_ANT_HOME%
set OLD_ANT_HOME=
:end
set LOCAL_AVALON_TOOLS=
1.1 jakarta-avalon-excalibur/examples/build.sh
Index: build.sh
===================================================================
#!/bin/sh
LOCAL_AVALON_TOOLS=$AVALON_TOOLS
if [ "$AVALON_TOOLS" = "" ] ; then
if [ -d ../../jakarta-avalon/tools ] ; then
LOCAL_AVALON_TOOLS=../../jakarta-avalon/tools
else
echo "Unable to locate tools directory at "
echo "../../jakarta-avalon/tools/ "
echo "Aborting."
exit 1
fi
fi
chmod u+x $LOCAL_AVALON_TOOLS/bin/antRun
chmod u+x $LOCAL_AVALON_TOOLS/bin/ant
$LOCAL_AVALON_TOOLS/bin/ant -logger org.apache.tools.ant.NoBannerLogger -emacs -Dtools.dir=$LOCAL_AVALON_TOOLS $@
1.1 jakarta-avalon-excalibur/examples/build.xml
Index: build.xml
===================================================================
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- ======================================================================= -->
<!-- Jakarta-Avalon-Examples build file! -->
<!-- ======================================================================= -->
<project name="jdbcdatasource" default="main" basedir=".">
<!-- external projects -->
<property name="avalon.proj"
value="${basedir}/../../jakarta-avalon"/>
<property name="avalon-excalibur.proj"
value="${basedir}/../../jakarta-avalon-excalibur"/>
<property name="avalon-logkit.proj"
value="${basedir}/../../jakarta-avalon-logkit"/>
<!-- Existing Directories -->
<property name="commonlib.dir" value="${basedir}/commonlib"/>
<!-- =================================================================== -->
<!-- Help on usage -->
<!-- =================================================================== -->
<target name="usage">
<echo message="Use the -projecthelp option instead"/>
</target>
<target name="help" depends="usage"/>
<!-- =================================================================== -->
<!-- Find Avalon Projects -->
<!-- =================================================================== -->
<target name="find-projects">
<!-- Avalon Framework jars -->
<condition property="avalon-framework.jar.present">
<available file="${avalon.proj}/build/lib/avalon-framework.jar"/>
</condition>
<condition property="avalon-framework.jar.needbuild">
<and>
<available file="${avalon.proj}"/>
<not>
<available file="${avalon.proj}/build/lib/avalon-framework.jar"/>
</not>
</and>
</condition>
<!-- Avalon Excalibur jars -->
<condition property="avalon-excalibur.jar.present">
<and>
<available file="${avalon-excalibur.proj}/build/lib/avalon-excalibur.jar"/>
<available file="${avalon-excalibur.proj}/build/lib/avalon-scratchpad.jar"/>
</and>
</condition>
<condition property="avalon-excalibur.jar.needbuild">
<and>
<available file="${avalon-excalibur.proj}"/>
<not>
<and>
<available file="${avalon-excalibur.proj}/build/lib/avalon-excalibur.jar"/>
<available file="${avalon-excalibur.proj}/build/lib/avalon-scratchpad.jar"/>
</and>
</not>
</and>
</condition>
<!-- Avalon LogKit jars -->
<condition property="logkit.jar.present">
<available file="${avalon-logkit.proj}/build/lib/logkit.jar"/>
</condition>
<condition property="logkit.jar.needbuild">
<and>
<available file="${avalon-logkit.proj}"/>
<not>
<available file="${avalon-logkit.proj}/build/lib/logkit.jar"/>
</not>
</and>
</condition>
</target>
<!-- =================================================================== -->
<!-- Collect Avalon tools/ext Jars -->
<!-- =================================================================== -->
<target name="collect-tools-jars">
<!-- Try getting the jars from the tools/ext directory -->
<copy file="${avalon.proj}/tools/ext/avalon-framework.jar"
todir="${commonlib.dir}" preservelastmodified="yes"/>
<copy file="${avalon.proj}/tools/ext/avalon-excalibur.jar"
todir="${commonlib.dir}" preservelastmodified="yes"/>
<copy file="${avalon.proj}/tools/ext/logkit.jar"
todir="${commonlib.dir}" preservelastmodified="yes"/>
<!-- Try getting the jars from the tools/lib directory -->
<copy file="${avalon.proj}/tools/lib/xml-apis.jar"
todir="${commonlib.dir}" preservelastmodified="yes"/>
<copy file="${avalon.proj}/tools/lib/xerces-1.4.4.jar"
todir="${commonlib.dir}" preservelastmodified="yes"/>
</target>
<!-- =================================================================== -->
<!-- Collect Avalon Framework build/lib Jars -->
<!-- =================================================================== -->
<target name="collect-framework-build-jars-present"
depends="find-projects" if="avalon-framework.jar.present">
<copy file="${avalon.proj}/build/lib/avalon-framework.jar"
todir="${commonlib.dir}" preservelastmodified="yes"/>
</target>
<target name="collect-framework-build-jars-needbuild"
depends="find-projects" if="avalon-framework.jar.needbuild">
<fail message="Please go to ${avalon.proj} and run build first."/>
</target>
<target name="collect-framework-build-jars"
depends="collect-framework-build-jars-present, collect-framework-build-jars-needbuild"/>
<!-- =================================================================== -->
<!-- Collect Avalon Excalibur build/lib Jars -->
<!-- =================================================================== -->
<target name="collect-excalibur-build-jars-present"
depends="find-projects" if="avalon-excalibur.jar.present">
<copy file="${avalon-excalibur.proj}/build/lib/avalon-excalibur.jar"
todir="${commonlib.dir}" preservelastmodified="yes"/>
<copy file="${avalon-excalibur.proj}/build/lib/avalon-scratchpad.jar"
todir="${commonlib.dir}" preservelastmodified="yes"/>
</target>
<target name="collect-excalibur-build-jars-needbuild"
depends="find-projects" if="avalon-excalibur.jar.needbuild">
<fail message="Please go to ${avalon-excalibur.proj} and run build first."/>
</target>
<target name="collect-excalibur-build-jars"
depends="collect-excalibur-build-jars-present, collect-excalibur-build-jars-needbuild"/>
<!-- =================================================================== -->
<!-- Collect Avalon Logkit build/lib Jars -->
<!-- =================================================================== -->
<target name="collect-logkit-build-jars-present"
depends="find-projects" if="logkit.jar.present">
<copy file="${avalon-logkit.proj}/build/lib/logkit.jar"
todir="${commonlib.dir}" preservelastmodified="yes"/>
</target>
<target name="collect-logkit-build-jars-needbuild"
depends="find-projects" if="logkit.jar.needbuild">
<fail message="Please go to ${avalon-logkit.proj} and run build first."/>
</target>
<target name="collect-logkit-build-jars"
depends="collect-logkit-build-jars-present, collect-logkit-build-jars-needbuild"/>
<!-- =================================================================== -->
<!-- Collect Avalon Jars -->
<!-- =================================================================== -->
<target name="collect-jars"
depends="collect-tools-jars, collect-framework-build-jars, collect-excalibur-build-jars, collect-logkit-build-jars"
description="Collects the newest available Avalon Jars for use by Examples Applications"/>
<!-- =================================================================== -->
<!-- Build All Examples -->
<!-- =================================================================== -->
<target name="prep-all-examples">
<property name="examples.target" value="main"/>
</target>
<target name="prep-all-examples-javadocs">
<property name="examples.target" value="all"/>
</target>
<target name="build-examples" depends="collect-jars" if="examples.target">
<!-- All example projects should be listed here -->
<!-- jdbcdatasource example -->
<ant antfile="build.xml" dir="${basedir}/jdbcdatasource"
target="${examples.target}" inheritall="false"/>
<!-- Add new tests here -->
</target>
<target name="all-examples" depends="prep-all-examples, build-examples"
description="Builds all of the examples."/>
<target name="all-examples-javadocs" depends="prep-all-examples-javadocs, build-examples"
description="Builds all of the examples with javadocs."/>
<!-- =================================================================== -->
<!-- Main -->
<!-- =================================================================== -->
<target name="main" depends="all-examples"/>
</project>
1.1 jakarta-avalon-excalibur/examples/commonlib/.cvsignore
Index: .cvsignore
===================================================================
avalon-excalibur.jar
avalon-framework.jar
avalon-scratchpad.jar
logkit.jar
xerces-1.4.4.jar
xml-apis.jar
1.1 jakarta-avalon-excalibur/examples/commonlib/hsqldb.jar
<<Binary file>>
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/.cvsignore
Index: .cvsignore
===================================================================
build
lib
sqldata
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/build.bat
Index: build.bat
===================================================================
@echo off
if exist "..\..\..\jakarta-avalon\tools\bin\ant.bat" set LOCAL_AVALON_TOOLS=..\..\..\jakarta-avalon\tools
if not "%AVALON_TOOLS%"=="" set LOCAL_AVALON_TOOLS=%AVALON_TOOLS%
if not "%LOCAL_AVALON_TOOLS%"=="" goto runAnt
echo "Unable to locate tools directory at "
echo "../../../jakarta-avalon/tools/"
echo "Aborting."
goto end
:runAnt
set OLD_ANT_HOME=%ANT_HOME%
set ANT_HOME=%LOCAL_AVALON_TOOLS%
%LOCAL_AVALON_TOOLS%\bin\ant.bat -logger org.apache.tools.ant.NoBannerLogger -emacs -Dtools.dir=%LOCAL_AVALON_TOOLS% %1 %2 %3 %4 %5 %6 %7 %8
set ANT_HOME=%OLD_ANT_HOME%
set OLD_ANT_HOME=
:end
set LOCAL_AVALON_TOOLS=
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/build.sh
Index: build.sh
===================================================================
#!/bin/sh
LOCAL_AVALON_TOOLS=$AVALON_TOOLS
if [ "$AVALON_TOOLS" = "" ] ; then
if [ -d ../../jakarta-avalon/tools ] ; then
LOCAL_AVALON_TOOLS=../../jakarta-avalon/tools
else
echo "Unable to locate tools directory at "
echo "../../jakarta-avalon/tools/"
echo "Aborting."
exit 1
fi
fi
chmod u+x $LOCAL_AVALON_TOOLS/bin/antRun
chmod u+x $LOCAL_AVALON_TOOLS/bin/ant
$LOCAL_AVALON_TOOLS/bin/ant -logger org.apache.tools.ant.NoBannerLogger -emacs -Dtools.dir=$LOCAL_AVALON_TOOLS $@
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/build.xml
Index: build.xml
===================================================================
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- ======================================================================= -->
<!-- JdbcDataSource Example build file! -->
<!-- ======================================================================= -->
<project name="jdbcdatasource" default="main" basedir=".">
<!-- ================================================================ -->
<!-- Local user-defined build properties. -->
<!-- ================================================================ -->
<!-- The file below should exist on your system. On Windows machines, -->
<!-- user.home is probably the root of the C drive, but you should -->
<!-- verify this. This file should be a normal Java properties file. -->
<property file="${user.home}/.ant.properties" />
<property name="name" value="jdbcdatasource"/>
<property name="Name" value="JdbcDataSource"/>
<!-- Directories build by ant -->
<property name="build.dir" value="${basedir}/build"/>
<property name="build.classes.dir" value="${build.dir}/classes"/>
<property name="build.javadocs.dir" value="${build.dir}/javadocs"/>
<property name="lib.dir" value="${basedir}/lib"/>
<property name="sqldata.dir" value="${basedir}/sqldata"/>
<!-- Existing directories -->
<property name="src.dir" value="${basedir}/src"/>
<property name="src.java.dir" value="${src.dir}/java"/>
<property name="commonlib.dir" value="${basedir}/../commonlib"/>
<!-- Define paths used by this project -->
<path id="project.class.path">
<fileset dir="${commonlib.dir}">
<include name="**/*.jar"/>
</fileset>
<pathelement path="${build.classes.dir}" />
</path>
<!-- =================================================================== -->
<!-- Help on usage -->
<!-- =================================================================== -->
<target name="usage">
<echo message="Use the -projecthelp option instead"/>
</target>
<target name="help" depends="usage"/>
<!-- =================================================================== -->
<!-- Help on usage -->
<!-- =================================================================== -->
<target name="collect-jars">
<ant antfile="build.xml" dir="${basedir}/.." target="collect-jars" inheritall="false"/>
</target>
<!-- =================================================================== -->
<!-- Initialize custom tasks -->
<!-- =================================================================== -->
<target name="init" depends="collect-jars">
</target>
<!-- =================================================================== -->
<!-- Compiles the source code -->
<!-- =================================================================== -->
<target name="compile" depends="init">
<mkdir dir="${build.dir}"/>
<mkdir dir="${build.classes.dir}"/>
<!-- compile everything under src/java -->
<javac srcdir="${src.java.dir}" destdir="${build.classes.dir}"
deprecation="on"
debug="on"
optimize="off">
<classpath refid="project.class.path" />
</javac>
<!-- copy image files to build directory -->
<copy todir="${build.classes.dir}" >
<fileset dir="${src.java.dir}" >
<include name="**/*.jpg" />
<include name="**/*.gif" />
</fileset>
</copy>
</target>
<!-- =================================================================== -->
<!-- Creates the jar archive -->
<!-- =================================================================== -->
<target name="jar" depends="compile" description="Builds the jar archive.">
<mkdir dir="${lib.dir}"/>
<jar jarfile="${lib.dir}/${name}.jar"
basedir="${build.classes.dir}"
includes="**/*.class,**/*.properties,**/*.xml,**/*.jpg,**/*.gif,**/*.roles"
/>
</target>
<!-- =================================================================== -->
<!-- Main target -->
<!-- =================================================================== -->
<target name="main" depends="jar" description="build the runnable application">
<mkdir dir="${sqldata.dir}"/>
</target>
<!-- =================================================================== -->
<!-- Creates the javadocs archive. -->
<!-- =================================================================== -->
<target name="javadocs" description="Generates javadoc documentation">
<mkdir dir="${build.javadocs.dir}"/>
<javadoc packagenames="org.apache.*"
sourcepath="${src.java.dir}"
destdir="${build.javadocs.dir}">
<classpath refid="project.class.path" />
<doclet name="com.sun.tools.doclets.standard.Standard">
<param name="-author"/>
<param name="-version"/>
<param name="-doctitle" value="${Name}"/>
<param name="-windowtitle" value="${Name} API"/>
<param name="-bottom"
value=""Copyright © 2001 Apache Jakarta Project. All Rights Reserved.""/>
</doclet>
</javadoc>
</target>
<!-- =================================================================== -->
<!-- Builds everything. -->
<!-- =================================================================== -->
<target name="all" depends="main, javadocs" description="Build everything"/>
<!-- =================================================================== -->
<!-- Cleans up compiled classes and generated XMLC source. -->
<!-- =================================================================== -->
<target name="clean" description="cleans up the directory">
<delete dir="${build.dir}"/>
</target>
</project>
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/bin/cpappend.bat
Index: cpappend.bat
===================================================================
set _LIBJARS=%_LIBJARS%;%1
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/bin/hsqldbmgr.bat
Index: hsqldbmgr.bat
===================================================================
@echo off
rem
rem Run HSQLDB Manager
rem
rem Author: Leif Mortenson [leif@silveregg.co.jp]
rem
rem Determine if JAVA_HOME is set and if so then use it
rem
if not "%JAVA_HOME%"=="" goto found_java
set EXAMPLE_JAVACMD=java
goto file_locate
:found_java
set EXAMPLE_JAVACMD=%JAVA_HOME%\bin\java
:file_locate
rem
rem Locate where the example is in filesystem
rem
if not "%OS%"=="Windows_NT" goto start
rem %~dp0 is name of current script under NT
set EXAMPLE_HOME=%~dp0
rem : operator works similar to make : operator
set EXAMPLE_HOME=%EXAMPLE_HOME:\bin\=%
:start
if not "%EXAMPLE_HOME%" == "" goto example_home
echo.
echo Warning: EXAMPLE_HOME environment variable is not set.
echo This needs to be set for Win9x as it's command prompt
echo scripting bites
echo.
goto end
:example_home
rem
rem build the runtime classpath
rem
set CP=%EXAMPLE_HOME%\lib\jdbcdatasource.jar
set _LIBJARS=;%EXAMPLE_HOME%\..\commonlib\hsqldb.jar
if not "%_LIBJARS%" == "" goto run
echo Unable to set CLASSPATH.
goto end
:run
set CP=%CP%%_LIBJARS%
rem Run the example application
%EXAMPLE_JAVACMD% -classpath "%CP%" org.hsqldb.util.DatabaseManager
:end
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/bin/run.bat
Index: run.bat
===================================================================
@echo off
rem
rem Example start script.
rem
rem Author: Leif Mortenson [leif@silveregg.co.jp]
rem
rem Determine if JAVA_HOME is set and if so then use it
rem
if not "%JAVA_HOME%"=="" goto found_java
set EXAMPLE_JAVACMD=java
goto file_locate
:found_java
set EXAMPLE_JAVACMD=%JAVA_HOME%\bin\java
:file_locate
rem
rem Locate where the example is in filesystem
rem
if not "%OS%"=="Windows_NT" goto start
rem %~dp0 is name of current script under NT
set EXAMPLE_HOME=%~dp0
rem : operator works similar to make : operator
set EXAMPLE_HOME=%EXAMPLE_HOME:\bin\=%
:start
if not "%EXAMPLE_HOME%" == "" goto example_home
echo.
echo Warning: EXAMPLE_HOME environment variable is not set.
echo This needs to be set for Win9x as it's command prompt
echo scripting bites
echo.
goto end
:example_home
rem
rem build the runtime classpath
rem
set CP=%EXAMPLE_HOME%\lib\jdbcdatasource.jar
set _LIBJARS=
for %%i in (%EXAMPLE_HOME%\..\commonlib\*.jar) do call %EXAMPLE_HOME%\bin\cpappend.bat %%i
if not "%_LIBJARS%" == "" goto run
echo Unable to set CLASSPATH dynamically.
goto end
:run
set CP=%CP%%_LIBJARS%
rem Run the example application
%EXAMPLE_JAVACMD% -classpath "%CP%" org.apache.avalon.examples.jdbcdatasource.Main %1 %2 %3 %4 %5 %6 %7 %8 %9
:end
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/conf/components.xml
Index: components.xml
===================================================================
<event-servlet logger="cm">
<!-- =============================================================== -->
<!-- Data sources. -->
<!-- =============================================================== -->
<datasources>
<jdbc name="test-db" logger="app.jdbc">
<pool-controller min="1" max="1">
<keep-alive disable="true"/>
</pool-controller>
<auto-commit>true</auto-commit>
<driver>org.hsqldb.jdbcDriver</driver>
<dburl>jdbc:hsqldb:..\sqldata\example</dburl>
<user>sa</user>
<password></password>
</jdbc>
</datasources>
<!-- =============================================================== -->
<!-- Application components. -->
<!-- =============================================================== -->
<hello-db logger="app">
<dbpool>test-db</dbpool>
</hello-db>
</event-servlet>
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/conf/logkit.xml
Index: logkit.xml
===================================================================
<logkit logger="lm" log-level="INFO">
<factories>
<factory type="stream"
class="org.apache.avalon.excalibur.logger.factory.StreamTargetFactory"/>
<factory type="file"
class="org.apache.avalon.excalibur.logger.factory.FileTargetFactory"/>
<factory type="priority-filter"
class="org.apache.avalon.excalibur.logger.factory.PriorityFilterTargetFactory"/>
</factories>
<targets>
<stream id="console">
<stream>System.out</stream>
<format type="avalon">
%19.19{time:yyyy-MM-dd'T'HH:mm:ss.SSS} %5.5{priority} [%15.15{category}]: %{message}\n%{throwable}
</format>
</stream>
</targets>
<categories>
<!-- Role Manager Logger -->
<category name="rm" log-level="INFO">
<log-target id-ref="console"/>
</category>
<!-- Component Manager Logger -->
<category name="cm" log-level="INFO">
<log-target id-ref="console"/>
</category>
<!-- Application Loggers -->
<category name="app" log-level="INFO">
<log-target id-ref="console"/>
<category name="jdbc" log-level="INFO">
<log-target id-ref="console"/>
</category>
</category>
</categories>
</logkit>
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/conf/roles.xml
Index: roles.xml
===================================================================
<role-list logger="rm">
<!-- =================================================================== -->
<!-- DataSource roles. -->
<!-- =================================================================== -->
<role name="org.apache.avalon.excalibur.datasource.DataSourceComponentSelector"
shorthand="datasources"
default-class="org.apache.avalon.excalibur.component.ExcaliburComponentSelector">
<hint shorthand="jdbc" class="org.apache.avalon.excalibur.datasource.JdbcDataSource"/>
<hint shorthand="j2ee" class="org.apache.avalon.excalibur.datasource.J2eeDataSource"/>
</role>
<!-- =================================================================== -->
<!-- Application roles. -->
<!-- =================================================================== -->
<role name="org.apache.avalon.examples.jdbcdatasource.HelloDBService"
shorthand="hello-db"
default-class="org.apache.avalon.examples.jdbcdatasource.DefaultHelloDBService"/>
</role-list>
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/src/java/org/apache/avalon/examples/jdbcdatasource/DefaultHelloDBService.java
Index: DefaultHelloDBService.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.avalon.examples.jdbcdatasource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import org.apache.avalon.excalibur.datasource.DataSourceComponent;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.ComponentSelector;
import org.apache.avalon.framework.component.Composable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
/**
* This example application creates a conmponent which makes use of a JdbcDataSource to
* connect to a Hypersonic SQL database. It then adds a row to a table that it creates
* displaying a list of all the rows in the table.
*
* Note, this code ignores exceptions to keep the code simple.
*
* @author <a href="mailto:leif@silveregg.co.jp">Leif Mortenson</a>
* @version CVS $Revision: 1.1 $ $Date: 2002/02/07 07:15:42 $
* @since 4.1
*/
public class DefaultHelloDBService
extends AbstractLogEnabled
implements HelloDBService, Composable, Configurable, Initializable, Disposable
{
/** ComponentManager which created this component */
protected ComponentManager m_manager;
private String m_dataSourceName;
private ComponentSelector m_dbSelector;
private DataSourceComponent m_dataSource;
/*---------------------------------------------------------------
* Constructors
*-------------------------------------------------------------*/
public DefaultHelloDBService()
{
}
/*---------------------------------------------------------------
* Private Methods
*-------------------------------------------------------------*/
/**
* Allocates a connection for the caller. The connection must be closed by the caller
* when no longer needed.
*
* @return an open DB connection.
*
* @throws SQLException if the connection can not be obtained for any reason.
*/
private Connection getConnection()
throws SQLException
{
return m_dataSource.getConnection();
}
/**
* Initializes the database by creating the required table. Normally
* this would not be needed. But doing this with HSQLDB makes it easier
* to run the example.
*/
private void initializeDatabase()
throws SQLException
{
try
{
Connection conn = getConnection();
try
{
PreparedStatement stmt = conn.prepareStatement(
"CREATE CACHED TABLE titles ( " +
" title VARCHAR NOT NULL, " +
" time TIMESTAMP NOT NULL " +
")" );
stmt.executeUpdate();
}
finally
{
// Return the connection to the pool by closing it.
conn.close();
}
}
catch ( SQLException e )
{
if ( e.getMessage().startsWith( "Table already exists" ) )
{
// Table is already there. Must have run the example before.
}
else
{
throw e;
}
}
}
/*---------------------------------------------------------------
* HelloDBService Methods
*-------------------------------------------------------------*/
/**
* Adds a single row to the database.
*/
public void addRow( String title )
{
getLogger().debug( "DefaultHelloDBService.addRow(" + title + ")" );
try
{
Connection conn = getConnection();
try
{
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO titles (title, time) VALUES (?, now())" );
stmt.setString( 1, title );
int result = stmt.executeUpdate();
if ( result == 1 )
{
System.out.println( "Added '" + title + "' to the database." );
}
else
{
getLogger().error( "Unable to add title to the database. database returned " +
result + " inserted." );
}
}
finally
{
// Return the connection to the pool by closing it.
conn.close();
}
}
catch ( SQLException e )
{
getLogger().error( "Unable to add title to the database.", e );
}
}
/**
* Ask the component to delete all rows in the database.
*/
public void deleteRows()
{
getLogger().debug( "DefaultHelloDBService.deleteRows()" );
try
{
Connection conn = getConnection();
try
{
PreparedStatement stmt = conn.prepareStatement(
"DELETE FROM titles" );
int result = stmt.executeUpdate();
System.out.println( "Deleted " + result + " titles from the database." );
}
finally
{
// Return the connection to the pool by closing it.
conn.close();
}
}
catch ( SQLException e )
{
getLogger().error( "Unable to delete old titles from the database.", e );
}
}
/**
* Ask the component to log all of the rows in the database to the logger
* with the info log level.
*/
public void logRows()
{
getLogger().debug( "DefaultHelloDBService.logRows()" );
try
{
Connection conn = getConnection();
try
{
PreparedStatement stmt = conn.prepareStatement(
"SELECT title, time FROM titles" );
ResultSet rs = stmt.executeQuery();
int count = 0;
while ( rs.next() )
{
String title = rs.getString( 1 );
Timestamp time = rs.getTimestamp( 2 );
System.out.println( " '" + title + "' saved at " + time );
count++;
}
if ( count == 0 )
{
System.out.println( "The database does not contain any saved titles." );
}
else
{
System.out.println( "The database contains " + count + " titles." );
}
}
finally
{
// Return the connection to the pool by closing it.
conn.close();
}
}
catch ( SQLException e )
{
getLogger().error( "Unable to delete old titles from the database.", e );
}
}
/*---------------------------------------------------------------
* Composable Methods
*-------------------------------------------------------------*/
/**
* Called by the Container to tell the component which ComponentManager
* is controlling it.
*
* @param ComponentManager which curently owns the component.
*/
public void compose( ComponentManager manager )
{
getLogger().debug( "DefaultHelloDBService.compose()" );
m_manager = manager;
}
/*---------------------------------------------------------------
* Configurable Methods
*-------------------------------------------------------------*/
/**
* Called by the Container to configure the component.
*
* @param configuration configuration info used to setup the component.
*
* @throws ConfigurationException if there are any problems with the configuration.
*/
public void configure( Configuration configuration )
throws ConfigurationException
{
getLogger().debug( "DefaultHelloDBService.configure()" );
// Obtain a reference to the configured DataSource
m_dataSourceName = configuration.getChild( "dbpool" ).getValue();
}
/*---------------------------------------------------------------
* Initializable Methods
*-------------------------------------------------------------*/
/**
* Called by the Container to initialize the component.
*
* @throws Exception if there were any problems durring initialization.
*/
public void initialize()
throws Exception
{
getLogger().debug( "DefaultHelloDBService.initialize()" );
// Get a reference to a data source
m_dbSelector = (ComponentSelector)m_manager.lookup( DataSourceComponent.ROLE + "Selector" );
m_dataSource = (DataSourceComponent)m_dbSelector.select( m_dataSourceName );
// Initialize the database.
initializeDatabase();
}
/*---------------------------------------------------------------
* Disposable Methods
*-------------------------------------------------------------*/
/**
* Called by the Container to dispose the component.
*/
public void dispose()
{
getLogger().debug( "DefaultHelloDBService.dispose()" );
// Free up the data source
if ( m_dbSelector != null )
{
if ( m_dataSource != null )
{
m_dbSelector.release( m_dataSource );
m_dataSource = null;
}
m_manager.release( m_dbSelector );
m_dbSelector = null;
}
}
}
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/src/java/org/apache/avalon/examples/jdbcdatasource/HelloDBService.java
Index: HelloDBService.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.avalon.examples.jdbcdatasource;
import org.apache.avalon.framework.component.Component;
/**
* This example application creates a conmponent which makes use of a JdbcDataSource to
* connect to a Hypersonic SQL database. It then adds a row to a table that it creates
* displaying a list of all the rows in the table.
*
* Note, this code ignores exceptions to keep the code simple.
*
* @author <a href="mailto:leif@silveregg.co.jp">Leif Mortenson</a>
* @version CVS $Revision: 1.1 $ $Date: 2002/02/07 07:15:42 $
* @since 4.1
*/
public interface HelloDBService
extends Component
{
String ROLE = "org.apache.avalon.examples.jdbcdatasource.HelloDBService";
/**
* Adds a single row to the database.
*/
void addRow( String title );
/**
* Ask the component to delete all rows in the database.
*/
void deleteRows();
/**
* Ask the component to log all of the rows in the database to the logger
* with the info log level.
*/
void logRows();
}
1.1 jakarta-avalon-excalibur/examples/jdbcdatasource/src/java/org/apache/avalon/examples/jdbcdatasource/Main.java
Index: Main.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.avalon.examples.jdbcdatasource;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.avalon.excalibur.component.DefaultRoleManager;
import org.apache.avalon.excalibur.component.ExcaliburComponentManager;
import org.apache.avalon.excalibur.logger.DefaultLogKitManager;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.avalon.framework.context.DefaultContext;
import org.apache.log.Hierarchy;
import org.apache.log.Logger;
import org.apache.log.Priority;
/**
* This example application creates a conmponent which makes use of a JdbcDataSource to
* connect to a Hypersonic SQL database. It then adds a row to a table that it creates
* displaying a list of all the rows in the table.
*
* Note, this code ignores exceptions to keep the code simple.
*
* @author <a href="mailto:leif@silveregg.co.jp">Leif Mortenson</a>
* @version CVS $Revision: 1.1 $ $Date: 2002/02/07 07:15:42 $
* @since 4.1
*/
public class Main
{
/*---------------------------------------------------------------
* Constructors
*-------------------------------------------------------------*/
private Main() {}
/*---------------------------------------------------------------
* Methods
*-------------------------------------------------------------*/
/**
* Loads a Configuration object given a config filename.
*/
private static Configuration loadConfiguration( DefaultConfigurationBuilder builder,
String file )
throws Exception
{
FileInputStream is = new FileInputStream( file );
try
{
return builder.build( is );
}
finally
{
is.close();
}
}
/**
* Creates and initializes the component manager using config files.
*/
private static ExcaliburComponentManager createComponentManager()
throws Exception
{
// Create a context to use.
DefaultContext context = new DefaultContext();
// Add any context variables here.
context.makeReadOnly();
// Create a ConfigurationBuilder to parse the config files.
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
// Load in the configuration files
Configuration logKitConfig = loadConfiguration( builder, "../conf/logkit.xml" );
Configuration rolesConfig = loadConfiguration( builder, "../conf/roles.xml" );
Configuration componentsConfig = loadConfiguration( builder, "../conf/components.xml" );
// Setup the LogKitManager
DefaultLogKitManager logManager = new DefaultLogKitManager();
Logger lmLogger = Hierarchy.getDefaultHierarchy().
getLoggerFor( logKitConfig.getAttribute( "logger", "INFO" ) );
lmLogger.setPriority(
Priority.getPriorityForName( logKitConfig.getAttribute( "log-level", "INFO" ) ) );
logManager.setLogger( lmLogger );
logManager.configure( logKitConfig );
// Setup the RoleManager
DefaultRoleManager roleManager = new DefaultRoleManager();
roleManager.setLogger(
logManager.getLogger( rolesConfig.getAttribute( "logger", "INFO" ) ) );
roleManager.configure( rolesConfig );
// Set up the ComponentManager
ExcaliburComponentManager manager = new ExcaliburComponentManager();
manager.setLogger(
logManager.getLogger( componentsConfig.getAttribute( "logger", "INFO" ) ) );
manager.setLogKitManager( logManager );
manager.contextualize( context );
manager.setRoleManager( roleManager );
manager.configure( componentsConfig );
manager.initialize();
return manager;
}
/**
* Loop and handle requests from the user.
*/
private static void handleRequests( HelloDBService helloDB )
{
System.out.println();
System.out.println( "Please enter a title to be added to the database" );
System.out.println( " (RESET deletes all titles, LIST lists all titles, QUIT or EXIT to quit)" );
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
String title;
boolean quit = false;
do
{
System.out.print ( ": " );
try
{
title = in.readLine();
}
catch (IOException e)
{
title = "";
}
if ( title.length() > 0 )
{
if ( title.equalsIgnoreCase( "RESET" ) )
{
System.out.println( "Deleting all titles currently in the database..." );
helloDB.deleteRows();
}
else if ( title.equalsIgnoreCase( "LIST" ) )
{
System.out.println( "Listing all titles currently in the database..." );
helloDB.logRows();
}
else if ( title.equalsIgnoreCase( "QUIT" ) || title.equalsIgnoreCase( "EXIT" ) )
{
quit = true;
}
else
{
System.out.println( "Adding title '" + title + "' to the database..." );
helloDB.addRow( title );
}
}
}
while ( !quit );
System.out.println();
}
/*---------------------------------------------------------------
* Main method
*-------------------------------------------------------------*/
/**
* All of the guts of this example exist in the main method.
*/
public static void main( String[] args )
throws Exception
{
System.out.println( "Running the JdbcDataSource Example Application" );
// Create the ComponentManager
ExcaliburComponentManager manager = createComponentManager();
try
{
// Obtain a reference to the HelloDBService instance
HelloDBService helloDB = (HelloDBService)manager.lookup( HelloDBService.ROLE );
try
{
handleRequests( helloDB );
}
finally
{
// Release the HelloDBService instance
manager.release( helloDB );
helloDB = null;
}
}
finally
{
// Dispose the ComponentManager
manager.dispose();
}
System.out.println();
System.out.println( "Exiting..." );
System.exit(0);
}
}
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>