KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > examples > jdbcdatasource > DefaultHelloDBService


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14  * implied.
15  *
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */

19
20 package org.apache.avalon.examples.jdbcdatasource;
21
22 import java.sql.Connection JavaDoc;
23 import java.sql.PreparedStatement JavaDoc;
24 import java.sql.ResultSet JavaDoc;
25 import java.sql.SQLException JavaDoc;
26 import java.sql.Timestamp JavaDoc;
27
28 import org.apache.avalon.excalibur.datasource.DataSourceComponent;
29 import org.apache.avalon.framework.activity.Disposable;
30 import org.apache.avalon.framework.activity.Initializable;
31 import org.apache.avalon.framework.configuration.Configurable;
32 import org.apache.avalon.framework.configuration.Configuration;
33 import org.apache.avalon.framework.configuration.ConfigurationException;
34 import org.apache.avalon.framework.logger.AbstractLogEnabled;
35 import org.apache.avalon.framework.service.ServiceException;
36 import org.apache.avalon.framework.service.ServiceManager;
37 import org.apache.avalon.framework.service.ServiceSelector;
38 import org.apache.avalon.framework.service.Serviceable;
39
40 /**
41  * This example application creates a conmponent which makes use of a JdbcDataSource to
42  * connect to a Hypersonic SQL database. It then adds a row to a table that it creates
43  * displaying a list of all the rows in the table.
44  *
45  * Note, this code ignores exceptions to keep the code simple.
46  *
47  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
48  * @version CVS $Revision: 1.4 $ $Date: 2004/02/28 11:47:28 $
49  * @since 4.1
50  */

51 public class DefaultHelloDBService
52     extends AbstractLogEnabled
53     implements HelloDBService, Serviceable, Configurable, Initializable, Disposable
54 {
55     /** ComponentManager which created this component */
56     private String JavaDoc m_dataSourceName;
57     private ServiceSelector m_dbSelector;
58     private DataSourceComponent m_dataSource;
59
60     /*---------------------------------------------------------------
61      * Constructors
62      *-------------------------------------------------------------*/

63     /** Instantiate a DefaultHelloDBService */
64     public DefaultHelloDBService()
65     {
66     }
67
68     /*---------------------------------------------------------------
69      * Private Methods
70      *-------------------------------------------------------------*/

71     /**
72      * Allocates a connection for the caller. The connection must be closed by the caller
73      * when no longer needed.
74      *
75      * @return an open DB connection.
76      *
77      * @throws SQLException if the connection can not be obtained for any reason.
78      */

79     private Connection JavaDoc getConnection()
80         throws SQLException JavaDoc
81     {
82         return m_dataSource.getConnection();
83     }
84
85     /**
86      * Initializes the database by creating the required table. Normally
87      * this would not be needed. But doing this with HSQLDB makes it easier
88      * to run the example.
89      *
90      * @throws SQLException if there is a problem setting the database up.
91      */

92     private void initializeDatabase()
93         throws SQLException JavaDoc
94     {
95         try
96         {
97             Connection JavaDoc conn = getConnection();
98             try
99             {
100                 PreparedStatement JavaDoc stmt = conn.prepareStatement(
101                     "CREATE CACHED TABLE titles ( " +
102                     " title VARCHAR NOT NULL, " +
103                     " time TIMESTAMP NOT NULL " +
104                     ")" );
105                 stmt.executeUpdate();
106             }
107             finally
108             {
109                 // Return the connection to the pool by closing it.
110
conn.close();
111             }
112         }
113         catch( SQLException JavaDoc e )
114         {
115             if( e.getMessage().startsWith( "Table already exists" ) )
116             {
117                 // Table is already there. Must have run the example before.
118
}
119             else
120             {
121                 throw e;
122             }
123         }
124     }
125
126     /*---------------------------------------------------------------
127      * HelloDBService Methods
128      *-------------------------------------------------------------*/

129     /**
130      * Adds a single row to the database.
131      *
132      * @param title The row title
133      */

134     public void addRow( String JavaDoc title )
135     {
136         getLogger().debug( "DefaultHelloDBService.addRow(" + title + ")" );
137
138         try
139         {
140             Connection JavaDoc conn = getConnection();
141             try
142             {
143                 PreparedStatement JavaDoc stmt = conn.prepareStatement(
144                     "INSERT INTO titles (title, time) VALUES (?, now())" );
145                 stmt.setString( 1, title );
146                 int result = stmt.executeUpdate();
147                 if( result == 1 )
148                 {
149                     System.out.println( "Added '" + title + "' to the database." );
150                 }
151                 else
152                 {
153                     getLogger().error( "Unable to add title to the database. database returned " +
154                                        result + " inserted." );
155                 }
156             }
157             finally
158             {
159                 // Return the connection to the pool by closing it.
160
conn.close();
161             }
162         }
163         catch( SQLException JavaDoc e )
164         {
165             getLogger().error( "Unable to add title to the database.", e );
166         }
167     }
168
169     /**
170      * Ask the component to delete all rows in the database.
171      */

172     public void deleteRows()
173     {
174         getLogger().debug( "DefaultHelloDBService.deleteRows()" );
175
176         try
177         {
178             Connection JavaDoc conn = getConnection();
179             try
180             {
181                 PreparedStatement JavaDoc stmt = conn.prepareStatement(
182                     "DELETE FROM titles" );
183                 int result = stmt.executeUpdate();
184                 System.out.println( "Deleted " + result + " titles from the database." );
185             }
186             finally
187             {
188                 // Return the connection to the pool by closing it.
189
conn.close();
190             }
191         }
192         catch( SQLException JavaDoc e )
193         {
194             getLogger().error( "Unable to delete old titles from the database.", e );
195         }
196     }
197
198     /**
199      * Ask the component to log all of the rows in the database to the logger
200      * with the info log level.
201      */

202     public void logRows()
203     {
204         getLogger().debug( "DefaultHelloDBService.logRows()" );
205
206         try
207         {
208             Connection JavaDoc conn = getConnection();
209             try
210             {
211                 PreparedStatement JavaDoc stmt = conn.prepareStatement(
212                     "SELECT title, time FROM titles" );
213                 ResultSet JavaDoc rs = stmt.executeQuery();
214                 int count = 0;
215                 while( rs.next() )
216                 {
217                     String JavaDoc title = rs.getString( 1 );
218                     Timestamp JavaDoc time = rs.getTimestamp( 2 );
219
220                     System.out.println( " '" + title + "' saved at " + time );
221                     count++;
222                 }
223
224                 if( count == 0 )
225                 {
226                     System.out.println( "The database does not contain any saved titles." );
227                 }
228                 else
229                 {
230                     System.out.println( "The database contains " + count + " titles." );
231                 }
232             }
233             finally
234             {
235                 // Return the connection to the pool by closing it.
236
conn.close();
237             }
238         }
239         catch( SQLException JavaDoc e )
240         {
241             getLogger().error( "Unable to delete old titles from the database.", e );
242         }
243     }
244
245     /*---------------------------------------------------------------
246      * Composable Methods
247      *-------------------------------------------------------------*/

248     /**
249      * Called by the Container to tell the component which ComponentManager
250      * is controlling it.
251      *
252      * @param manager which curently owns the component.
253      *
254      * @avalon.service interface="org.apache.avalon.excalibur.datasource.DataSourceComponentSelector"
255      */

256     public void service( final ServiceManager manager )
257         throws ServiceException
258     {
259         getLogger().debug( "DefaultHelloDBService.compose()" );
260         m_dbSelector = (ServiceSelector)manager.lookup( DataSourceComponent.ROLE + "Selector" );
261     }
262
263     /*---------------------------------------------------------------
264      * Configurable Methods
265      *-------------------------------------------------------------*/

266     /**
267      * Called by the Container to configure the component.
268      *
269      * @param configuration configuration info used to setup the component.
270      *
271      * @throws ConfigurationException if there are any problems with the configuration.
272      */

273     public void configure( Configuration configuration )
274         throws ConfigurationException
275     {
276         getLogger().debug( "DefaultHelloDBService.configure()" );
277
278         // Obtain a reference to the configured DataSource
279
m_dataSourceName = configuration.getChild( "dbpool" ).getValue();
280     }
281
282     /*---------------------------------------------------------------
283      * Initializable Methods
284      *-------------------------------------------------------------*/

285     /**
286      * Called by the Container to initialize the component.
287      *
288      * @throws Exception if there were any problems durring initialization.
289      */

290     public void initialize()
291         throws Exception JavaDoc
292     {
293         getLogger().debug( "DefaultHelloDBService.initialize()" );
294
295         // Get a reference to a data source
296
m_dataSource = (DataSourceComponent)m_dbSelector.select( m_dataSourceName );
297
298         // Initialize the database.
299
initializeDatabase();
300     }
301
302     /*---------------------------------------------------------------
303      * Disposable Methods
304      *-------------------------------------------------------------*/

305     /**
306      * Called by the Container to dispose the component.
307      */

308     public void dispose()
309     {
310         getLogger().debug( "DefaultHelloDBService.dispose()" );
311
312         // Free up the data source
313
if( m_dbSelector != null )
314         {
315             if( m_dataSource != null )
316             {
317                 m_dbSelector.release( m_dataSource );
318                 m_dataSource = null;
319             }
320             m_dbSelector = null;
321         }
322     }
323 }
324
325
Popular Tags