KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > client > net > NetConnection40


1 /*
2  
3    Derby - Class org.apache.derby.client.net.NetConnection40
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.derby.client.net;
23
24 import java.sql.Array JavaDoc;
25 import org.apache.derby.client.am.SQLExceptionFactory;
26 import org.apache.derby.client.am.SqlException;
27 import java.sql.Blob JavaDoc;
28 import java.sql.Clob JavaDoc;
29 import java.sql.Connection JavaDoc;
30 import java.sql.NClob JavaDoc;
31 import java.sql.PreparedStatement JavaDoc;
32 import java.sql.ResultSet JavaDoc;
33 import java.sql.SQLClientInfoException JavaDoc;
34 import java.sql.SQLException JavaDoc;
35 import java.sql.SQLXML JavaDoc;
36 import java.sql.Struct JavaDoc;
37 import java.util.HashMap JavaDoc;
38 import java.util.Map JavaDoc;
39 import java.util.Properties JavaDoc;
40 import java.util.Enumeration JavaDoc;
41 import org.apache.derby.client.ClientPooledConnection;
42 import org.apache.derby.client.am.ClientMessageId;
43 import org.apache.derby.client.am.FailedProperties40;
44 import org.apache.derby.shared.common.reference.SQLState;
45
46 public class NetConnection40 extends org.apache.derby.client.net.NetConnection {
47     /**
48      * Prepared statement that is used each time isValid() is called on this
49      * connection. The statement is created the first time isValid is called
50      * and closed when the connection is closed (by the close call).
51      */

52     private PreparedStatement JavaDoc isValidStmt = null;
53
54     /*
55      *-------------------------------------------------------
56      * JDBC 4.0
57      *-------------------------------------------------------
58     */

59
60     public NetConnection40(NetLogWriter netLogWriter,
61                          String JavaDoc databaseName,
62                          java.util.Properties JavaDoc properties) throws SqlException {
63     super(netLogWriter,databaseName,properties);
64     }
65     public NetConnection40(NetLogWriter netLogWriter,
66                          org.apache.derby.jdbc.ClientBaseDataSource dataSource,
67                          String JavaDoc user,
68                          String JavaDoc password) throws SqlException {
69     super(netLogWriter,dataSource,user,password);
70     }
71      public NetConnection40(NetLogWriter netLogWriter,
72                          int driverManagerLoginTimeout,
73                          String JavaDoc serverName,
74                          int portNumber,
75                          String JavaDoc databaseName,
76                          java.util.Properties JavaDoc properties) throws SqlException{
77     super(netLogWriter,driverManagerLoginTimeout,serverName,portNumber,databaseName,properties);
78      }
79      public NetConnection40(NetLogWriter netLogWriter,
80                          String JavaDoc user,
81                          String JavaDoc password,
82                          org.apache.derby.jdbc.ClientBaseDataSource dataSource,
83                          int rmId,
84                          boolean isXAConn) throws SqlException{
85     super(netLogWriter,user,password,dataSource,rmId,isXAConn);
86     }
87     public NetConnection40(NetLogWriter netLogWriter,
88                          String JavaDoc ipaddr,
89                          int portNumber,
90                          org.apache.derby.jdbc.ClientBaseDataSource dataSource,
91                          boolean isXAConn) throws SqlException{
92         super(netLogWriter,ipaddr,portNumber,dataSource,isXAConn);
93     }
94     
95     
96     /**
97      * The constructor for the NetConnection40 class which contains
98      * implementations of JDBC 4.0 specific methods in the java.sql.Connection
99      * interface. This constructor is called from the ClientPooledConnection object
100      * to enable the NetConnection to pass <code>this</code> on to the associated
101      * prepared statement object thus enabling the prepared statement object
102      * to inturn raise the statement events to the ClientPooledConnection object.
103      *
104      * @param netLogWriter NetLogWriter object associated with this connection.
105      * @param user user id for this connection.
106      * @param password password for this connection.
107      * @param dataSource The DataSource object passed from the PooledConnection
108      * object from which this constructor was called.
109      * @param rmId The Resource manager ID for XA Connections
110      * @param isXAConn true if this is a XA connection.
111      * @param cpc The ClientPooledConnection object from which this
112      * NetConnection constructor was called. This is used
113      * to pass StatementEvents back to the pooledConnection
114      * object.
115      * @throws SqlException
116      */

117     
118     public NetConnection40(NetLogWriter netLogWriter,
119                          String JavaDoc user,
120                          String JavaDoc password,
121                          org.apache.derby.jdbc.ClientBaseDataSource dataSource,
122                          int rmId,
123                          boolean isXAConn,
124                          ClientPooledConnection cpc) throws SqlException{
125     super(netLogWriter,user,password,dataSource,rmId,isXAConn,cpc);
126     }
127     
128
129     
130     public Array JavaDoc createArrayOf(String JavaDoc typeName, Object JavaDoc[] elements)
131         throws SQLException JavaDoc {
132         throw SQLExceptionFactory.notImplemented ("createArrayOf(String,Object[])");
133     }
134
135     /**
136      * Constructs an object that implements the Clob interface. The object
137      * returned initially contains no data.
138      * @return An object that implements the Clob interface
139      * @throws SQLException if an object that implements the
140      * Clob interface can not be constructed.
141      *
142      */

143     
144     public Clob JavaDoc createClob() throws SQLException JavaDoc {
145         try {
146             checkForClosedConnection();
147         } catch (SqlException se) {
148             throw se.getSQLException();
149         }
150         org.apache.derby.client.am.Clob clob = new org.apache.derby.client.am.Clob(this.agent_,"");
151         return clob;
152     }
153
154     /**
155      * Constructs an object that implements the Clob interface. The object
156      * returned initially contains no data.
157      * @return An object that implements the Clob interface
158      * @throws SQLException if an object that implements the
159      * Clob interface can not be constructed.
160      *
161      */

162     
163     public Blob JavaDoc createBlob() throws SQLException JavaDoc {
164         try {
165             checkForClosedConnection();
166         } catch (SqlException se) {
167             throw se.getSQLException();
168         }
169         org.apache.derby.client.am.Blob blob = new org.apache.derby.client.am.Blob(new byte[0],this.agent_, 0);
170         return blob;
171     }
172     
173     public NClob JavaDoc createNClob() throws SQLException JavaDoc {
174         throw SQLExceptionFactory.notImplemented ("createNClob ()");
175     }
176
177     public SQLXML JavaDoc createSQLXML() throws SQLException JavaDoc {
178         throw SQLExceptionFactory.notImplemented ("createSQLXML ()");
179     }
180
181     public Struct JavaDoc createStruct(String JavaDoc typeName, Object JavaDoc[] attributes)
182         throws SQLException JavaDoc {
183         throw SQLExceptionFactory.notImplemented ("createStruct(String,Object[])");
184     }
185
186     /**
187      * Checks if the connection has not been closed and is still valid.
188      * The validity is checked by running a simple query against the
189      * database.
190      *
191      * The timeout specified by the caller is implemented as follows:
192      * On the server: uses the queryTimeout functionality to make the
193      * query time out on the server in case the server has problems or
194      * is highly loaded.
195      * On the client: uses a timeout on the socket to make sure that
196      * the client is not blocked forever in the cases where the server
197      * is "hanging" or not sending the reply.
198      *
199      * @param timeout The time in seconds to wait for the database
200      * operation used to validate the connection to complete. If the
201      * timeout period expires before the operation completes, this
202      * method returns false. A value of 0 indicates a timeout is not
203      * applied to the database operation.
204      * @return true if the connection is valid, false otherwise
205      * @exception SQLException if the parameter value is illegal or if a
206      * database error has occured
207      */

208     public boolean isValid(int timeout) throws SQLException JavaDoc {
209         // Validate that the timeout has a legal value
210
if (timeout < 0) {
211             throw new SqlException(agent_.logWriter_,
212                                new ClientMessageId(SQLState.INVALID_API_PARAMETER),
213                                new Integer JavaDoc(timeout), "timeout",
214                                "java.sql.Connection.isValid" ).getSQLException();
215         }
216
217         // Check if the connection is closed
218
if (isClosed()) {
219             return false;
220         }
221
222         // Do a simple query against the database
223
synchronized(this) {
224             try {
225                 // Save the current network timeout value
226
int oldTimeout = netAgent_.getTimeout();
227
228                 // Set the required timeout value on the network connection
229
netAgent_.setTimeout(timeout);
230
231                 // If this is the first time this method is called on this
232
// connection we prepare the query
233
if (isValidStmt == null) {
234                     isValidStmt = prepareStatement("VALUES (1)");
235                 }
236
237                 // Set the query timeout
238
isValidStmt.setQueryTimeout(timeout);
239
240                 // Run the query against the database
241
ResultSet JavaDoc rs = isValidStmt.executeQuery();
242                 rs.close();
243
244                 // Restore the previous timeout value
245
netAgent_.setTimeout(oldTimeout);
246             } catch(SQLException JavaDoc e) {
247                 // If an SQL exception is thrown the connection is not valid,
248
// we ignore the exception and return false.
249
return false;
250             }
251      }
252
253         return true; // The connection is valid
254
}
255
256     /**
257      * Close the connection and release its resources.
258      * @exception SQLException if a database-access error occurs.
259      */

260     synchronized public void close() throws SQLException JavaDoc {
261         // Release resources owned by the prepared statement used by isValid
262
if (isValidStmt != null) {
263             isValidStmt.close();
264             isValidStmt = null;
265         }
266         super.close();
267     }
268
269     /**
270      * <code>setClientInfo</code> will always throw a
271      * <code>SQLClientInfoException</code> since Derby does not support
272      * any properties.
273      *
274      * @param name a property key <code>String</code>
275      * @param value a property value <code>String</code>
276      * @exception SQLException always.
277      */

278     public void setClientInfo(String JavaDoc name, String JavaDoc value)
279     throws SQLClientInfoException JavaDoc{
280         Properties JavaDoc p = FailedProperties40.makeProperties(name,value);
281     try { checkForClosedConnection(); }
282     catch (SqlException se) {
283             throw new SQLClientInfoException JavaDoc
284                 (se.getMessage(), se.getSQLState(),
285                  new FailedProperties40(p).getProperties());
286         }
287
288         if (name == null && value == null) {
289             return;
290         }
291         setClientInfo(p);
292     }
293
294     /**
295      * <code>setClientInfo</code> will throw a
296      * <code>SQLClientInfoException</code> uless the <code>properties</code>
297      * paramenter is empty, since Derby does not support any
298      * properties. All the property keys in the
299      * <code>properties</code> parameter are added to failedProperties
300      * of the exception thrown, with REASON_UNKNOWN_PROPERTY as the
301      * value.
302      *
303      * @param properties a <code>Properties</code> object with the
304      * properties to set.
305      * @exception SQLClientInfoException unless the properties
306      * parameter is null or empty.
307      */

308     public void setClientInfo(Properties JavaDoc properties)
309     throws SQLClientInfoException JavaDoc {
310     FailedProperties40 fp = new FailedProperties40(properties);
311     try { checkForClosedConnection(); }
312     catch (SqlException se) {
313         throw new SQLClientInfoException JavaDoc(se.getMessage(), se.getSQLState(),
314                       fp.getProperties());
315     }
316     
317     if (properties == null || properties.isEmpty()) {
318             return;
319         }
320
321     SqlException se =
322         new SqlException(agent_.logWriter_,
323                  new ClientMessageId
324                  (SQLState.PROPERTY_UNSUPPORTED_CHANGE),
325                  fp.getFirstKey(), fp.getFirstValue());
326         throw new SQLClientInfoException JavaDoc(se.getMessage(),
327                                          se.getSQLState(), fp.getProperties());
328     }
329
330     /**
331      * <code>getClientInfo</code> always returns a
332      * <code>null String</code> since Derby doesn't support
333      * ClientInfoProperties.
334      *
335      * @param name a <code>String</code> value
336      * @return a <code>null String</code> value
337      * @exception SQLException if the connection is closed.
338      */

339     public String JavaDoc getClientInfo(String JavaDoc name)
340     throws SQLException JavaDoc{
341     try {
342         checkForClosedConnection();
343         return null;
344     }
345     catch (SqlException se) { throw se.getSQLException(); }
346     }
347     
348     /**
349      * <code>getClientInfo</code> always returns an empty
350      * <code>Properties</code> object since Derby doesn't support
351      * ClientInfoProperties.
352      *
353      * @return an empty <code>Properties</code> object.
354      * @exception SQLException if the connection is closed.
355      */

356     public Properties JavaDoc getClientInfo()
357     throws SQLException JavaDoc{
358     try {
359         checkForClosedConnection();
360         return new Properties JavaDoc();
361     }
362     catch (SqlException se) { throw se.getSQLException(); }
363     }
364
365     
366     /**
367      * Returns the type map for this connection.
368      *
369      * @return type map for this connection
370      * @exception SQLException if a database access error occurs
371      */

372     public final Map JavaDoc<String JavaDoc, Class JavaDoc<?>> getTypeMap() throws SQLException JavaDoc {
373         // This method is already implemented with a non-generic
374
// signature in am/Connection. We could just use that method
375
// directly, but then we get a compiler warning (unchecked
376
// cast/conversion). Copy the map to avoid the compiler
377
// warning.
378
Map JavaDoc typeMap = super.getTypeMap();
379         if (typeMap == null) return null;
380         Map JavaDoc<String JavaDoc, Class JavaDoc<?>> genericTypeMap = new HashMap JavaDoc<String JavaDoc, Class JavaDoc<?>>();
381         for (Object JavaDoc key : typeMap.keySet()) {
382             genericTypeMap.put((String JavaDoc) key, (Class JavaDoc) typeMap.get(key));
383         }
384         return genericTypeMap;
385     }
386
387     /**
388      * Returns false unless <code>interfaces</code> is implemented
389      *
390      * @param interfaces a Class defining an interface.
391      * @return true if this implements the interface or
392      * directly or indirectly wraps an object
393      * that does.
394      * @throws java.sql.SQLException if an error occurs while determining
395      * whether this is a wrapper for an object
396      * with the given interface.
397      */

398     public boolean isWrapperFor(Class JavaDoc<?> interfaces) throws SQLException JavaDoc {
399         try {
400             checkForClosedConnection();
401         } catch (SqlException se) {
402             throw se.getSQLException();
403         }
404         return interfaces.isInstance(this);
405     }
406     
407     /**
408      * Returns <code>this</code> if this class implements the interface
409      *
410      * @param interfaces a Class defining an interface
411      * @return an object that implements the interface
412      * @throws java.sql.SQLException if no object if found that implements the
413      * interface
414      */

415     public <T> T unwrap(java.lang.Class JavaDoc<T> interfaces)
416                                    throws SQLException JavaDoc {
417         try {
418             checkForClosedConnection();
419             return interfaces.cast(this);
420         } catch (ClassCastException JavaDoc cce) {
421             throw new SqlException(null,
422                 new ClientMessageId(SQLState.UNABLE_TO_UNWRAP),
423                 interfaces).getSQLException();
424         } catch (SqlException se) {
425             throw se.getSQLException();
426         }
427     }
428     
429 }
430
Popular Tags