KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > log > output > db > DefaultJDBCTarget


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

17 package org.apache.log.output.db;
18
19 import java.io.StringWriter JavaDoc;
20 import java.sql.Connection JavaDoc;
21 import java.sql.PreparedStatement JavaDoc;
22 import java.sql.SQLException JavaDoc;
23 import java.sql.Timestamp JavaDoc;
24 import javax.sql.DataSource JavaDoc;
25 import org.apache.log.ContextMap;
26 import org.apache.log.LogEvent;
27
28 /**
29  * The basic DB target for configurable output formats.
30  *
31  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
32  * @author Peter Donald
33  */

34 public class DefaultJDBCTarget
35     extends AbstractJDBCTarget
36 {
37     private final String JavaDoc m_table;
38     private final ColumnInfo[] m_columns;
39
40     private PreparedStatement JavaDoc m_statement;
41
42     /**
43      * Creation of a new JDBC logging target.
44      * @param dataSource the JDBC datasource
45      * @param table the table
46      * @param columns a ColumnInfo array
47      */

48     public DefaultJDBCTarget( final DataSource JavaDoc dataSource,
49                               final String JavaDoc table,
50                               final ColumnInfo[] columns )
51     {
52         super( dataSource );
53         m_table = table;
54         m_columns = columns;
55
56         if( null == table )
57         {
58             throw new NullPointerException JavaDoc( "table property must not be null" );
59         }
60
61         if( null == columns )
62         {
63             throw new NullPointerException JavaDoc( "columns property must not be null" );
64         }
65
66         if( 0 == columns.length )
67         {
68             throw new NullPointerException JavaDoc( "columns must have at least 1 element" );
69         }
70
71         open();
72     }
73
74     /**
75      * Output a log event to DB.
76      * This must be implemented by subclasses.
77      *
78      * @param event the log event.
79      */

80     protected synchronized void output( final LogEvent event )
81     {
82         //TODO: Retry logic so that this method is called multiple times if it fails
83
//Make retry configurable and if fail send event onto ErrorHandler
84
try
85         {
86             for( int i = 0; i < m_columns.length; i++ )
87             {
88                 specifyColumn( m_statement, i, event );
89             }
90
91             m_statement.executeUpdate();
92         }
93         catch( final SQLException JavaDoc se )
94         {
95             getErrorHandler().error( "Error executing statement", se, event );
96         }
97     }
98
99     /**
100      * Open connection to underlying database.
101      *
102      */

103     protected synchronized void openConnection()
104     {
105         //if( null != m_statement ) return;
106
super.openConnection();
107
108         m_statement = null;
109         try
110         {
111             final Connection JavaDoc connection = getConnection();
112             if( null != connection )
113             {
114                 m_statement = connection.prepareStatement( getStatementSQL() );
115             }
116         }
117         catch( final SQLException JavaDoc se )
118         {
119             getErrorHandler().error( "Error preparing statement", se, null );
120         }
121     }
122
123     /**
124      * Return the SQL insert statement.
125      * @return the statement
126      */

127     protected String JavaDoc getStatementSQL()
128     {
129         final StringBuffer JavaDoc sb = new StringBuffer JavaDoc( "INSERT INTO " );
130         sb.append( m_table );
131         sb.append( " (" );
132         sb.append( m_columns[ 0 ].getName() );
133
134         for( int i = 1; i < m_columns.length; i++ )
135         {
136             sb.append( ", " );
137             sb.append( m_columns[ i ].getName() );
138         }
139
140         sb.append( ") VALUES (?" );
141
142         for( int i = 1; i < m_columns.length; i++ )
143         {
144             sb.append( ", ?" );
145         }
146
147         sb.append( ")" );
148
149         return sb.toString();
150     }
151
152     /**
153      * Test if the target is stale.
154      * @return TRUE if the target is stale else FALSE
155      */

156     protected boolean isStale()
157     {
158         return super.isStale();
159         //Check: "SELECT * FROM " + m_table + " WHERE 0 = 99" here ...
160
}
161
162     /**
163      * Close connection to underlying database.
164      *
165      */

166     protected synchronized void closeConnection()
167     {
168         //close prepared statement here
169
super.closeConnection();
170
171         if( null != m_statement )
172         {
173             try
174             {
175                 m_statement.close();
176             }
177             catch( final SQLException JavaDoc se )
178             {
179                 getErrorHandler().error( "Error closing statement", se, null );
180             }
181
182             m_statement = null;
183         }
184     }
185
186     /**
187      * Adds a single object into statement.
188      * @param statement the prepard statement
189      * @param index the index
190      * @param event the log event
191      * @exception SQLException if an SQL related error occurs
192      * @exception IllegalStateException if the supplied index is out of bounds
193      */

194     protected void specifyColumn( final PreparedStatement JavaDoc statement,
195                                   final int index,
196                                   final LogEvent event )
197         throws SQLException JavaDoc,
198         IllegalStateException JavaDoc
199     {
200         final ColumnInfo info = m_columns[ index ];
201
202         switch( info.getType() )
203         {
204             case ColumnType.RELATIVE_TIME:
205                 statement.setLong( index + 1, event.getRelativeTime() );
206                 break;
207
208             case ColumnType.TIME:
209                 statement.setTimestamp( index + 1, new Timestamp JavaDoc( event.getTime() ) );
210                 break;
211
212             case ColumnType.MESSAGE:
213                 statement.setString( index + 1, event.getMessage() );
214                 break;
215
216             case ColumnType.CATEGORY:
217                 statement.setString( index + 1, event.getCategory() );
218                 break;
219
220             case ColumnType.PRIORITY:
221                 statement.setString( index + 1, event.getPriority().getName() );
222                 break;
223
224             case ColumnType.CONTEXT:
225                 statement.setString( index + 1, getContextMap( event.getContextMap(),
226                                                                info.getAux() ) );
227                 break;
228
229             case ColumnType.STATIC:
230                 statement.setString( index + 1, info.getAux() );
231                 break;
232
233             case ColumnType.THROWABLE:
234                 statement.setString( index + 1, getStackTrace( event.getThrowable() ) );
235                 break;
236
237             default:
238                 throw new IllegalStateException JavaDoc( "Unknown ColumnType: " + info.getType() );
239         }
240     }
241
242     /**
243      * Return the underlying table
244      * @return the table name
245      */

246     protected final String JavaDoc getTable()
247     {
248         return m_table;
249     }
250
251     /**
252      * Return the column info for an supplied index.
253      * @param index the index
254      * @return the column info
255      */

256     protected final ColumnInfo getColumn( final int index )
257     {
258         return m_columns[ index ];
259     }
260
261     private String JavaDoc getStackTrace( final Throwable JavaDoc throwable )
262     {
263         if( null == throwable )
264         {
265             return "";
266         }
267         final StringWriter JavaDoc sw = new StringWriter JavaDoc();
268         throwable.printStackTrace( new java.io.PrintWriter JavaDoc( sw ) );
269         return sw.toString();
270     }
271
272     private String JavaDoc getContextMap( final ContextMap map, final String JavaDoc aux )
273     {
274         if( null == map )
275         {
276             return "";
277         }
278         else
279         {
280             return map.get( aux, "" ).toString();
281         }
282     }
283 }
284
Popular Tags