KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > access > jdbc > ProcedureAction


1 /* ====================================================================
2  *
3  * The ObjectStyle Group Software License, version 1.1
4  * ObjectStyle Group - http://objectstyle.org/
5  *
6  * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
7  * of the software. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if any,
22  * must include the following acknowlegement:
23  * "This product includes software developed by independent contributors
24  * and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
29  * or promote products derived from this software without prior written
30  * permission. For written permission, email
31  * "andrus at objectstyle dot org".
32  *
33  * 5. Products derived from this software may not be called "ObjectStyle"
34  * or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
35  * names without prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals and hosted on ObjectStyle Group web site. For more
53  * information on the ObjectStyle Group, please see
54  * <http://objectstyle.org/>.
55  */

56 package org.objectstyle.cayenne.access.jdbc;
57
58 import java.sql.CallableStatement JavaDoc;
59 import java.sql.Connection JavaDoc;
60 import java.sql.ResultSet JavaDoc;
61 import java.sql.SQLException JavaDoc;
62 import java.util.Collections JavaDoc;
63 import java.util.HashMap JavaDoc;
64 import java.util.List JavaDoc;
65 import java.util.Map JavaDoc;
66
67 import org.objectstyle.cayenne.CayenneRuntimeException;
68 import org.objectstyle.cayenne.access.OperationObserver;
69 import org.objectstyle.cayenne.access.QueryLogger;
70 import org.objectstyle.cayenne.access.trans.ProcedureTranslator;
71 import org.objectstyle.cayenne.access.types.ExtendedType;
72 import org.objectstyle.cayenne.dba.DbAdapter;
73 import org.objectstyle.cayenne.map.EntityResolver;
74 import org.objectstyle.cayenne.map.Procedure;
75 import org.objectstyle.cayenne.map.ProcedureParameter;
76 import org.objectstyle.cayenne.query.ProcedureQuery;
77
78 /**
79  * A SQLAction that runs a stored procedure. Note that ProcedureAction has internal state
80  * and is not thread-safe.
81  *
82  * @since 1.2
83  * @author Andrei Adamchik
84  */

85 public class ProcedureAction extends BaseSQLAction {
86
87     protected ProcedureQuery query;
88
89     /**
90      * Holds a number of ResultSets processed by the action. This value is reset to zero
91      * on every "performAction" call.
92      */

93     protected int processedResultSets;
94
95     public ProcedureAction(ProcedureQuery query, DbAdapter adapter,
96             EntityResolver entityResolver) {
97         super(adapter, entityResolver);
98         this.query = query;
99     }
100
101     public void performAction(Connection JavaDoc connection, OperationObserver observer)
102             throws SQLException JavaDoc, Exception JavaDoc {
103
104         processedResultSets = 0;
105
106         ProcedureTranslator transl = new ProcedureTranslator();
107         transl.setAdapter(getAdapter());
108         transl.setQuery(query);
109         transl.setEntityResolver(getEntityResolver());
110         transl.setConnection(connection);
111
112         CallableStatement JavaDoc statement = (CallableStatement JavaDoc) transl.createStatement(query
113                 .getLoggingLevel());
114
115         try {
116             // stored procedure may contain a mixture of update counts and result sets,
117
// and out parameters. Read out parameters first, then
118
// iterate until we exhaust all results
119
statement.execute();
120
121             // read out parameters
122
readProcedureOutParameters(statement, observer);
123
124             // read the rest of the query
125
while (true) {
126                 if (statement.getMoreResults()) {
127                     ResultSet JavaDoc rs = statement.getResultSet();
128
129                     try {
130                         RowDescriptor descriptor = describeResultSet(
131                                 rs,
132                                 processedResultSets++);
133                         readResultSet(rs, descriptor, query, observer);
134                     }
135                     finally {
136                         try {
137                             rs.close();
138                         }
139                         catch (SQLException JavaDoc ex) {
140                         }
141                     }
142                 }
143                 else {
144                     int updateCount = statement.getUpdateCount();
145                     if (updateCount == -1) {
146                         break;
147                     }
148                     QueryLogger.logUpdateCount(query.getLoggingLevel(), updateCount);
149                     observer.nextCount(query, updateCount);
150                 }
151             }
152         }
153         finally {
154             try {
155                 statement.close();
156             }
157             catch (SQLException JavaDoc ex) {
158
159             }
160         }
161     }
162
163     /**
164      * Creates a RowDescriptor for result set.
165      *
166      * @param resultSet JDBC ResultSet
167      * @param setIndex a zero-based index of the ResultSet in the query results.
168      */

169     protected RowDescriptor describeResultSet(ResultSet JavaDoc resultSet, int setIndex) {
170         if (setIndex < 0) {
171             throw new IllegalArgumentException JavaDoc(
172                     "Expected a non-negative result set index. Got: " + setIndex);
173         }
174
175         List JavaDoc descriptors = query.getResultDescriptors();
176
177         if (descriptors.isEmpty()) {
178             // failover to default JDBC result descriptor
179
return new RowDescriptor(resultSet, getAdapter().getExtendedTypes());
180         }
181
182         // if one result is described, all of them must be present...
183
if (setIndex >= descriptors.size() || descriptors.get(setIndex) == null) {
184             throw new CayenneRuntimeException("No descriptor for result set at index '"
185                     + setIndex
186                     + "' configured.");
187         }
188
189         ColumnDescriptor[] columns = (ColumnDescriptor[]) descriptors.get(setIndex);
190         return new RowDescriptor(columns, getAdapter().getExtendedTypes());
191     }
192
193     /**
194      * Returns stored procedure for an internal query.
195      */

196     protected Procedure getProcedure() {
197         return getEntityResolver().lookupProcedure(query);
198     }
199
200     /**
201      * Helper method that reads OUT parameters of a CallableStatement.
202      */

203     protected void readProcedureOutParameters(
204             CallableStatement JavaDoc statement,
205             OperationObserver delegate) throws SQLException JavaDoc, Exception JavaDoc {
206
207         long t1 = System.currentTimeMillis();
208
209         // build result row...
210
Map JavaDoc result = null;
211         List JavaDoc parameters = getProcedure().getCallParameters();
212         for (int i = 0; i < parameters.size(); i++) {
213             ProcedureParameter parameter = (ProcedureParameter) parameters.get(i);
214
215             if (!parameter.isOutParam()) {
216                 continue;
217             }
218
219             if (result == null) {
220                 result = new HashMap JavaDoc();
221             }
222
223             ColumnDescriptor descriptor = new ColumnDescriptor(parameter);
224             ExtendedType type = getAdapter().getExtendedTypes().getRegisteredType(
225                     descriptor.getJavaClass());
226             Object JavaDoc val = type.materializeObject(statement, i + 1, descriptor
227                     .getJdbcType());
228
229             result.put(descriptor.getLabel(), val);
230         }
231
232         if (result != null && !result.isEmpty()) {
233             // treat out parameters as a separate data row set
234
QueryLogger.logSelectCount(query.getLoggingLevel(), 1, System
235                     .currentTimeMillis()
236                     - t1);
237             delegate.nextDataRows(query, Collections.singletonList(result));
238         }
239     }
240 }
Popular Tags