KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2
3    Derby - Class org.apache.derby.client.net.NetConnection
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 package org.apache.derby.client.net;
22
23 import java.sql.SQLException JavaDoc;
24 import org.apache.derby.client.am.CallableStatement;
25 import org.apache.derby.client.am.DatabaseMetaData;
26 import org.apache.derby.client.am.DisconnectException;
27 import org.apache.derby.client.am.EncryptionManager;
28 import org.apache.derby.client.am.PreparedStatement;
29 import org.apache.derby.client.am.ProductLevel;
30 import org.apache.derby.client.am.SqlException;
31 import org.apache.derby.client.am.ClientMessageId;
32 import org.apache.derby.shared.common.reference.MessageId;
33 import org.apache.derby.shared.common.i18n.MessageUtil;
34 import org.apache.derby.client.am.Statement;
35 import org.apache.derby.client.am.Utils;
36 import org.apache.derby.jdbc.ClientBaseDataSource;
37 import org.apache.derby.jdbc.ClientDataSource;
38 import org.apache.derby.jdbc.ClientDriver;
39 import org.apache.derby.client.ClientPooledConnection;
40
41 import org.apache.derby.shared.common.reference.SQLState;
42
43 public class NetConnection extends org.apache.derby.client.am.Connection {
44     
45     // Use this to get internationalized strings...
46
protected static MessageUtil msgutil = SqlException.getMessageUtil();
47
48     protected NetAgent netAgent_;
49     //contains a reference to the PooledConnection from which this created
50
//It then passes this reference to the PreparedStatement created from it
51
//The PreparedStatement then uses this to pass the close and the error
52
//occurred conditions back to the PooledConnection which can then throw the
53
//appropriate events.
54
protected ClientPooledConnection pooledConnection_ = null;
55
56
57     // For XA Transaction
58
protected int pendingEndXACallinfoOffset_ = -1;
59
60
61     // byte[] to save the connect flows for connection reset
62
protected byte[] cachedConnectBytes_ = null;
63     protected boolean wroteConnectFromCache_ = false;
64     //-----------------------------state------------------------------------------
65

66     // these variables store the manager levels for the connection.
67
// they are initialized to the highest value which this driver supports
68
// at the current time. theses intial values should be increased when
69
// new manager level support is added to this driver. these initial values
70
// are sent to the server in the excsat command. the server will return a
71
// set of values and these will be parsed out by parseExcsatrd and parseMgrlvlls.
72
// during this parsing, these instance variable values will be reset to the negotiated
73
// levels for the connection. these values may be less than the
74
// values origionally set here at constructor time. it is these new values
75
// (following the parse) which are the levels for the connection. after
76
// a successful excsat command, these values can be checked to see
77
// what protocol is supported by this particular connection.
78
// if support for a new manager class is added, the buildExcsat and parseMgrlvlls
79
// methods will need to be changed to accomodate sending and receiving the new class.
80
protected int targetAgent_ = NetConfiguration.MGRLVL_7; //01292003jev monitoring
81
protected int targetCmntcpip_ = NetConfiguration.MGRLVL_5;
82     protected int targetRdb_ = NetConfiguration.MGRLVL_7;
83     public int targetSecmgr_ = NetConfiguration.MGRLVL_7;
84     protected int targetCmnappc_ = NetConfiguration.MGRLVL_NA; //NA since currently not used by net
85
protected int targetXamgr_ = NetConfiguration.MGRLVL_7;
86     protected int targetSyncptmgr_ = NetConfiguration.MGRLVL_NA;
87     protected int targetRsyncmgr_ = NetConfiguration.MGRLVL_NA;
88
89
90     // this is the external name of the target server.
91
// it is set by the parseExcsatrd method but not really used for much at this
92
// time. one possible use is for logging purposes and in the future it
93
// may be placed in the trace.
94
String JavaDoc targetExtnam_;
95     String JavaDoc extnam_;
96
97     // Server Class Name of the target server returned in excsatrd.
98
// Again this is something which the driver is not currently using
99
// to make any decions. Right now it is just stored for future logging.
100
// It does contain some useful information however and possibly
101
// the database meta data object will make use of this
102
// for example, the product id (prdid) would give this driver an idea of
103
// what type of sevrer it is connected to.
104
public String JavaDoc targetSrvclsnm_;
105
106     // Server Name of the target server returned in excsatrd.
107
// Again this is something which we don't currently use but
108
// keep it in case we want to log it in some problem determination
109
// trace/dump later.
110
protected String JavaDoc targetSrvnam_;
111
112     // Server Product Release Level of the target server returned in excsatrd.
113
// specifies the procuct release level of a ddm server.
114
// Again this is something which we don't currently use but
115
// keep it in case we want to log it in some problem determination
116
// trace/dump later.
117
public String JavaDoc targetSrvrlslv_;
118
119     // Keys used for encryption.
120
transient byte[] publicKey_;
121     transient byte[] targetPublicKey_;
122
123     // Seeds used for strong password substitute generation (USRSSBPWD)
124
transient byte[] sourceSeed_; // Client seed
125
transient byte[] targetSeed_; // Server seed
126

127     // Product-Specific Data (prddta) sent to the server in the accrdb command.
128
// The prddta has a specified format. It is saved in case it is needed again
129
// since it takes a little effort to compute. Saving this information is
130
// useful for when the connect flows need to be resent (right now the connect
131
// flow is resent when this driver disconnects and reconnects with
132
// non unicode ccsids. this is done when the server doesn't recoginze the
133
// unicode ccsids).
134
//
135

136     byte[] prddta_;
137
138     // Correlation Token of the source sent to the server in the accrdb.
139
// It is saved like the prddta in case it is needed for a connect reflow.
140
public byte[] crrtkn_;
141
142     // The Secmec used by the target.
143
// It contains the negotiated security mechanism for the connection.
144
// Initially the value of this is 0. It is set only when the server and
145
// the target successfully negotiate a security mechanism.
146
int targetSecmec_;
147
148     // the security mechanism requested by the application
149
protected int securityMechanism_;
150
151     // stored the password for deferred reset only.
152
private transient char[] deferredResetPassword_ = null;
153     
154     //If Network Server gets null connection from the embedded driver,
155
//it sends RDBAFLRM followed by SQLCARD with null SQLException.
156
//Client will parse the SQLCARD and set connectionNull to true if the
157
//SQLCARD is empty. If connectionNull=true, connect method in
158
//ClientDriver will in turn return null connection.
159
private boolean connectionNull = false;
160
161     private void setDeferredResetPassword(String JavaDoc password) {
162         deferredResetPassword_ = (password == null) ? null : flipBits(password.toCharArray());
163     }
164
165     private String JavaDoc getDeferredResetPassword() {
166         if (deferredResetPassword_ == null) {
167             return null;
168         }
169         String JavaDoc password = new String JavaDoc(flipBits(deferredResetPassword_));
170         flipBits(deferredResetPassword_); // re-encrypt password
171
return password;
172     }
173
174     protected byte[] cnntkn_ = null;
175
176     // resource manager Id for XA Connections.
177
private int rmId_ = 0;
178     protected NetXAResource xares_ = null;
179     protected java.util.Hashtable JavaDoc indoubtTransactions_ = null;
180     protected int currXACallInfoOffset_ = 0;
181     private short seqNo_ = 1;
182
183     // Flag to indicate a read only transaction
184
protected boolean readOnlyTransaction_ = true;
185
186     //---------------------constructors/finalizer---------------------------------
187

188     public NetConnection(NetLogWriter netLogWriter,
189                          String JavaDoc databaseName,
190                          java.util.Properties JavaDoc properties) throws SqlException {
191         super(netLogWriter, 0, "", -1, databaseName, properties);
192     }
193
194     public NetConnection(NetLogWriter netLogWriter,
195                          org.apache.derby.jdbc.ClientBaseDataSource dataSource,
196                          String JavaDoc user,
197                          String JavaDoc password) throws SqlException {
198         super(netLogWriter, user, password, dataSource);
199         setDeferredResetPassword(password);
200     }
201
202     // For jdbc 1 connections
203
public NetConnection(NetLogWriter netLogWriter,
204                          int driverManagerLoginTimeout,
205                          String JavaDoc serverName,
206                          int portNumber,
207                          String JavaDoc databaseName,
208                          java.util.Properties JavaDoc properties) throws SqlException {
209         super(netLogWriter, driverManagerLoginTimeout, serverName, portNumber, databaseName, properties);
210         netAgent_ = (NetAgent) super.agent_;
211         if (netAgent_.exceptionOpeningSocket_ != null) {
212             throw netAgent_.exceptionOpeningSocket_;
213         }
214         checkDatabaseName();
215         String JavaDoc password = ClientBaseDataSource.getPassword(properties);
216         securityMechanism_ = ClientBaseDataSource.getSecurityMechanism(properties);
217         flowConnect(password, securityMechanism_);
218         if(!isConnectionNull())
219             completeConnect();
220     }
221
222     // For JDBC 2 Connections
223
public NetConnection(NetLogWriter netLogWriter,
224                          String JavaDoc user,
225                          String JavaDoc password,
226                          org.apache.derby.jdbc.ClientBaseDataSource dataSource,
227                          int rmId,
228                          boolean isXAConn) throws SqlException {
229         super(netLogWriter, user, password, isXAConn, dataSource);
230         netAgent_ = (NetAgent) super.agent_;
231         initialize(user, password, dataSource, rmId, isXAConn);
232     }
233
234     public NetConnection(NetLogWriter netLogWriter,
235                          String JavaDoc ipaddr,
236                          int portNumber,
237                          org.apache.derby.jdbc.ClientBaseDataSource dataSource,
238                          boolean isXAConn) throws SqlException {
239         super(netLogWriter, isXAConn, dataSource);
240         netAgent_ = (NetAgent) super.agent_;
241         if (netAgent_.exceptionOpeningSocket_ != null) {
242             throw netAgent_.exceptionOpeningSocket_;
243         }
244         checkDatabaseName();
245         this.isXAConnection_ = isXAConn;
246         flowSimpleConnect();
247         productID_ = targetSrvrlslv_;
248         super.completeConnect();
249     }
250     
251     // For JDBC 2 Connections
252
/**
253      * This constructor is called from the ClientPooledConnection object
254      * to enable the NetConnection to pass <code>this</code> on to the associated
255      * prepared statement object thus enabling the prepared statement object
256      * to inturn raise the statement events to the ClientPooledConnection object
257      * @param netLogWriter NetLogWriter object associated with this connection
258      * @param user user id for this connection
259      * @param password password for this connection
260      * @param dataSource The DataSource object passed from the PooledConnection
261      * object from which this constructor was called
262      * @param rmId The Resource manager ID for XA Connections
263      * @param isXAConn true if this is a XA connection
264      * @param cpc The ClientPooledConnection object from which this
265      * NetConnection constructor was called. This is used
266      * to pass StatementEvents back to the pooledConnection
267      * object
268      * @throws SqlException
269      */

270     
271     public NetConnection(NetLogWriter netLogWriter,
272                          String JavaDoc user,
273                          String JavaDoc password,
274                          org.apache.derby.jdbc.ClientBaseDataSource dataSource,
275                          int rmId,
276                          boolean isXAConn,
277                          ClientPooledConnection cpc) throws SqlException {
278         super(netLogWriter, user, password, isXAConn, dataSource);
279         netAgent_ = (NetAgent) super.agent_;
280         initialize(user, password, dataSource, rmId, isXAConn);
281         this.pooledConnection_=cpc;
282     }
283
284     private void initialize(String JavaDoc user,
285                             String JavaDoc password,
286                             org.apache.derby.jdbc.ClientBaseDataSource dataSource,
287                             int rmId,
288                             boolean isXAConn) throws SqlException {
289         securityMechanism_ = dataSource.getSecurityMechanism(password);
290
291         setDeferredResetPassword(password);
292         checkDatabaseName();
293         dataSource_ = dataSource;
294         this.rmId_ = rmId;
295         this.isXAConnection_ = isXAConn;
296         flowConnect(password, securityMechanism_);
297         completeConnect();
298
299     }
300
301     // preferably without password in the method signature.
302
// We can probally get rid of flowReconnect method.
303
public void resetNetConnection(org.apache.derby.client.am.LogWriter logWriter,
304                                    String JavaDoc user,
305                                    String JavaDoc password,
306                                    org.apache.derby.jdbc.ClientBaseDataSource ds,
307                                    boolean recomputeFromDataSource) throws SqlException {
308         super.resetConnection(logWriter, user, ds, recomputeFromDataSource);
309         //----------------------------------------------------
310
if (recomputeFromDataSource) {
311             // do not reset managers on a connection reset. this information shouldn't
312
// change and can be used to check secmec support.
313

314             targetExtnam_ = null;
315             targetSrvclsnm_ = null;
316             targetSrvnam_ = null;
317             targetSrvrlslv_ = null;
318             publicKey_ = null;
319             targetPublicKey_ = null;
320             sourceSeed_ = null;
321             targetSeed_ = null;
322             targetSecmec_ = 0;
323             if (ds != null && securityMechanism_ == 0) {
324                 securityMechanism_ = ds.getSecurityMechanism(password);
325             }
326             resetConnectionAtFirstSql_ = false;
327
328         }
329         if (password != null) {
330             deferredResetPassword_ = null;
331         } else {
332             password = getDeferredResetPassword();
333         }
334         // properties prddta_ and crrtkn_ will be initialized by
335
// calls to constructPrddta() and constructCrrtkn()
336
//----------------------------------------------------------
337
boolean isDeferredReset = flowReconnect(password, securityMechanism_);
338         completeReset(isDeferredReset, recomputeFromDataSource);
339     }
340
341
342     protected void reset_(org.apache.derby.client.am.LogWriter logWriter,
343                           String JavaDoc user, String JavaDoc password,
344                           ClientBaseDataSource ds,
345                           boolean recomputeFromDataSource) throws SqlException {
346         checkResetPreconditions(logWriter, user, password, ds);
347         resetNetConnection(logWriter, user, password, ds, recomputeFromDataSource);
348     }
349
350     protected void reset_(org.apache.derby.client.am.LogWriter logWriter,
351                           ClientBaseDataSource ds,
352                           boolean recomputeFromDataSource) throws SqlException {
353         checkResetPreconditions(logWriter, null, null, ds);
354         resetNetConnection(logWriter, ds, recomputeFromDataSource);
355     }
356
357     private void resetNetConnection(org.apache.derby.client.am.LogWriter logWriter,
358                             org.apache.derby.jdbc.ClientBaseDataSource ds,
359                             boolean recomputeFromDataSource) throws SqlException {
360         super.resetConnection(logWriter, null, ds, recomputeFromDataSource);
361         //----------------------------------------------------
362
if (recomputeFromDataSource) {
363             // do not reset managers on a connection reset. this information shouldn't
364
// change and can be used to check secmec support.
365

366             targetExtnam_ = null;
367             targetSrvclsnm_ = null;
368             targetSrvnam_ = null;
369             targetSrvrlslv_ = null;
370             publicKey_ = null;
371             targetPublicKey_ = null;
372             sourceSeed_ = null;
373             targetSeed_ = null;
374             targetSecmec_ = 0;
375             if (ds != null && securityMechanism_ == 0) {
376                 securityMechanism_ = ds.getSecurityMechanism();
377             }
378             resetConnectionAtFirstSql_ = false;
379         }
380         // properties prddta_ and crrtkn_ will be initialized by
381
// calls to constructPrddta() and constructCrrtkn()
382
//----------------------------------------------------------
383
boolean isDeferredReset = flowReconnect(null, securityMechanism_);
384         completeReset(isDeferredReset, recomputeFromDataSource);
385     }
386
387     protected void checkResetPreconditions(org.apache.derby.client.am.LogWriter logWriter,
388                                            String JavaDoc user,
389                                            String JavaDoc password,
390                                            ClientBaseDataSource ds) throws SqlException {
391         if (inUnitOfWork_) {
392             throw new SqlException(logWriter,
393                 new ClientMessageId(SQLState.NET_CONNECTION_RESET_NOT_ALLOWED_IN_UNIT_OF_WORK));
394         }
395     }
396
397     java.util.List JavaDoc getSpecialRegisters() {
398         if (xares_ != null) {
399             return xares_.getSpecialRegisters();
400         } else {
401             return null;
402         }
403     }
404
405     public void addSpecialRegisters(String JavaDoc s) {
406         if (xares_ != null) {
407             xares_.addSpecialRegisters(s);
408         }
409     }
410
411     public void completeConnect() throws SqlException {
412         super.completeConnect();
413     }
414
415     protected void completeReset(boolean isDeferredReset, boolean recomputeFromDataSource) throws SqlException {
416         super.completeReset(isDeferredReset, recomputeFromDataSource);
417     }
418
419     public void flowConnect(String JavaDoc password,
420                             int securityMechanism) throws SqlException {
421         netAgent_ = (NetAgent) super.agent_;
422         constructExtnam();
423         // these calls need to be after newing up the agent
424
// because they require the ccsid manager
425
constructPrddta(); // construct product data
426

427         netAgent_.typdef_ = new Typdef(netAgent_, 1208, NetConfiguration.SYSTEM_ASC, 1200, 1208);
428         netAgent_.targetTypdef_ = new Typdef(netAgent_);
429         netAgent_.originalTargetTypdef_ = netAgent_.targetTypdef_;
430         setDeferredResetPassword(password);
431         try {
432             switch (securityMechanism) {
433             case NetConfiguration.SECMEC_USRIDPWD: // Clear text user id and password
434
checkUserPassword(user_, password);
435                 flowUSRIDPWDconnect(password);
436                 break;
437             case NetConfiguration.SECMEC_USRIDONL: // Clear text user, no password sent to server
438
checkUser(user_);
439                 flowUSRIDONLconnect();
440                 break;
441             case NetConfiguration.SECMEC_USRENCPWD: // Clear text user, encrypted password
442
checkUserPassword(user_, password);
443                 flowUSRENCPWDconnect(password);
444                 break;
445             case NetConfiguration.SECMEC_EUSRIDPWD: // Encrypted user, encrypted password
446
checkUserPassword(user_, password);
447                 flowEUSRIDPWDconnect(password);
448                 break;
449             case NetConfiguration.SECMEC_EUSRIDDTA:
450                 checkUserPassword(user_, password);
451                 flowEUSRIDDTAconnect();
452                 break;
453             case NetConfiguration.SECMEC_EUSRPWDDTA:
454                 checkUserPassword(user_, password);
455                 flowEUSRPWDDTAconnect(password);
456                 break;
457             case NetConfiguration.SECMEC_USRSSBPWD: // Clear text user, strong password substitute
458
checkUserPassword(user_, password);
459                 flowUSRSSBPWDconnect(password);
460                 break;
461
462             default:
463                 throw new SqlException(agent_.logWriter_,
464                     new ClientMessageId(SQLState.SECMECH_NOT_SUPPORTED),
465                     new Integer JavaDoc(securityMechanism));
466             }
467         } catch (java.lang.Throwable JavaDoc e) { // if *anything* goes wrong, make sure the connection is destroyed
468
// always mark the connection closed in case of an error.
469
// This prevents attempts to use this closed connection
470
// to retrieve error message text if an error SQLCA
471
// is returned in one of the connect flows.
472
open_ = false;
473             // logWriter may be closed in agent_.close(),
474
// so SqlException needs to be created before that
475
// but to be thrown after.
476
SqlException exceptionToBeThrown;
477             if (e instanceof SqlException) // rethrow original exception if it's an SqlException
478
{
479                 exceptionToBeThrown = (SqlException) e;
480             } else // any other exceptions will be wrapped by an SqlException first
481
{
482                 exceptionToBeThrown = new SqlException(agent_.logWriter_,
483                     new ClientMessageId(SQLState.JAVA_EXCEPTION),
484                     e.getClass().getName(), e.getMessage(), e);
485             }
486
487             try {
488                 if (agent_ != null) {
489                     agent_.close();
490                 }
491             } catch (SqlException ignoreMe) {
492             }
493
494             throw exceptionToBeThrown;
495         }
496     }
497     
498     protected void flowSimpleConnect() throws SqlException {
499         netAgent_ = (NetAgent) super.agent_;
500         constructExtnam();
501         // these calls need to be after newing up the agent
502
// because they require the ccsid manager
503
constructPrddta(); // construct product data
504

505         netAgent_.typdef_ = new Typdef(netAgent_, 1208, NetConfiguration.SYSTEM_ASC, 1200, 1208);
506         netAgent_.targetTypdef_ = new Typdef(netAgent_);
507         netAgent_.originalTargetTypdef_ = netAgent_.targetTypdef_;
508
509         try {
510             flowServerAttributes();
511         } catch (java.lang.Throwable JavaDoc e) { // if *anything* goes wrong, make sure the connection is destroyed
512
// always mark the connection closed in case of an error.
513
// This prevents attempts to use this closed connection
514
// to retrieve error message text if an error SQLCA
515
// is returned in one of the connect flows.
516
open_ = false;
517             // logWriter may be closed in agent_.close(),
518
// so SqlException needs to be created before that
519
// but to be thrown after.
520
SqlException exceptionToBeThrown;
521             if (e instanceof SqlException) // rethrow original exception if it's an SqlException
522
{
523                 exceptionToBeThrown = (SqlException) e;
524             } else // any other exceptions will be wrapped by an SqlException first
525
{
526                 exceptionToBeThrown = new SqlException(agent_.logWriter_,
527                     new ClientMessageId(SQLState.JAVA_EXCEPTION),
528                     e.getClass().getName(), e.getMessage(), e);
529             }
530
531             try {
532                 if (agent_ != null) {
533                     agent_.close();
534                 }
535             } catch (SqlException ignoreMe) {
536             }
537
538             throw exceptionToBeThrown;
539         }
540     }
541
542     protected boolean flowReconnect(String JavaDoc password, int securityMechanism) throws SqlException {
543         constructExtnam();
544         // these calls need to be after newing up the agent
545
// because they require the ccsid manager
546
constructPrddta(); //modify this to not new up an array
547

548         checkSecmgrForSecmecSupport(securityMechanism);
549         try {
550             switch (securityMechanism) {
551             case NetConfiguration.SECMEC_USRIDPWD: // Clear text user id and password
552
checkUserPassword(user_, password);
553                 resetConnectionAtFirstSql_ = true;
554                 setDeferredResetPassword(password);
555                 return true;
556             case NetConfiguration.SECMEC_USRIDONL: // Clear text user, no password sent to server
557
checkUser(user_);
558                 resetConnectionAtFirstSql_ = true;
559                 return true;
560             case NetConfiguration.SECMEC_USRENCPWD: // Clear text user, encrypted password
561
checkUserPassword(user_, password);
562                 resetConnectionAtFirstSql_ = true;
563                 setDeferredResetPassword(password);
564                 return true;
565             case NetConfiguration.SECMEC_EUSRIDPWD: // Encrypted user, encrypted password
566
checkUserPassword(user_, password);
567                 resetConnectionAtFirstSql_ = true;
568                 setDeferredResetPassword(password);
569                 return true;
570             case NetConfiguration.SECMEC_EUSRIDDTA:
571                 checkUserPassword(user_, password);
572                 resetConnectionAtFirstSql_ = true;
573                 setDeferredResetPassword(password);
574                 return true;
575             case NetConfiguration.SECMEC_EUSRPWDDTA:
576                 checkUserPassword(user_, password);
577                 resetConnectionAtFirstSql_ = true;
578                 setDeferredResetPassword(password);
579                 return true;
580             case NetConfiguration.SECMEC_USRSSBPWD: // Clear text user, strong password substitute
581
checkUserPassword(user_, password);
582                 resetConnectionAtFirstSql_ = true;
583                 setDeferredResetPassword(password);
584                 return true;
585             default:
586                 throw new SqlException(agent_.logWriter_,
587                     new ClientMessageId(SQLState.SECMECH_NOT_SUPPORTED),
588                     new Integer JavaDoc(securityMechanism));
589             }
590         } catch (SqlException sqle) { // this may not be needed because on method up the stack
591
open_ = false; // all reset exceptions are caught and wrapped in disconnect exceptions
592
try {
593                 if (agent_ != null) {
594                     agent_.close();
595                 }
596             } catch (SqlException ignoreMe) {
597             }
598             throw sqle;
599         }
600     }
601
602     protected void finalize() throws java.lang.Throwable JavaDoc {
603         super.finalize();
604     }
605
606     protected byte[] getCnnToken() {
607         return cnntkn_;
608     }
609
610     protected short getSequenceNumber() {
611         return ++seqNo_;
612     }
613
614     //--------------------------------flow methods--------------------------------
615

616     private void flowUSRIDPWDconnect(String JavaDoc password) throws SqlException {
617         flowServerAttributesAndKeyExchange(NetConfiguration.SECMEC_USRIDPWD,
618                 null); // publicKey
619

620         flowSecurityCheckAndAccessRdb(targetSecmec_, //securityMechanism
621
user_,
622                 password,
623                 null, //encryptedUserid
624
null); //encryptedPassword
625
}
626
627
628     private void flowUSRIDONLconnect() throws SqlException {
629         flowServerAttributesAndKeyExchange(NetConfiguration.SECMEC_USRIDONL,
630                 null); //publicKey
631

632         flowSecurityCheckAndAccessRdb(targetSecmec_, //securityMechanism
633
user_,
634                 null, //password
635
null, //encryptedUserid
636
null); //encryptedPassword
637
}
638
639
640     private void flowUSRENCPWDconnect(String JavaDoc password) throws SqlException {
641         flowServerAttributes();
642
643         checkSecmgrForSecmecSupport(NetConfiguration.SECMEC_USRENCPWD);
644         initializePublicKeyForEncryption();
645         flowKeyExchange(NetConfiguration.SECMEC_USRENCPWD, publicKey_);
646
647         flowSecurityCheckAndAccessRdb(targetSecmec_, //securityMechanism
648
user_,
649                 null, //password
650
null, //encryptedUserid
651
encryptedPasswordForUSRENCPWD(password));
652     }
653
654
655     private void flowEUSRIDPWDconnect(String JavaDoc password) throws SqlException {
656         flowServerAttributes();
657
658         checkSecmgrForSecmecSupport(NetConfiguration.SECMEC_EUSRIDPWD);
659         initializePublicKeyForEncryption();
660         flowKeyExchange(NetConfiguration.SECMEC_EUSRIDPWD, publicKey_);
661
662         flowSecurityCheckAndAccessRdb(targetSecmec_, //securityMechanism
663
null, //user
664
null, //password
665
encryptedUseridForEUSRIDPWD(),
666                 encryptedPasswordForEUSRIDPWD(password));
667     }
668
669     private void flowEUSRIDDTAconnect() throws SqlException {
670         flowServerAttributes();
671
672         checkSecmgrForSecmecSupport(NetConfiguration.SECMEC_EUSRIDPWD);
673         initializePublicKeyForEncryption();
674         flowKeyExchange(NetConfiguration.SECMEC_EUSRIDDTA, publicKey_);
675
676
677         flowSecurityCheckAndAccessRdb(targetSecmec_, //securityMechanism
678
null, //user
679
null, //password
680
encryptedUseridForEUSRIDPWD(),
681                 null);//encryptedPasswordForEUSRIDPWD (password),
682
}
683
684     private void flowEUSRPWDDTAconnect(String JavaDoc password) throws SqlException {
685         flowServerAttributes();
686
687         checkSecmgrForSecmecSupport(NetConfiguration.SECMEC_EUSRPWDDTA);
688         initializePublicKeyForEncryption();
689         flowKeyExchange(NetConfiguration.SECMEC_EUSRPWDDTA, publicKey_);
690
691
692         flowSecurityCheckAndAccessRdb(targetSecmec_, //securityMechanism
693
null, //user
694
null, //password
695
encryptedUseridForEUSRIDPWD(),
696                 encryptedPasswordForEUSRIDPWD(password));
697     }
698
699     /**
700      * The User ID and Strong Password Substitute mechanism (USRSSBPWD)
701      * authenticates the user like the user ID and password mechanism, but
702      * the password does not flow. A password substitute is generated instead
703      * using the SHA-1 algorithm, and is sent to the application server.
704      *
705      * The application server generates a password substitute using the same
706      * algorithm and compares it with the application requester's password
707      * substitute. If equal, the user is authenticated.
708      *
709      * The SECTKN parameter is used to flow the client and server encryption
710      * seeds on the ACCSEC and ACCSECRD commands.
711      *
712      * More information in DRDA, V3, Volume 3 standard - PWDSSB (page 650)
713      */

714     private void flowUSRSSBPWDconnect(String JavaDoc password) throws SqlException {
715         flowServerAttributes();
716
717         checkSecmgrForSecmecSupport(NetConfiguration.SECMEC_USRSSBPWD);
718         // Generate a random client seed to send to the target server - in
719
// response we will also get a generated seed from this last one.
720
// Seeds are used on both sides to generate the password substitute.
721
initializeClientSeed();
722
723         flowSeedExchange(NetConfiguration.SECMEC_USRSSBPWD, sourceSeed_);
724
725         flowSecurityCheckAndAccessRdb(targetSecmec_, //securityMechanism
726
user_,
727                 null,
728                 null,
729                 passwordSubstituteForUSRSSBPWD(password)); // PWD Substitute
730
}
731
732     private void flowServerAttributes() throws SqlException {
733         agent_.beginWriteChainOutsideUOW();
734         netAgent_.netConnectionRequest_.writeExchangeServerAttributes(extnam_, //externalName
735
targetAgent_,
736                 netAgent_.targetSqlam_,
737                 targetRdb_,
738                 targetSecmgr_,
739                 targetCmntcpip_,
740                 targetCmnappc_,
741                 targetXamgr_,
742                 targetSyncptmgr_,
743                 targetRsyncmgr_);
744         agent_.flowOutsideUOW();
745         netAgent_.netConnectionReply_.readExchangeServerAttributes(this);
746         agent_.endReadChain();
747     }
748
749     private void flowKeyExchange(int securityMechanism, byte[] publicKey) throws SqlException {
750         agent_.beginWriteChainOutsideUOW();
751         netAgent_.netConnectionRequest_.writeAccessSecurity(securityMechanism,
752                 databaseName_,
753                 publicKey);
754         agent_.flowOutsideUOW();
755         netAgent_.netConnectionReply_.readAccessSecurity(this, securityMechanism);
756         agent_.endReadChain();
757     }
758
759     private void flowSeedExchange(int securityMechanism, byte[] sourceSeed) throws SqlException {
760         agent_.beginWriteChainOutsideUOW();
761         netAgent_.netConnectionRequest_.writeAccessSecurity(securityMechanism,
762                 databaseName_,
763                 sourceSeed);
764         agent_.flowOutsideUOW();
765         netAgent_.netConnectionReply_.readAccessSecurity(this, securityMechanism);
766         agent_.endReadChain();
767     }
768
769     private void flowServerAttributesAndKeyExchange(int securityMechanism,
770                                                     byte[] publicKey) throws SqlException {
771         agent_.beginWriteChainOutsideUOW();
772         writeServerAttributesAndKeyExchange(securityMechanism, publicKey);
773         agent_.flowOutsideUOW();
774         readServerAttributesAndKeyExchange(securityMechanism);
775         agent_.endReadChain();
776     }
777
778     private void flowServerAttributesAndSeedExchange(int securityMechanism,
779                                                      byte[] sourceSeed) throws SqlException {
780         agent_.beginWriteChainOutsideUOW();
781         writeServerAttributesAndSeedExchange(sourceSeed);
782         agent_.flowOutsideUOW();
783         readServerAttributesAndSeedExchange();
784         agent_.endReadChain();
785     }
786
787     private void flowSecurityCheckAndAccessRdb(int securityMechanism,
788                                                String JavaDoc user,
789                                                String JavaDoc password,
790                                                byte[] encryptedUserid,
791                                                byte[] encryptedPassword) throws SqlException {
792         agent_.beginWriteChainOutsideUOW();
793         writeSecurityCheckAndAccessRdb(securityMechanism,
794                 user,
795                 password,
796                 encryptedUserid,
797                 encryptedPassword);
798         agent_.flowOutsideUOW();
799         readSecurityCheckAndAccessRdb();
800         agent_.endReadChain();
801     }
802
803     private void writeAllConnectCommandsChained(int securityMechanism,
804                                                 String JavaDoc user,
805                                                 String JavaDoc password) throws SqlException {
806         writeServerAttributesAndKeyExchange(securityMechanism,
807                 null); // publicKey
808
writeSecurityCheckAndAccessRdb(securityMechanism,
809                 user,
810                 password,
811                 null, //encryptedUserid
812
null); //encryptedPassword,
813
}
814
815     private void readAllConnectCommandsChained(int securityMechanism) throws SqlException {
816         readServerAttributesAndKeyExchange(securityMechanism);
817         readSecurityCheckAndAccessRdb();
818     }
819
820     private void writeServerAttributesAndKeyExchange(int securityMechanism,
821                                                      byte[] publicKey) throws SqlException {
822         netAgent_.netConnectionRequest_.writeExchangeServerAttributes(extnam_, //externalName
823
targetAgent_,
824                 netAgent_.targetSqlam_,
825                 targetRdb_,
826                 targetSecmgr_,
827                 targetCmntcpip_,
828                 targetCmnappc_,
829                 targetXamgr_,
830                 targetSyncptmgr_,
831                 targetRsyncmgr_);
832         netAgent_.netConnectionRequest_.writeAccessSecurity(securityMechanism,
833                 databaseName_,
834                 publicKey);
835     }
836
837     private void writeServerAttributesAndSeedExchange(byte[] sourceSeed)
838                                                         throws SqlException {
839         
840         // For now, we're just calling our cousin method to do the job
841
writeServerAttributesAndKeyExchange(NetConfiguration.SECMEC_USRSSBPWD,
842                                             sourceSeed);
843     }
844
845     private void readServerAttributesAndKeyExchange(int securityMechanism) throws SqlException {
846         netAgent_.netConnectionReply_.readExchangeServerAttributes(this);
847         netAgent_.netConnectionReply_.readAccessSecurity(this, securityMechanism);
848     }
849
850     private void readServerAttributesAndSeedExchange() throws SqlException {
851         // For now, we're just calling our cousin method to do the job
852
readServerAttributesAndKeyExchange(NetConfiguration.SECMEC_USRSSBPWD);
853     }
854
855     private void writeSecurityCheckAndAccessRdb(int securityMechanism,
856                                                 String JavaDoc user,
857                                                 String JavaDoc password,
858                                                 byte[] encryptedUserid,
859                                                 byte[] encryptedPassword) throws SqlException {
860         netAgent_.netConnectionRequest_.writeSecurityCheck(securityMechanism,
861                 databaseName_,
862                 user,
863                 password,
864                 encryptedUserid,
865                 encryptedPassword);
866         netAgent_.netConnectionRequest_.writeAccessDatabase(databaseName_,
867                 false,
868                 crrtkn_,
869                 prddta_,
870                 netAgent_.typdef_);
871     }
872
873     private void cacheConnectBytes(int beginOffset, int endOffset) {
874         int length = endOffset - beginOffset;
875         cachedConnectBytes_ = new byte[length];
876         netAgent_.netConnectionRequest_.finalizePreviousChainedDss(false);
877         System.arraycopy(netAgent_.netConnectionRequest_.bytes_,
878                 beginOffset,
879                 cachedConnectBytes_,
880                 0,
881                 length);
882         netAgent_.netConnectionRequest_.setDssLengthLocation(netAgent_.netConnectionRequest_.offset_);
883     }
884
885     private void readSecurityCheckAndAccessRdb() throws SqlException {
886         netAgent_.netConnectionReply_.readSecurityCheck(this);
887         netAgent_.netConnectionReply_.readAccessDatabase(this);
888     }
889
890     void writeDeferredReset() throws SqlException {
891         if (canUseCachedConnectBytes_ && cachedConnectBytes_ != null &&
892                 (securityMechanism_ == NetConfiguration.SECMEC_USRIDPWD ||
893                 securityMechanism_ == NetConfiguration.SECMEC_USRIDONL)) {
894             writeDeferredResetFromCache();
895             wroteConnectFromCache_ = true;
896         } else {
897             int beginOffset = netAgent_.netConnectionRequest_.offset_;
898             int endOffset = 0;
899             // NetConfiguration.SECMEC_USRIDPWD
900
if (securityMechanism_ == NetConfiguration.SECMEC_USRIDPWD) {
901                 writeAllConnectCommandsChained(NetConfiguration.SECMEC_USRIDPWD,
902                         user_,
903                         getDeferredResetPassword());
904                 endOffset = netAgent_.netConnectionRequest_.offset_;
905                 cacheConnectBytes(beginOffset, endOffset);
906             }
907             // NetConfiguration.SECMEC_USRIDONL
908
else if (securityMechanism_ == NetConfiguration.SECMEC_USRIDONL) {
909                 writeAllConnectCommandsChained(NetConfiguration.SECMEC_USRIDONL,
910                         user_,
911                         null); //password
912
endOffset = netAgent_.netConnectionRequest_.offset_;
913                 cacheConnectBytes(beginOffset, endOffset);
914             }
915             // Either NetConfiguration.SECMEC_USRENCPWD,
916
// NetConfiguration.SECMEC_EUSRIDPWD or
917
// NetConfiguration.SECMEC_USRSSBPWD
918
else {
919                 if (securityMechanism_ == NetConfiguration.SECMEC_USRSSBPWD)
920                     initializeClientSeed();
921                 else // SECMEC_USRENCPWD, SECMEC_EUSRIDPWD
922
initializePublicKeyForEncryption();
923
924                 // Set the resetConnectionAtFirstSql_ to false to avoid going in an
925
// infinite loop, since all the flow methods call beginWriteChain which then
926
// calls writeDeferredResetConnection where the check for resetConnectionAtFirstSql_
927
// is done. By setting the resetConnectionAtFirstSql_ to false will avoid calling the
928
// writeDeferredReset method again.
929
resetConnectionAtFirstSql_ = false;
930
931                 if (securityMechanism_ == NetConfiguration.SECMEC_USRSSBPWD)
932                     flowSeedExchange(securityMechanism_, sourceSeed_);
933                 else // SECMEC_USRENCPWD, SECMEC_EUSRIDPWD
934
flowServerAttributesAndKeyExchange(securityMechanism_, publicKey_);
935
936                 agent_.beginWriteChainOutsideUOW();
937
938                 // Reset the resetConnectionAtFirstSql_ to true since we are done
939
// with the flow method.
940
resetConnectionAtFirstSql_ = true;
941
942                 // NetConfiguration.SECMEC_USRENCPWD
943
if (securityMechanism_ == NetConfiguration.SECMEC_USRENCPWD) {
944                     writeSecurityCheckAndAccessRdb(NetConfiguration.SECMEC_USRENCPWD,
945                             user_,
946                             null, //password
947
null, //encryptedUserid
948
encryptedPasswordForUSRENCPWD(getDeferredResetPassword()));
949                 }
950                 // NetConfiguration.SECMEC_USRSSBPWD
951
else if (securityMechanism_ == NetConfiguration.SECMEC_USRSSBPWD) {
952                     writeSecurityCheckAndAccessRdb(NetConfiguration.SECMEC_USRSSBPWD,
953                             user_,
954                             null,
955                             null,
956                             passwordSubstituteForUSRSSBPWD(getDeferredResetPassword()));
957                 }
958                 else { // NetConfiguration.SECMEC_EUSRIDPWD
959
writeSecurityCheckAndAccessRdb(NetConfiguration.SECMEC_EUSRIDPWD,
960                             null, //user
961
null, //password
962
encryptedUseridForEUSRIDPWD(),
963                             encryptedPasswordForEUSRIDPWD(getDeferredResetPassword()));
964                 }
965             }
966         }
967     }
968
969     void readDeferredReset() throws SqlException {
970         resetConnectionAtFirstSql_ = false;
971         if (wroteConnectFromCache_) {
972             netAgent_.netConnectionReply_.verifyDeferredReset();
973             return;
974         }
975         // either NetConfiguration.SECMEC_USRIDPWD or NetConfiguration.SECMEC_USRIDONL
976
if (securityMechanism_ == NetConfiguration.SECMEC_USRIDPWD ||
977                 securityMechanism_ == NetConfiguration.SECMEC_USRIDONL) {
978             readAllConnectCommandsChained(securityMechanism_);
979         }
980         // either NetConfiguration.SECMEC_USRENCPWD or NetConfiguration.SECMEC_EUSRIDPWD
981
else {
982             // either NetConfiguration.SECMEC_USRENCPWD or NetConfiguration.SECMEC_EUSRIDPWD
983
readSecurityCheckAndAccessRdb();
984         }
985         if (agent_.loggingEnabled()) {
986             agent_.logWriter_.traceConnectResetExit(this);
987         }
988     }
989
990     //-------------------parse callback methods--------------------------------
991

992     void setServerAttributeData(String JavaDoc extnam,
993                                 String JavaDoc srvclsnm,
994                                 String JavaDoc srvnam,
995                                 String JavaDoc srvrlslv) {
996         targetExtnam_ = extnam; // any of these could be null
997
targetSrvclsnm_ = srvclsnm; // since then can be optionally returned from the
998
targetSrvnam_ = srvnam; // server
999
targetSrvrlslv_ = srvrlslv;
1000    }
1001
1002    // secmecList is always required and will not be null.
1003
// secchkcd has an implied severity of error.
1004
// it will be returned if an error is detected.
1005
// if no errors and security mechanism requires a sectkn, then
1006
void setAccessSecurityData(int secchkcd,
1007                               int desiredSecmec,
1008                               int[] secmecList,
1009                               boolean sectknReceived,
1010                               byte[] sectkn) throws DisconnectException {
1011        // - if the secchkcd is not 0, then map to an exception.
1012
if (secchkcd != CodePoint.SECCHKCD_00) {
1013            // the implied severity code is error
1014
netAgent_.setSvrcod(CodePoint.SVRCOD_ERROR);
1015            agent_.accumulateReadException(mapSecchkcd(secchkcd));
1016        } else {
1017            // - verify that the secmec parameter reflects the value sent
1018
// in the ACCSEC command.
1019
// should we check for null list
1020
if ((secmecList.length == 1) &&
1021                    (secmecList[0] == desiredSecmec)) {
1022                // the security mechanism returned from the server matches
1023
// the mechanism requested by the client.
1024
targetSecmec_ = secmecList[0];
1025
1026                if ((targetSecmec_ == NetConfiguration.SECMEC_USRENCPWD) ||
1027                        (targetSecmec_ == NetConfiguration.SECMEC_EUSRIDPWD) ||
1028                        (targetSecmec_ == NetConfiguration.SECMEC_USRSSBPWD) ||
1029                        (targetSecmec_ == NetConfiguration.SECMEC_EUSRIDDTA) ||
1030                        (targetSecmec_ == NetConfiguration.SECMEC_EUSRPWDDTA)) {
1031
1032                    // a security token is required for USRENCPWD, or EUSRIDPWD.
1033
if (!sectknReceived) {
1034                        agent_.accumulateChainBreakingReadExceptionAndThrow(
1035                            new DisconnectException(agent_,
1036                                new ClientMessageId(SQLState.NET_SECTKN_NOT_RETURNED)));
1037                    } else {
1038                        if (targetSecmec_ == NetConfiguration.SECMEC_USRSSBPWD)
1039                            targetSeed_ = sectkn;
1040                        else
1041                            targetPublicKey_ = sectkn;
1042                        if (encryptionManager_ != null) {
1043                            encryptionManager_.resetSecurityKeys();
1044                        }
1045                    }
1046                }
1047            } else {
1048                // accumulate an SqlException and don't disconnect yet
1049
// if a SECCHK was chained after this it would receive a secchk code
1050
// indicating the security mechanism wasn't supported and that would be a
1051
// chain breaking exception. if no SECCHK is chained this exception
1052
// will be surfaced by endReadChain
1053
// agent_.accumulateChainBreakingReadExceptionAndThrow (
1054
// new DisconnectException (agent_,"secmec not supported ","0000", -999));
1055
agent_.accumulateReadException(new SqlException(agent_.logWriter_,
1056                    new ClientMessageId(SQLState.NET_SECKTKN_NOT_RETURNED)));
1057            }
1058        }
1059    }
1060
1061    void securityCheckComplete(int svrcod, int secchkcd) {
1062        netAgent_.setSvrcod(svrcod);
1063        if (secchkcd == CodePoint.SECCHKCD_00) {
1064            return;
1065        }
1066        agent_.accumulateReadException(mapSecchkcd(secchkcd));
1067    }
1068
1069    void rdbAccessed(int svrcod,
1070                     String JavaDoc prdid,
1071                     boolean crrtknReceived,
1072                     byte[] crrtkn) {
1073        if (crrtknReceived) {
1074            crrtkn_ = crrtkn;
1075        }
1076
1077        netAgent_.setSvrcod(svrcod);
1078        productID_ = prdid;
1079    }
1080
1081
1082    //-------------------Abstract object factories--------------------------------
1083

1084    protected org.apache.derby.client.am.Agent newAgent_(org.apache.derby.client.am.LogWriter logWriter, int loginTimeout, String JavaDoc serverName, int portNumber)
1085            throws SqlException {
1086        return new NetAgent(this,
1087                (NetLogWriter) logWriter,
1088                loginTimeout,
1089                serverName,
1090                portNumber);
1091    }
1092
1093
1094    protected Statement newStatement_(int type, int concurrency, int holdability) throws SqlException {
1095        return new NetStatement(netAgent_, this, type, concurrency, holdability).statement_;
1096    }
1097
1098    protected void resetStatement_(Statement statement, int type, int concurrency, int holdability) throws SqlException {
1099        ((NetStatement) statement.materialStatement_).resetNetStatement(netAgent_, this, type, concurrency, holdability);
1100    }
1101
1102    protected PreparedStatement newPositionedUpdatePreparedStatement_(String JavaDoc sql,
1103                                                                      org.apache.derby.client.am.Section section) throws SqlException {
1104        //passing the pooledConnection_ object which will be used to raise
1105
//StatementEvents to the PooledConnection
1106
return new NetPreparedStatement(netAgent_, this, sql, section,pooledConnection_).preparedStatement_;
1107    }
1108
1109    protected PreparedStatement newPreparedStatement_(String JavaDoc sql, int type, int concurrency, int holdability, int autoGeneratedKeys, String JavaDoc[] columnNames) throws SqlException {
1110        
1111        //passing the pooledConnection_ object which will be used to raise
1112
//StatementEvents to the PooledConnection
1113
return new NetPreparedStatement(netAgent_, this, sql, type, concurrency, holdability, autoGeneratedKeys, columnNames,pooledConnection_).preparedStatement_;
1114    }
1115
1116    protected void resetPreparedStatement_(PreparedStatement ps,
1117                                           String JavaDoc sql,
1118                                           int resultSetType,
1119                                           int resultSetConcurrency,
1120                                           int resultSetHoldability,
1121                                           int autoGeneratedKeys,
1122                                           String JavaDoc[] columnNames) throws SqlException {
1123        ((NetPreparedStatement) ps.materialPreparedStatement_).resetNetPreparedStatement(netAgent_, this, sql, resultSetType, resultSetConcurrency, resultSetHoldability, autoGeneratedKeys, columnNames);
1124    }
1125
1126
1127    protected CallableStatement newCallableStatement_(String JavaDoc sql, int type, int concurrency, int holdability) throws SqlException {
1128        //passing the pooledConnection_ object which will be used to raise
1129
//StatementEvents to the PooledConnection
1130
return new NetCallableStatement(netAgent_, this, sql, type, concurrency, holdability,pooledConnection_).callableStatement_;
1131    }
1132
1133    protected void resetCallableStatement_(CallableStatement cs,
1134                                           String JavaDoc sql,
1135                                           int resultSetType,
1136                                           int resultSetConcurrency,
1137                                           int resultSetHoldability) throws SqlException {
1138        ((NetCallableStatement) cs.materialCallableStatement_).resetNetCallableStatement(netAgent_, this, sql, resultSetType, resultSetConcurrency, resultSetHoldability);
1139    }
1140
1141
1142    protected DatabaseMetaData newDatabaseMetaData_() {
1143            return ClientDriver.getFactory().newNetDatabaseMetaData(netAgent_, this);
1144    }
1145
1146    //-------------------private helper methods--------------------------------
1147

1148    private void checkDatabaseName() throws SqlException {
1149        // netAgent_.logWriter may not be initialized yet
1150
if (databaseName_ == null) {
1151            throw new SqlException(agent_.logWriter_,
1152                new ClientMessageId(SQLState.CONNECT_REQUIRED_PROPERTY_NOT_SET),
1153                "databaseName");
1154        }
1155    }
1156
1157    private void checkUserLength(String JavaDoc user) throws SqlException {
1158        int usridLength = user.length();
1159        if ((usridLength == 0) || (usridLength > NetConfiguration.USRID_MAXSIZE)) {
1160            throw new SqlException(netAgent_.logWriter_,
1161                new ClientMessageId(SQLState.CONNECT_USERID_LENGTH_OUT_OF_RANGE),
1162                new Integer JavaDoc(usridLength),
1163                new Integer JavaDoc(NetConfiguration.USRID_MAXSIZE));
1164        }
1165    }
1166
1167    private void checkPasswordLength(String JavaDoc password) throws SqlException {
1168        int passwordLength = password.length();
1169        if ((passwordLength == 0) || (passwordLength > NetConfiguration.PASSWORD_MAXSIZE)) {
1170            throw new SqlException(netAgent_.logWriter_,
1171                new ClientMessageId(SQLState.CONNECT_PASSWORD_LENGTH_OUT_OF_RANGE),
1172                new Integer JavaDoc(passwordLength),
1173                new Integer JavaDoc(NetConfiguration.PASSWORD_MAXSIZE));
1174        }
1175    }
1176
1177    private void checkUser(String JavaDoc user) throws SqlException {
1178        if (user == null) {
1179            throw new SqlException(netAgent_.logWriter_,
1180                new ClientMessageId(SQLState.CONNECT_USERID_ISNULL));
1181        }
1182        checkUserLength(user);
1183    }
1184
1185    private void checkUserPassword(String JavaDoc user, String JavaDoc password) throws SqlException {
1186        checkUser(user);
1187        if (password == null) {
1188            throw new SqlException(netAgent_.logWriter_,
1189                new ClientMessageId(SQLState.CONNECT_PASSWORD_ISNULL));
1190        }
1191        checkPasswordLength(password);
1192    }
1193
1194
1195    // Determine if a security mechanism is supported by
1196
// the security manager used for the connection.
1197
// An exception is thrown if the security mechanism is not supported
1198
// by the secmgr.
1199
private void checkSecmgrForSecmecSupport(int securityMechanism) throws SqlException {
1200        boolean secmecSupported = false;
1201        int[] supportedSecmecs = null;
1202
1203        // Point to a list (array) of supported security mechanisms.
1204
supportedSecmecs = NetConfiguration.SECMGR_SECMECS;
1205
1206        // check to see if the security mechanism is on the supported list.
1207
for (int i = 0; (i < supportedSecmecs.length) && (!secmecSupported); i++) {
1208            if (supportedSecmecs[i] == securityMechanism) {
1209                secmecSupported = true;
1210            }
1211        }
1212
1213        // throw an exception if not supported (not on list).
1214
if (!secmecSupported) {
1215            throw new SqlException(agent_.logWriter_,
1216                new ClientMessageId(SQLState.SECMECH_NOT_SUPPORTED),
1217                new Integer JavaDoc(securityMechanism));
1218        }
1219    }
1220
1221    // If secchkcd is not 0, map to SqlException
1222
// according to the secchkcd received.
1223
private SqlException mapSecchkcd(int secchkcd) {
1224        if (secchkcd == CodePoint.SECCHKCD_00) {
1225            return null;
1226        }
1227
1228        // the net driver will not support new password at this time.
1229
// Here is the message for -30082 (STATE "08001"):
1230
// Attempt to establish connection failed with security
1231
// reason {0} {1} + reason-code + reason-string.
1232
switch (secchkcd) {
1233        case CodePoint.SECCHKCD_01: // ERROR SVRCOD
1234
return new SqlException(agent_.logWriter_,
1235                new ClientMessageId(SQLState.NET_CONNECT_AUTH_FAILED),
1236                msgutil.getTextMessage(MessageId.CONN_SECMECH_NOT_SUPPORTED));
1237        case CodePoint.SECCHKCD_10: // ERROR SVRCOD
1238
return new SqlException(agent_.logWriter_,
1239                new ClientMessageId(SQLState.NET_CONNECT_AUTH_FAILED),
1240                msgutil.getTextMessage(MessageId.CONN_PASSWORD_MISSING));
1241        case CodePoint.SECCHKCD_12: // ERROR SVRCOD
1242
return new SqlException(agent_.logWriter_,
1243                new ClientMessageId(SQLState.NET_CONNECT_AUTH_FAILED),
1244                msgutil.getTextMessage(MessageId.CONN_USERID_MISSING));
1245        case CodePoint.SECCHKCD_13: // ERROR SVRCOD
1246
return new SqlException(agent_.logWriter_,
1247                new ClientMessageId(SQLState.NET_CONNECT_AUTH_FAILED),
1248                msgutil.getTextMessage(MessageId.CONN_USERID_OR_PASSWORD_INVALID));
1249        case CodePoint.SECCHKCD_14: // ERROR SVRCOD
1250
return new SqlException(agent_.logWriter_,
1251                new ClientMessageId(SQLState.NET_CONNECT_AUTH_FAILED),
1252                msgutil.getTextMessage(MessageId.CONN_USERID_REVOKED));
1253        case CodePoint.SECCHKCD_15: // ERROR SVRCOD
1254
return new SqlException(agent_.logWriter_,
1255                new ClientMessageId(SQLState.NET_CONNECT_AUTH_FAILED),
1256                msgutil.getTextMessage(MessageId.CONN_NEW_PASSWORD_INVALID));
1257        case CodePoint.SECCHKCD_0A: // ERROR SVRCOD
1258
return new SqlException(agent_.logWriter_,
1259                new ClientMessageId(SQLState.NET_CONNECT_AUTH_FAILED),
1260                msgutil.getTextMessage(MessageId.CONN_SECSVC_NONRETRYABLE_ERR));
1261        case CodePoint.SECCHKCD_0B: // ERROR SVRCOD
1262
return new SqlException(agent_.logWriter_,
1263                new ClientMessageId(SQLState.NET_CONNECT_AUTH_FAILED),
1264                msgutil.getTextMessage(MessageId.CONN_SECTKN_MISSING_OR_INVALID));
1265        case CodePoint.SECCHKCD_0E: // ERROR SVRCOD
1266
return new SqlException(agent_.logWriter_,
1267                new ClientMessageId(SQLState.NET_CONNECT_AUTH_FAILED),
1268                msgutil.getTextMessage(MessageId.CONN_PASSWORD_EXPIRED));
1269        case CodePoint.SECCHKCD_0F: // ERROR SVRCOD
1270
return new SqlException(agent_.logWriter_,
1271                new ClientMessageId(SQLState.NET_CONNECT_AUTH_FAILED),
1272                msgutil.getTextMessage(MessageId.CONN_USERID_OR_PASSWORD_INVALID));
1273        default: // ERROR SVRCOD
1274
return new SqlException(agent_.logWriter_,
1275                new ClientMessageId(SQLState.NET_CONNECT_AUTH_FAILED),
1276                msgutil.getTextMessage(MessageId.CONN_NOT_SPECIFIED));
1277        }
1278    }
1279
1280    // Construct the correlation token.
1281
// The crrtkn has the following format.
1282
//
1283
// <Almost IP address>.<local port number><current time in millis>
1284
// | | | || |
1285
// +----+--------------+ +-----+---------++---------+--------+
1286
// | | |
1287
// 8 bytes 4 bytes 6 bytes
1288
// Total lengtho of 19 bytes.
1289
//
1290
// 1 char for each 1/2 byte in the IP address.
1291
// If the first character of the <IP address> or <port number>
1292
// starts with '0' thru '9', it will be mapped to 'G' thru 'P'.
1293
// Reason for mapping the IP address is in order to use the crrtkn as the LUWID when using SNA in a hop site.
1294
protected void constructCrrtkn() throws SqlException {
1295        byte[] localAddressBytes = null;
1296        long time = 0;
1297        int num = 0;
1298        int halfByte = 0;
1299        int i = 0;
1300        int j = 0;
1301
1302        // allocate the crrtkn array.
1303
if (crrtkn_ == null) {
1304            crrtkn_ = new byte[19];
1305        } else {
1306            java.util.Arrays.fill(crrtkn_, (byte) 0);
1307        }
1308
1309        localAddressBytes = netAgent_.socket_.getLocalAddress().getAddress();
1310
1311        // IP addresses are returned in a 4 byte array.
1312
// Obtain the character representation of each half byte.
1313
for (i = 0, j = 0; i < 4; i++, j += 2) {
1314
1315            // since a byte is signed in java, convert any negative
1316
// numbers to positive before shifting.
1317
num = localAddressBytes[i] < 0 ? localAddressBytes[i] + 256 : localAddressBytes[i];
1318            halfByte = (num >> 4) & 0x0f;
1319
1320            // map 0 to G
1321
// The first digit of the IP address is is replaced by
1322
// the characters 'G' thro 'P'(in order to use the crrtkn as the LUWID when using
1323
// SNA in a hop site). For example, 0 is mapped to G, 1 is mapped H,etc.
1324
if (i == 0) {
1325                crrtkn_[j] = netAgent_.sourceCcsidManager_.numToSnaRequiredCrrtknChar_[halfByte];
1326            } else {
1327                crrtkn_[j] = netAgent_.sourceCcsidManager_.numToCharRepresentation_[halfByte];
1328            }
1329
1330            halfByte = (num) & 0x0f;
1331            crrtkn_[j + 1] = netAgent_.sourceCcsidManager_.numToCharRepresentation_[halfByte];
1332        }
1333
1334        // fill the '.' in between the IP address and the port number
1335
crrtkn_[8] = netAgent_.sourceCcsidManager_.dot_;
1336
1337        // Port numbers have values which fit in 2 unsigned bytes.
1338
// Java returns port numbers in an int so the value is not negative.
1339
// Get the character representation by converting the
1340
// 4 low order half bytes to the character representation.
1341
num = netAgent_.socket_.getLocalPort();
1342
1343        halfByte = (num >> 12) & 0x0f;
1344        crrtkn_[9] = netAgent_.sourceCcsidManager_.numToSnaRequiredCrrtknChar_[halfByte];
1345        halfByte = (num >> 8) & 0x0f;
1346        crrtkn_[10] = netAgent_.sourceCcsidManager_.numToCharRepresentation_[halfByte];
1347        halfByte = (num >> 4) & 0x0f;
1348        crrtkn_[11] = netAgent_.sourceCcsidManager_.numToCharRepresentation_[halfByte];
1349        halfByte = (num) & 0x0f;
1350        crrtkn_[12] = netAgent_.sourceCcsidManager_.numToCharRepresentation_[halfByte];
1351
1352        // The final part of CRRTKN is a 6 byte binary number that makes the
1353
// crrtkn unique, which is usually the time stamp/process id.
1354
// If the new time stamp is the
1355
// same as one of the already created ones, then recreate the time stamp.
1356
time = System.currentTimeMillis();
1357
1358        for (i = 0; i < 6; i++) {
1359            // store 6 bytes of 8 byte time into crrtkn
1360
crrtkn_[i + 13] = (byte) (time >>> (40 - (i * 8)));
1361        }
1362    }
1363
1364
1365    private void constructExtnam() throws SqlException {
1366        extnam_ = "derbydnc" + java.lang.Thread.currentThread().getName();
1367    }
1368
1369    private void constructPrddta() throws SqlException {
1370        int prddtaLen = 1;
1371
1372        if (prddta_ == null) {
1373            prddta_ = new byte[NetConfiguration.PRDDTA_MAXSIZE];
1374        } else {
1375            java.util.Arrays.fill(prddta_, (byte) 0);
1376        }
1377
1378        for (int i = 0; i < NetConfiguration.PRDDTA_ACCT_SUFFIX_LEN_BYTE; i++) {
1379            prddta_[i] = netAgent_.sourceCcsidManager_.space_;
1380        }
1381
1382        prddtaLen = netAgent_.sourceCcsidManager_.convertFromUCS2(NetConfiguration.PRDID,
1383                prddta_,
1384                prddtaLen,
1385                netAgent_);
1386
1387        prddtaLen = netAgent_.sourceCcsidManager_.convertFromUCS2(NetConfiguration.PRDDTA_PLATFORM_ID,
1388                prddta_,
1389                prddtaLen,
1390                netAgent_);
1391
1392        int extnamTruncateLength = Utils.min(extnam_.length(), NetConfiguration.PRDDTA_APPL_ID_FIXED_LEN);
1393        netAgent_.sourceCcsidManager_.convertFromUCS2(extnam_.substring(0, extnamTruncateLength),
1394                prddta_,
1395                prddtaLen,
1396                netAgent_);
1397        prddtaLen += NetConfiguration.PRDDTA_APPL_ID_FIXED_LEN;
1398
1399        if (user_ != null) {
1400            int userTruncateLength = Utils.min(user_.length(), NetConfiguration.PRDDTA_USER_ID_FIXED_LEN);
1401            netAgent_.sourceCcsidManager_.convertFromUCS2(user_.substring(0, userTruncateLength),
1402                    prddta_,
1403                    prddtaLen,
1404                    netAgent_);
1405        }
1406
1407        prddtaLen += NetConfiguration.PRDDTA_USER_ID_FIXED_LEN;
1408
1409        prddta_[NetConfiguration.PRDDTA_ACCT_SUFFIX_LEN_BYTE] = 0;
1410        prddtaLen++;
1411        // the length byte value does not include itself.
1412
prddta_[NetConfiguration.PRDDTA_LEN_BYTE] = (byte) (prddtaLen - 1);
1413    }
1414
1415    private void initializePublicKeyForEncryption() throws SqlException {
1416        if (encryptionManager_ == null) {
1417            encryptionManager_ = new EncryptionManager(agent_);
1418        }
1419        publicKey_ = encryptionManager_.obtainPublicKey();
1420    }
1421
1422    // SECMEC_USRSSBPWD security mechanism - Generate a source (client) seed
1423
// to send to the target (application) server.
1424
private void initializeClientSeed() throws SqlException {
1425        if (encryptionManager_ == null) {
1426            encryptionManager_ = new EncryptionManager(
1427                                    agent_,
1428                                    EncryptionManager.SHA_1_DIGEST_ALGORITHM);
1429        }
1430        sourceSeed_ = encryptionManager_.generateSeed();
1431    }
1432
1433    private byte[] encryptedPasswordForUSRENCPWD(String JavaDoc password) throws SqlException {
1434        return encryptionManager_.encryptData(netAgent_.sourceCcsidManager_.convertFromUCS2(password, netAgent_),
1435                NetConfiguration.SECMEC_USRENCPWD,
1436                netAgent_.sourceCcsidManager_.convertFromUCS2(user_, netAgent_),
1437                targetPublicKey_);
1438    }
1439
1440    private byte[] encryptedUseridForEUSRIDPWD() throws SqlException {
1441        return encryptionManager_.encryptData(netAgent_.sourceCcsidManager_.convertFromUCS2(user_, netAgent_),
1442                NetConfiguration.SECMEC_EUSRIDPWD,
1443                targetPublicKey_,
1444                targetPublicKey_);
1445    }
1446
1447    private byte[] encryptedPasswordForEUSRIDPWD(String JavaDoc password) throws SqlException {
1448        return encryptionManager_.encryptData(netAgent_.sourceCcsidManager_.convertFromUCS2(password, netAgent_),
1449                NetConfiguration.SECMEC_EUSRIDPWD,
1450                targetPublicKey_,
1451                targetPublicKey_);
1452    }
1453
1454    private byte[] passwordSubstituteForUSRSSBPWD(String JavaDoc password) throws SqlException {
1455        String JavaDoc userName = user_;
1456        
1457        // Define which userName takes precedence - If we have a dataSource
1458
// available here, it is posible that the userName has been
1459
// overriden by some defined as part of the connection attributes
1460
// (see ClientBaseDataSource.updateDataSourceValues().
1461
// We need to use the right userName as strong password
1462
// substitution depends on the userName when the substitute
1463
// password is generated; if we were not using the right userName
1464
// then authentication would fail when regenerating the substitute
1465
// password on the engine server side, where userName as part of the
1466
// connection attributes would get used to authenticate the user.
1467
if (dataSource_ != null)
1468        {
1469            String JavaDoc dataSourceUserName = dataSource_.getUser();
1470            if (!dataSourceUserName.equals("") &&
1471                userName.equalsIgnoreCase(
1472                    dataSource_.propertyDefault_user) &&
1473                !dataSourceUserName.equalsIgnoreCase(
1474                    dataSource_.propertyDefault_user))
1475            {
1476                userName = dataSourceUserName;
1477            }
1478        }
1479        return encryptionManager_.substitutePassword(
1480                userName, password, sourceSeed_, targetSeed_);
1481    }
1482
1483    // Methods to get the manager levels for Regression harness only.
1484
public int getSQLAM() {
1485        return netAgent_.targetSqlam_;
1486    }
1487
1488    public int getAGENT() {
1489        return targetAgent_;
1490    }
1491
1492    public int getCMNTCPIP() {
1493        return targetCmntcpip_;
1494    }
1495
1496    public int getRDB() {
1497        return targetRdb_;
1498    }
1499
1500    public int getSECMGR() {
1501        return targetSecmgr_;
1502    }
1503
1504    public int getXAMGR() {
1505        return targetXamgr_;
1506    }
1507
1508    public int getSYNCPTMGR() {
1509        return targetSyncptmgr_;
1510    }
1511
1512    public int getRSYNCMGR() {
1513        return targetRsyncmgr_;
1514    }
1515
1516
1517    private char[] flipBits(char[] array) {
1518        for (int i = 0; i < array.length; i++) {
1519            array[i] ^= 0xff;
1520        }
1521        return array;
1522    }
1523
1524    private void writeDeferredResetFromCache() {
1525        int length = cachedConnectBytes_.length;
1526        System.arraycopy(cachedConnectBytes_,
1527                0,
1528                netAgent_.netConnectionRequest_.bytes_,
1529                netAgent_.netConnectionRequest_.offset_,
1530                length);
1531        netAgent_.netConnectionRequest_.offset_ += length;
1532        netAgent_.netConnectionRequest_.setDssLengthLocation(netAgent_.netConnectionRequest_.offset_);
1533        netAgent_.netConnectionRequest_.setCorrelationID(4);
1534    }
1535
1536
1537    public void writeCommitSubstitute_() throws SqlException {
1538        netAgent_.connectionRequest_.writeCommitSubstitute(this);
1539    }
1540
1541    public void readCommitSubstitute_() throws SqlException {
1542        netAgent_.connectionReply_.readCommitSubstitute(this);
1543    }
1544
1545    public void writeLocalXAStart_() throws SqlException {
1546        netAgent_.connectionRequest_.writeLocalXAStart(this);
1547    }
1548
1549    public void readLocalXAStart_() throws SqlException {
1550        netAgent_.connectionReply_.readLocalXAStart(this);
1551    }
1552
1553    public void writeLocalXACommit_() throws SqlException {
1554        netAgent_.connectionRequest_.writeLocalXACommit(this);
1555    }
1556
1557    public void readLocalXACommit_() throws SqlException {
1558        netAgent_.connectionReply_.readLocalXACommit(this);
1559    }
1560
1561    public void writeLocalXARollback_() throws SqlException {
1562        netAgent_.connectionRequest_.writeLocalXARollback(this);
1563    }
1564
1565    public void readLocalXARollback_() throws SqlException {
1566        netAgent_.connectionReply_.readLocalXARollback(this);
1567    }
1568
1569    public void writeLocalCommit_() throws SqlException {
1570        netAgent_.connectionRequest_.writeLocalCommit(this);
1571    }
1572
1573    public void readLocalCommit_() throws SqlException {
1574        netAgent_.connectionReply_.readLocalCommit(this);
1575    }
1576
1577    public void writeLocalRollback_() throws SqlException {
1578        netAgent_.connectionRequest_.writeLocalRollback(this);
1579    }
1580
1581    public void readLocalRollback_() throws SqlException {
1582        netAgent_.connectionReply_.readLocalRollback(this);
1583    }
1584
1585
1586    protected void markClosed_() {
1587    }
1588
1589    protected boolean isGlobalPending_() {
1590        return false;
1591    }
1592
1593    protected boolean doCloseStatementsOnClose_() {
1594        return true;
1595    }
1596
1597    protected boolean allowCloseInUOW_() {
1598        return false;
1599    }
1600
1601    // Driver-specific determination if local COMMIT/ROLLBACK is allowed;
1602
// Allow local COMMIT/ROLLBACK only if we are not in an XA transaction
1603
protected boolean allowLocalCommitRollback_() throws org.apache.derby.client.am.SqlException {
1604       
1605        if (getXAState() == XA_T0_NOT_ASSOCIATED) {
1606            return true;
1607        }
1608        return false;
1609    }
1610
1611    public void setInputStream(java.io.InputStream JavaDoc inputStream) {
1612        netAgent_.setInputStream(inputStream);
1613    }
1614
1615    public void setOutputStream(java.io.OutputStream JavaDoc outputStream) {
1616        netAgent_.setOutputStream(outputStream);
1617    }
1618
1619    public java.io.InputStream JavaDoc getInputStream() {
1620        return netAgent_.getInputStream();
1621    }
1622
1623    public java.io.OutputStream JavaDoc getOutputStream() {
1624        return netAgent_.getOutputStream();
1625    }
1626
1627
1628    public void writeTransactionStart(Statement statement) throws SqlException {
1629    }
1630
1631    public void readTransactionStart() throws SqlException {
1632        super.readTransactionStart();
1633    }
1634
1635    public void setIndoubtTransactions(java.util.Hashtable JavaDoc indoubtTransactions) {
1636        if (isXAConnection_) {
1637            if (indoubtTransactions_ != null) {
1638                indoubtTransactions_.clear();
1639            }
1640            indoubtTransactions_ = indoubtTransactions;
1641        }
1642    }
1643
1644    protected void setReadOnlyTransactionFlag(boolean flag) {
1645        readOnlyTransaction_ = flag;
1646    }
1647
1648    public org.apache.derby.client.am.SectionManager newSectionManager
1649            (String JavaDoc collection,
1650             org.apache.derby.client.am.Agent agent,
1651             String JavaDoc databaseName) {
1652        return new org.apache.derby.client.am.SectionManager(collection, agent, databaseName);
1653    }
1654
1655    protected int getSocketAndInputOutputStreams(String JavaDoc server, int port) {
1656        try {
1657            netAgent_.socket_ = (java.net.Socket JavaDoc) java.security.AccessController.doPrivileged(new OpenSocketAction(server, port));
1658        } catch (java.security.PrivilegedActionException JavaDoc e) {
1659            Exception JavaDoc openSocketException = e.getException();
1660            if (netAgent_.loggingEnabled()) {
1661                netAgent_.logWriter_.tracepoint("[net]", 101, "Client Re-route: " + openSocketException.getClass().getName() + " : " + openSocketException.getMessage());
1662            }
1663            return -1;
1664        }
1665
1666        try {
1667            netAgent_.rawSocketOutputStream_ = netAgent_.socket_.getOutputStream();
1668            netAgent_.rawSocketInputStream_ = netAgent_.socket_.getInputStream();
1669        } catch (java.io.IOException JavaDoc e) {
1670            if (netAgent_.loggingEnabled()) {
1671                netAgent_.logWriter_.tracepoint("[net]", 103, "Client Re-route: java.io.IOException " + e.getMessage());
1672            }
1673            try {
1674                netAgent_.socket_.close();
1675            } catch (java.io.IOException JavaDoc doNothing) {
1676            }
1677            return -1;
1678        }
1679        return 0;
1680    }
1681
1682    protected int checkAlternateServerHasEqualOrHigherProductLevel(ProductLevel orgLvl, int orgServerType) {
1683        if (orgLvl == null && orgServerType == 0) {
1684            return 0;
1685        }
1686        ProductLevel alternateServerProductLvl =
1687                netAgent_.netConnection_.databaseMetaData_.productLevel_;
1688        boolean alternateServerIsEqualOrHigherToOriginalServer =
1689                (alternateServerProductLvl.greaterThanOrEqualTo
1690                (orgLvl.versionLevel_,
1691                        orgLvl.releaseLevel_,
1692                        orgLvl.modificationLevel_)) ? true : false;
1693        // write an entry to the trace
1694
if (!alternateServerIsEqualOrHigherToOriginalServer &&
1695                netAgent_.loggingEnabled()) {
1696            netAgent_.logWriter_.tracepoint("[net]",
1697                    99,
1698                    "Client Re-route failed because the alternate server is on a lower product level than the origianl server.");
1699        }
1700        return (alternateServerIsEqualOrHigherToOriginalServer) ? 0 : -1;
1701    }
1702
1703    public boolean willAutoCommitGenerateFlow() {
1704        // this logic must be in sync with writeCommit() logic
1705
if (!autoCommit_) {
1706            return false;
1707        }
1708        if (!isXAConnection_) {
1709            return true;
1710        }
1711        boolean doCommit = false;
1712        int xaState = getXAState();
1713
1714        
1715        if (xaState == XA_T0_NOT_ASSOCIATED) {
1716            doCommit = true;
1717        }
1718
1719        return doCommit;
1720    }
1721
1722    public int getSecurityMechanism() {
1723        return securityMechanism_;
1724    }
1725
1726    public EncryptionManager getEncryptionManager() {
1727        return encryptionManager_;
1728    }
1729
1730    public byte[] getTargetPublicKey() {
1731        return targetPublicKey_;
1732    }
1733
1734    public String JavaDoc getProductID() {
1735        return targetSrvclsnm_;
1736    }
1737
1738    public void doResetNow() throws SqlException {
1739        if (!resetConnectionAtFirstSql_) {
1740            return; // reset not needed
1741
}
1742        agent_.beginWriteChainOutsideUOW();
1743        agent_.flowOutsideUOW();
1744        agent_.endReadChain();
1745    }
1746    
1747    /**
1748     * @return Returns the connectionNull.
1749     */

1750    public boolean isConnectionNull() {
1751        return connectionNull;
1752    }
1753    /**
1754     * @param connectionNull The connectionNull to set.
1755     */

1756    public void setConnectionNull(boolean connectionNull) {
1757        this.connectionNull = connectionNull;
1758    }
1759
1760    /**
1761     * Check whether the server has full support for the QRYCLSIMP
1762     * parameter in OPNQRY.
1763     *
1764     * @return true if QRYCLSIMP is fully supported
1765     */

1766    public final boolean serverSupportsQryclsimp() {
1767        NetDatabaseMetaData metadata =
1768            (NetDatabaseMetaData) databaseMetaData_;
1769        return metadata.serverSupportsQryclsimp();
1770    }
1771    
1772    /**
1773     * Returns if a transaction is in process
1774     * @return open
1775     */

1776    public boolean isOpen() {
1777        return open_;
1778    }
1779    
1780    /**
1781     * closes underlying connection and associated resource.
1782     */

1783    synchronized public void close() throws SQLException JavaDoc {
1784        // call super.close*() to do the close*
1785
super.close();
1786        if (!isXAConnection_)
1787            return;
1788        if (isOpen()) {
1789            return; // still open, return
1790
}
1791        if (xares_ != null) {
1792            xares_.removeXaresFromSameRMchain();
1793        }
1794    }
1795    
1796    /**
1797     * closes underlying connection and associated resource.
1798     */

1799    synchronized public void closeX() throws SQLException JavaDoc {
1800        // call super.close*() to do the close*
1801
super.closeX();
1802        if (!isXAConnection_)
1803            return;
1804        if (isOpen()) {
1805            return; // still open, return
1806
}
1807        if (xares_ != null) {
1808            xares_.removeXaresFromSameRMchain();
1809        }
1810    }
1811    
1812    /**
1813     * Invalidates connection but keeps socket open.
1814     */

1815    synchronized public void closeForReuse() throws SqlException {
1816        // call super.close*() to do the close*
1817
super.closeForReuse();
1818        if (!isXAConnection_)
1819            return;
1820        if (isOpen()) {
1821            return; // still open, return
1822
}
1823        if (xares_ != null) {
1824            xares_.removeXaresFromSameRMchain();
1825        }
1826    }
1827    
1828    /**
1829     * closes resources connection will be not available
1830     * for reuse.
1831     */

1832    synchronized public void closeResources() throws SQLException JavaDoc {
1833        // call super.close*() to do the close*
1834
super.closeResources();
1835        if (!isXAConnection_)
1836            return;
1837        
1838        if (isOpen()) {
1839            return; // still open, return
1840
}
1841        if (xares_ != null) {
1842            xares_.removeXaresFromSameRMchain();
1843        }
1844    }
1845    
1846    
1847    /**
1848     * Invokes write commit on NetXAConnection
1849     */

1850    protected void writeXACommit_() throws SqlException {
1851        xares_.netXAConn_.writeCommit();
1852    }
1853    
1854    /**
1855     * Invokes readCommit on NetXAConnection
1856     */

1857    protected void readXACommit_() throws SqlException {
1858        xares_.netXAConn_.readCommit();
1859    }
1860    
1861    /**
1862     * Invokes writeRollback on NetXAConnection
1863     */

1864    protected void writeXARollback_() throws SqlException {
1865        xares_.netXAConn_.writeRollback();
1866    }
1867    
1868    /**
1869     * Invokes writeRollback on NetXAConnection
1870     */

1871    protected void readXARollback_() throws SqlException {
1872            xares_.netXAConn_.readRollback();
1873    }
1874    
1875    
1876    protected void writeXATransactionStart(Statement statement) throws SqlException {
1877        xares_.netXAConn_.writeTransactionStart(statement);
1878    }
1879}
1880
1881
Popular Tags