KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derbyTesting > functionTests > tests > jdbc4 > TestResultSetMethods


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

21
22 package org.apache.derbyTesting.functionTests.tests.jdbc4;
23
24 import org.apache.derby.impl.jdbc.Util;
25
26 import java.io.Reader JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.sql.Connection JavaDoc;
29 import java.sql.DriverManager JavaDoc;
30 import java.sql.PreparedStatement JavaDoc;
31 import java.sql.CallableStatement JavaDoc;
32 import java.sql.ResultSet JavaDoc;
33 import java.sql.SQLException JavaDoc;
34 import java.sql.Statement JavaDoc;
35 import org.apache.derby.shared.common.reference.SQLState;
36 import java.lang.reflect.InvocationTargetException JavaDoc;
37 import java.lang.reflect.Method JavaDoc;
38 import java.util.HashMap JavaDoc;
39 import org.apache.derby.tools.ij;
40 import org.apache.derbyTesting.functionTests.util.SQLStateConstants;
41
42 /**
43  * This class is used to test the implementations of the JDBC 4.0 methods
44  * in the ResultSet interface
45  */

46 public class TestResultSetMethods {
47     
48     Connection JavaDoc conn=null;
49     PreparedStatement JavaDoc ps=null;
50     ResultSet JavaDoc rs=null;
51     
52     /**
53      * Checks that a <code>boolean</code> value is
54      * <code>true</code>. Throws an exception if it is false.
55      *
56      * @param expr boolean expected to be true
57      * @param msg message when assertion fails
58      * @exception RuntimeException if <code>expr</code> is false
59      */

60     private static void assert_(boolean expr, String JavaDoc msg) {
61         if (!expr) {
62             throw new RuntimeException JavaDoc("Assertion failed: " + msg);
63         }
64     }
65     
66     /**
67      * Tests that <code>ResultSet.getHoldability()</code> has the
68      * correct behaviour.
69      */

70     void t_getHoldability() {
71         Boolean JavaDoc savedAutoCommit = null;
72         try {
73             savedAutoCommit = conn.getAutoCommit();
74             conn.setAutoCommit(false);
75
76             // test default holdability
77
Statement JavaDoc stmt = conn.createStatement();
78             ResultSet JavaDoc rs = stmt.executeQuery("values(1)");
79             assert_(rs.getHoldability() == ResultSet.HOLD_CURSORS_OVER_COMMIT,
80                     "default holdability is HOLD_CURSORS_OVER_COMMIT");
81             rs.close();
82             try {
83                 rs.getHoldability();
84                 assert_(false, "getHoldability() should fail when closed");
85             } catch (SQLException JavaDoc sqle) {
86                 String JavaDoc sqlState = sqle.getSQLState();
87                 // client driver throws exception with SQL state null
88
// when result set is closed
89
if (sqlState != null &&
90                     !sqlState.equals("XCL16")) {
91                     throw sqle;
92                 }
93             }
94
95             // test explicitly set holdability
96
final int[] holdabilities = {
97                 ResultSet.HOLD_CURSORS_OVER_COMMIT,
98                 ResultSet.CLOSE_CURSORS_AT_COMMIT,
99             };
100             for (int h : holdabilities) {
101                 Statement JavaDoc s =
102                     conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
103                                          ResultSet.CONCUR_READ_ONLY, h);
104                 rs = s.executeQuery("values(1)");
105                 assert_(rs.getHoldability() == h,
106                         "holdability " + holdabilityString(h));
107                 rs.close();
108                 s.close();
109             }
110
111             // test holdability of result set returned from a stored
112
// procedure (DERBY-1101)
113
stmt.execute("create procedure getresultsetwithhold(in hold int) " +
114                          "parameter style java language java external name " +
115                          "'org.apache.derbyTesting.functionTests.tests." +
116                          "jdbc4.TestResultSetMethods." +
117                          "getResultSetWithHoldability' " +
118                          "dynamic result sets 1 reads sql data");
119             for (int statementHoldability : holdabilities) {
120                 for (int procHoldability : holdabilities) {
121                     CallableStatement JavaDoc cs =
122                         conn.prepareCall("call getresultsetwithhold(?)",
123                                          ResultSet.TYPE_FORWARD_ONLY,
124                                          ResultSet.CONCUR_READ_ONLY,
125                                          statementHoldability);
126                     cs.setInt(1, procHoldability);
127                     cs.execute();
128                     rs = cs.getResultSet();
129                     int holdability = rs.getHoldability();
130                     assert_(holdability == procHoldability,
131                             "holdability of ResultSet from stored proc: " +
132                             holdabilityString(holdability));
133                     conn.commit();
134                     boolean holdable;
135                     try {
136                         rs.next();
137                         holdable = true;
138                     } catch (SQLException JavaDoc sqle) {
139                         String JavaDoc sqlstate = sqle.getSQLState();
140                         // SQL state for closed result set is XCL16,
141
// but it is null in the client driver
142
if (sqlstate == null || sqlstate.equals("XCL16")) {
143                             holdable = false;
144                         } else {
145                             throw sqle;
146                         }
147                     }
148                     if (holdable) {
149                         assert_(holdability ==
150                                 ResultSet.HOLD_CURSORS_OVER_COMMIT,
151                                 "non-holdable result set not closed on commit");
152                     } else {
153                         assert_(holdability ==
154                                 ResultSet.CLOSE_CURSORS_AT_COMMIT,
155                                 "holdable result set closed on commit");
156                     }
157                     rs.close();
158                     cs.close();
159                 }
160             }
161             stmt.execute("drop procedure getresultsetwithhold");
162             stmt.close();
163             conn.commit();
164         } catch(Exception JavaDoc e) {
165             System.out.println("Unexpected exception caught " + e);
166             e.printStackTrace(System.out);
167         } finally {
168             if (savedAutoCommit != null) {
169                 try {
170                     conn.setAutoCommit(savedAutoCommit);
171                 } catch (SQLException JavaDoc sqle) {
172                     sqle.printStackTrace(System.out);
173                 }
174             }
175         }
176     }
177
178     /**
179      * Convert holdability from an integer to a readable string.
180      *
181      * @param holdability an <code>int</code> value representing a holdability
182      * @return a <code>String</code> value representing the same holdability
183      */

184     private static String JavaDoc holdabilityString(int holdability) {
185         switch (holdability) {
186         case ResultSet.HOLD_CURSORS_OVER_COMMIT:
187             return "HOLD_CURSORS_OVER_COMMIT";
188         case ResultSet.CLOSE_CURSORS_AT_COMMIT:
189             return "CLOSE_CURSORS_AT_COMMIT";
190         default:
191             return "UNKNOWN HOLDABILITY";
192         }
193     }
194     
195     /**
196      * Tests that <code>ResultSet.isClosed()</code> returns the
197      * correct value in different situations.
198      */

199     void t_isClosed(){
200         try {
201             Statement JavaDoc stmt = conn.createStatement();
202
203             // simple open/read/close test
204
ResultSet JavaDoc rs = stmt.executeQuery("values(1)");
205             assert_(!rs.isClosed(), "rs should be open");
206             while (rs.next());
207             assert_(!rs.isClosed(), "rs should be open");
208             rs.close();
209             assert_(rs.isClosed(), "rs should be closed");
210
211             // execute and re-execute statement
212
rs = stmt.executeQuery("values(1)");
213             assert_(!rs.isClosed(), "rs should be open");
214             ResultSet JavaDoc rs2 = stmt.executeQuery("values(1)");
215             assert_(rs.isClosed(), "rs should be closed");
216             assert_(!rs2.isClosed(), "rs2 should be open");
217
218             // re-execute another statement on the same connection
219
Statement JavaDoc stmt2 = conn.createStatement();
220             rs = stmt2.executeQuery("values(1)");
221             assert_(!rs2.isClosed(), "rs2 should be open");
222             assert_(!rs.isClosed(), "rs should be open");
223
224             // retrieve multiple result sets
225
stmt.execute("create procedure retrieve_result_sets() " +
226                          "parameter style java language java external name " +
227                          "'org.apache.derbyTesting.functionTests.tests." +
228                          "jdbc4.TestResultSetMethods.threeResultSets' " +
229                          "dynamic result sets 3 reads sql data");
230             stmt.execute("call retrieve_result_sets()");
231             ResultSet JavaDoc[] rss = new ResultSet JavaDoc[3];
232             int count = 0;
233             do {
234                 rss[count] = stmt.getResultSet();
235                 assert_(!rss[count].isClosed(),
236                         "rss[" + count + "] should be open");
237                 if (count > 0) {
238                     assert_(rss[count-1].isClosed(),
239                             "rss[" + (count-1) + "] should be closed");
240                 }
241                 ++count;
242             } while (stmt.getMoreResults());
243             assert_(count == 3, "expected three result sets");
244             stmt.execute("drop procedure retrieve_result_sets");
245
246             // close statement
247
rs = stmt2.executeQuery("values(1)");
248             stmt2.close();
249             assert_(rs.isClosed(), "rs should be closed");
250
251             // close connection
252
Connection JavaDoc conn2 = ij.startJBMS();
253             stmt2 = conn2.createStatement();
254             rs = stmt2.executeQuery("values(1)");
255             conn2.close();
256             assert_(rs.isClosed(), "rs should be closed");
257
258             stmt.close();
259             stmt2.close();
260             
261         } catch(Exception JavaDoc e) {
262             System.out.println("Unexpected exception caught"+e);
263             e.printStackTrace();
264         }
265     }
266     
267     /**
268      * Test that an exception is thrown when methods are called
269      * on a closed result set (DERBY-1060).
270      */

271     private void testExceptionWhenClosed() {
272         try {
273             // create a result set and close it
274
Statement JavaDoc stmt = conn.createStatement();
275             ResultSet JavaDoc rs = stmt.executeQuery("values(1)");
276             rs.close();
277
278             // maps method name to parameter list
279
HashMap JavaDoc<String JavaDoc, Class JavaDoc[]> params = new HashMap JavaDoc<String JavaDoc, Class JavaDoc[]>();
280             // maps method name to argument list
281
HashMap JavaDoc<String JavaDoc, Object JavaDoc[]> args = new HashMap JavaDoc<String JavaDoc, Object JavaDoc[]>();
282
283             // methods with no parameters
284
String JavaDoc[] zeroArgMethods = {
285                 "getWarnings", "clearWarnings", "getStatement",
286                 "getMetaData", "getConcurrency", "getHoldability",
287                 "getRow", "getType", "rowDeleted", "rowInserted",
288                 "rowUpdated", "getFetchDirection", "getFetchSize",
289             };
290             for (String JavaDoc name : zeroArgMethods) {
291                 params.put(name, null);
292                 args.put(name, null);
293             }
294
295             // methods with a single int parameter
296
for (String JavaDoc name : new String JavaDoc[] { "setFetchDirection",
297                                               "setFetchSize" }) {
298                 params.put(name, new Class JavaDoc[] { Integer.TYPE });
299                 args.put(name, new Integer JavaDoc[] { 0 });
300             }
301
302             // invoke the methods
303
for (String JavaDoc name : params.keySet()) {
304                 try {
305                     Method JavaDoc method =
306                         rs.getClass().getMethod(name, params.get(name));
307                     try {
308                         method.invoke(rs, args.get(name));
309                     } catch (InvocationTargetException JavaDoc ite) {
310                         Throwable JavaDoc cause = ite.getCause();
311                         if (cause instanceof SQLException JavaDoc) {
312                             SQLException JavaDoc sqle = (SQLException JavaDoc) cause;
313                             String JavaDoc state = sqle.getSQLState();
314                             // Should get SQL state XCL16 when the
315
// result set is closed, but client driver
316
// sends null.
317
if (state == null ||
318                                 state.equals("XCL16")) {
319                                 continue;
320                             }
321                         }
322                         throw cause;
323                     }
324                     System.out.println("no exception thrown for " + name +
325                                        "() when ResultSet is closed");
326                 } catch (Throwable JavaDoc t) {
327                     System.out.println("Unexpected exception when " +
328                                        "invoking " + name + "():");
329                     t.printStackTrace(System.out);
330                 }
331             }
332             stmt.close();
333         } catch (SQLException JavaDoc e) {
334             System.out.println("Unexpected exception caught:");
335             e.printStackTrace(System.out);
336         }
337     }
338     
339     /**
340      * Tests the wrapper methods isWrapperFor and unwrap. There are two cases
341      * to be tested
342      * Case 1: isWrapperFor returns true and we call unwrap
343      * Case 2: isWrapperFor returns false and we call unwrap
344      *
345      * @param rs The ResultSet object on which the wrapper
346      * methods are tested
347      */

348     void t_wrapper(ResultSet JavaDoc rs) {
349         Class JavaDoc<ResultSet JavaDoc> wrap_class = ResultSet JavaDoc.class;
350         
351         //The if succeeds and we call the unwrap method on the conn object
352
try {
353             if(rs.isWrapperFor(wrap_class)) {
354                 ResultSet JavaDoc rs1 =
355                         (ResultSet JavaDoc)rs.unwrap(wrap_class);
356             }
357             else {
358                 System.out.println("isWrapperFor wrongly returns false");
359             }
360         }
361         catch(SQLException JavaDoc sqle) {
362             sqle.printStackTrace();
363         }
364         
365         //Being Test for Case2
366
//test for the case when isWrapper returns false
367
//using some class that will return false when
368
//passed to isWrapperFor
369
Class JavaDoc<PreparedStatement JavaDoc> wrap_class1 = PreparedStatement JavaDoc.class;
370         
371         try {
372             //returning false is the correct behaviour in this case
373
//Generate a message if it returns true
374
if(rs.isWrapperFor(wrap_class1)) {
375                 System.out.println("isWrapperFor wrongly returns true");
376             }
377             else {
378                 PreparedStatement JavaDoc ps1 = (PreparedStatement JavaDoc)
379                                            rs.unwrap(wrap_class1);
380                 System.out.println("unwrap does not throw the expected " +
381                                    "exception");
382             }
383         }
384         catch (SQLException JavaDoc sqle) {
385             //Calling unwrap in this case throws an
386
//SQLException ensure that this SQLException
387
//has the correct SQLState
388
if(!SQLStateConstants.UNABLE_TO_UNWRAP.equals(sqle.getSQLState())) {
389                 sqle.printStackTrace();
390             }
391         }
392     }
393     void startTestResultSetMethods(Connection JavaDoc conn_in,PreparedStatement JavaDoc ps_in,ResultSet JavaDoc rs_in) {
394         conn = conn_in;
395         ps = ps_in;
396         rs = rs_in;
397         
398         t_getHoldability();
399         t_isClosed();
400         
401         testExceptionWhenClosed();
402     }
403     
404     /**
405      * Method that is invoked by <code>t_isClosed()</code> (as a
406      * stored procedure) to retrieve three result sets.
407      *
408      * @param rs1 first result set
409      * @param rs2 second result set
410      * @param rs3 third result set
411      * @exception SQLException if a database error occurs
412      */

413     public static void threeResultSets(ResultSet JavaDoc[] rs1,
414                                        ResultSet JavaDoc[] rs2,
415                                        ResultSet JavaDoc[] rs3)
416         throws SQLException JavaDoc
417     {
418         Connection JavaDoc c = DriverManager.getConnection("jdbc:default:connection");
419         Statement JavaDoc stmt1 = c.createStatement();
420         rs1[0] = stmt1.executeQuery("values(1)");
421         Statement JavaDoc stmt2 = c.createStatement();
422         rs2[0] = stmt2.executeQuery("values(1)");
423         Statement JavaDoc stmt3 = c.createStatement();
424         rs3[0] = stmt3.executeQuery("values(1)");
425         c.close();
426     }
427
428     /**
429      * Method invoked by <code>t_getHoldability()</code> (as a stored
430      * procedure) to retrieve a result set with a given holdability.
431      *
432      * @param holdability requested holdability
433      * @param rs result set returned from stored procedure
434      * @exception SQLException if a database error occurs
435      */

436     public static void getResultSetWithHoldability(int holdability,
437                                                    ResultSet JavaDoc[] rs)
438         throws SQLException JavaDoc
439     {
440         Connection JavaDoc c = DriverManager.getConnection("jdbc:default:connection");
441         Statement JavaDoc s = c.createStatement(ResultSet.TYPE_FORWARD_ONLY,
442                                         ResultSet.CONCUR_READ_ONLY,
443                                         holdability);
444         rs[0] = s.executeQuery("values (1), (2), (3)");
445         c.close();
446     }
447     
448     /**
449      * <p>
450      * Return true if we're running under the embedded client.
451      * </p>
452      * @return a boolean value signifying whether we are running under the
453      * embedded framework
454      */

455     private static boolean usingEmbeddedClient()
456     {
457             return "embedded".equals(System.getProperty("framework" ) );
458     }
459     
460     public static void main(String JavaDoc args[]) {
461         try {
462             // use the ij utility to read the property file and
463
// make the initial connection.
464
ij.getPropertyArg(args);
465         
466             Connection JavaDoc conn_main = ij.startJBMS();
467
468             PreparedStatement JavaDoc ps_main=null;
469             ResultSet JavaDoc rs_main=null;
470         
471             ps_main = conn_main.prepareStatement("select count(*) from sys.systables");
472             rs_main = ps_main.executeQuery();
473         
474             TestResultSetMethods trsm = new TestResultSetMethods();
475                         
476             trsm.startTestResultSetMethods(conn_main,ps_main,rs_main);
477                         trsm.t_wrapper(rs_main);
478         } catch(Exception JavaDoc e) {
479             System.out.println(""+e);
480             e.printStackTrace();
481         }
482         
483         
484     }
485 }
486
Popular Tags