KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > acting > modular > DatabaseQueryAction


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

16
17 package org.apache.cocoon.acting.modular;
18
19 import java.sql.Connection JavaDoc;
20 import java.sql.PreparedStatement JavaDoc;
21 import java.sql.ResultSet JavaDoc;
22 import java.sql.ResultSetMetaData JavaDoc;
23 import java.sql.SQLException JavaDoc;
24 import java.util.Map JavaDoc;
25
26 import org.apache.avalon.framework.configuration.Configuration;
27 import org.apache.avalon.framework.configuration.ConfigurationException;
28 import org.apache.avalon.framework.service.ServiceException;
29
30 /**
31  * Executes an arbitrary query. The query is associated with a table
32  * and selected through the others mode. All keys and values are set
33  * in order of appearance, starting with keys, thus the query needs to
34  * have as many placeholders for prepared statement parameters. If it
35  * is an update query, the number of affected rows is returned to the
36  * sitemap.
37  *
38  *<pre>
39  * &lt;table name="example"&gt;
40  * &lt;queries&gt;
41  * &lt;query mode="one"&gt;update example set count=count+1 where id=?&lt;/query&gt;
42  * &lt;query mode="two"&gt;select count, name from example where id=?&lt;/query&gt;
43  * &lt;/queries&gt;
44  * &lt;keys&gt;
45  * &lt;key name="id"/&gt;
46  * &lt;/keys&gt;
47  * &lt;values/&gt;
48  * &lt;/table&gt;
49  *</pre>
50  *
51  * @author <a HREF="mailto:haul@apache.org">Christian Haul</a>
52  * @version CVS $Id: DatabaseQueryAction.java 124698 2005-01-09 01:57:13Z antonio $
53  */

54 public class DatabaseQueryAction extends DatabaseAction {
55
56     /**
57      * determine which mode to use as default mode
58      * here: SELECT
59      * highly specific to operation INSERT / UPDATE / DELETE / SELECT
60      */

61     protected String JavaDoc selectMode ( boolean isAutoIncrement, Map JavaDoc modes ) {
62         
63         return (String JavaDoc) modes.get( MODE_OTHERS );
64     }
65
66     /**
67      * determine whether autoincrement columns should be honoured by
68      * this operation. This is usually snsible only for INSERTs.
69      */

70     protected boolean honourAutoIncrement() { return false; }
71
72
73     /**
74      * Get the String representation of the PreparedStatement. This is
75      * mapped to the Configuration object itself, so if it doesn't exist,
76      * it will be created.
77      *
78      * @param table the table's configuration object
79      * @return the insert query as a string
80      */

81     protected CacheHelper getQuery( Configuration table, Map JavaDoc modeTypes, Map JavaDoc defaultModeNames )
82         throws ConfigurationException, ServiceException {
83
84         LookUpKey lookUpKey = new LookUpKey( table, modeTypes );
85         CacheHelper queryData = null;
86         synchronized( this.cachedQueryData ) {
87             queryData = (CacheHelper) this.cachedQueryData.get( lookUpKey );
88             if (queryData == null) {
89                 Configuration[] queries = table.getChild("queries").getChildren("query");
90                 Configuration[] keys = table.getChild("keys").getChildren("key");
91                 Configuration[] values = table.getChild("values").getChildren("value");
92
93                 boolean found = false;
94                 String JavaDoc queryModeName = "";
95                 String JavaDoc query = "";
96                 boolean useValues = true;
97                 for (int i=0; i<queries.length; i++) {
98                     queryModeName = queries[i].getAttribute("mode",null);
99                     if ( queryModeName.equals(modeTypes.get(MODE_OTHERS)) || "all".equals(queryModeName)) {
100                         query = queries[i].getValue();
101                         useValues = queries[i].getAttributeAsBoolean("use-values", useValues);
102                         found = true;
103                         break;
104                     }
105                 }
106
107                 if (!found) {
108                     throw new ConfigurationException("Could not find query mode " +
109                                                      modeTypes.get(MODE_OTHERS) +
110                                                      " for table " + table.getAttribute("name",null));
111                 }
112
113                 
114
115                 queryData = new CacheHelper( keys.length, keys.length + (useValues ? values.length : 0));
116                 queryData.queryString = query;
117                 fillModes( keys , true , defaultModeNames, modeTypes, queryData );
118                 if (useValues) fillModes( values, false, defaultModeNames, modeTypes, queryData );
119                 
120                 this.cachedQueryData.put( lookUpKey, queryData );
121             }
122         }
123
124         return queryData;
125     }
126
127
128     /**
129      * Fetch all values for all columns that are needed to do the database operation.
130      */

131     protected Object JavaDoc[][] getColumnValues( Configuration tableConf, CacheHelper queryData, Map JavaDoc objectModel )
132         throws ConfigurationException, ServiceException {
133
134         Object JavaDoc[][] columnValues = new Object JavaDoc[ queryData.columns.length ][];
135         for ( int i = 0; i < queryData.columns.length; i++ ){
136             columnValues[i] = this.getColumnValue( tableConf, queryData.columns[i], objectModel );
137         }
138         return columnValues;
139     }
140
141
142     /**
143      * set all necessary ?s and execute the query
144      */

145     protected int processRow ( Map JavaDoc objectModel, Connection JavaDoc conn, PreparedStatement JavaDoc statement, String JavaDoc outputMode,
146                                Configuration table, CacheHelper queryData, Object JavaDoc[][] columnValues,
147                                int rowIndex, Map JavaDoc results )
148         throws SQLException JavaDoc, ConfigurationException, Exception JavaDoc {
149
150         int currentIndex = 1;
151
152         // ordering is different for SELECT just needs keys
153
for (int i = 0; i < queryData.columns.length; i++) {
154             Column col = queryData.columns[i];
155             if ( col.isKey ) {
156                 this.setColumn(objectModel, outputMode, results, table, col.columnConf, rowIndex,
157                                columnValues[ i ][ ( col.isSet ? rowIndex : 0 ) ], statement, currentIndex );
158                 currentIndex++;
159             }
160         }
161         boolean hasResult = statement.execute();
162         if (!hasResult) {
163             return statement.getUpdateCount();
164         } else {
165             // retrieve values
166
ResultSet JavaDoc resultset = statement.getResultSet();
167             ResultSetMetaData JavaDoc metadata = resultset.getMetaData();
168             rowIndex = 0;
169             while ( resultset.next() ){
170                 //if ( ! ( rowIndex == -1 && resultset.isLast() ) ) {
171
rowIndex++;
172                 //}
173
String JavaDoc tableName = "";
174                 String JavaDoc columnName = "";
175                 for (int i = 1; i <= metadata.getColumnCount(); i++) {
176                     Object JavaDoc value = resultset.getObject(i);
177                     tableName = metadata.getTableName(i);
178                     columnName = metadata.getColumnLabel(i) + "[" + rowIndex + "]";
179                     if (!tableName.equals("")) {
180                         columnName = tableName + "." + columnName;
181                     }
182                     if (this.getLogger().isDebugEnabled()) {
183                         this.getLogger().debug("retrieving " + columnName + " as " + value);
184                     }
185                     results.put(metadata.getTableName(i)+"."+metadata.getColumnLabel(i),value);
186                 }
187             }
188             return rowIndex;
189         }
190     }
191
192
193 }
194
Popular Tags