1 17 package org.apache.log.output.db; 18 19 import java.sql.PreparedStatement ; 20 import java.sql.ResultSet ; 21 import java.sql.SQLException ; 22 import java.sql.Statement ; 23 import java.util.HashMap ; 24 import javax.sql.DataSource ; 25 import org.apache.log.LogEvent; 26 27 36 public class NormalizedJDBCTarget 37 extends DefaultJDBCTarget 38 { 39 private HashMap m_categoryIDs = new HashMap (); 40 private HashMap m_priorityIDs = new HashMap (); 41 42 public NormalizedJDBCTarget( final DataSource dataSource, 43 final String table, 44 final ColumnInfo[] columns ) 45 { 46 super( dataSource, table, columns ); 47 } 48 49 52 protected void specifyColumn( final PreparedStatement statement, 53 final int index, 54 final LogEvent event ) 55 throws SQLException 56 { 57 final ColumnInfo info = getColumn( index ); 58 int id = 0; 59 String tableName = null; 60 61 switch( info.getType() ) 62 { 63 case ColumnType.CATEGORY: 64 tableName = getTable() + "_" + ColumnType.CATEGORY_STR + "_SET"; 65 id = getID( tableName, m_categoryIDs, event.getCategory() ); 66 statement.setInt( index + 1, id ); 67 break; 68 69 case ColumnType.PRIORITY: 70 tableName = getTable() + "_" + ColumnType.PRIORITY_STR + "_SET"; 71 id = getID( tableName, m_priorityIDs, event.getPriority().getName() ); 72 statement.setInt( index + 1, id ); 73 break; 74 75 default: 76 super.specifyColumn( statement, index, event ); 77 } 78 } 79 80 protected synchronized int getID( final String tableName, final HashMap idMap, final String instance ) 81 throws SQLException 82 { 83 final Integer id = (Integer )idMap.get( instance ); 84 if( null != id ) return id.intValue(); 85 86 Statement statement = null; 88 ResultSet resultSet = null; 89 90 try 91 { 92 statement = getConnection().createStatement(); 93 94 final String querySql = "SELECT ID FROM " + tableName + " WHERE NAME='" + instance + "'"; 95 resultSet = statement.executeQuery( querySql ); 96 97 if( resultSet.next() ) 98 { 99 final Integer newID = new Integer ( resultSet.getInt( 1 ) ); 100 idMap.put( instance, newID ); 101 return newID.intValue(); 102 } 103 104 resultSet.close(); 105 106 109 final String maxQuerySql = "SELECT MAX(ID) FROM " + tableName; 112 resultSet = statement.executeQuery( maxQuerySql ); 113 int max = 0; 114 if( resultSet.next() ) max = resultSet.getInt( 1 ); 115 resultSet.close(); 116 117 final int newID = max + 1; 118 final String insertSQL = "INSERT INTO " + tableName + 119 " (ID, NAME) VALUES ( " + newID + ", '" + instance + "')"; 120 statement.executeUpdate( insertSQL ); 121 122 idMap.put( instance, new Integer ( newID ) ); 123 return newID; 124 } 125 finally 126 { 127 if( null != resultSet ) 129 { 130 try 131 { 132 resultSet.close(); 133 } 134 catch( final Exception e ) 135 { 136 } 137 } 138 if( null != statement ) 139 { 140 try 141 { 142 statement.close(); 143 } 144 catch( final Exception e ) 145 { 146 } 147 } 148 } 149 } 150 } 151 | Popular Tags |