KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2
3    Derby - Class org.apache.derby.client.net.NetAgent
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.net.SocketException JavaDoc;
25
26 import org.apache.derby.client.am.Agent;
27 import org.apache.derby.client.am.DisconnectException;
28 import org.apache.derby.client.am.SqlException;
29 import org.apache.derby.client.am.ClientMessageId;
30 import org.apache.derby.client.am.Utils;
31 import org.apache.derby.shared.common.sanity.SanityManager;
32
33 import org.apache.derby.shared.common.reference.SQLState;
34 import org.apache.derby.shared.common.reference.MessageId;
35 import org.apache.derby.shared.common.i18n.MessageUtil;
36
37 public class NetAgent extends Agent {
38     //---------------------navigational members-----------------------------------
39

40     // All these request objects point to the same physical request object.
41
public ConnectionRequestInterface connectionRequest_;
42     public NetConnectionRequest packageRequest_;
43     public StatementRequestInterface statementRequest_;
44     public ResultSetRequestInterface resultSetRequest_;
45
46     // All these reply objects point to the same physical reply object.
47
public ConnectionReply connectionReply_;
48     public ConnectionReply packageReply_;
49     public StatementReply statementReply_;
50     public ResultSetReply resultSetReply_;
51
52     //---------------------navigational cheat-links-------------------------------
53
// Cheat-links are for convenience only, and are not part of the conceptual model.
54
// Warning:
55
// Cheat-links should only be defined for invariant state data.
56
// That is, the state data is set by the constructor and never changes.
57

58     // Alias for (NetConnection) super.connection
59
NetConnection netConnection_;
60
61     // Alias for (Request) super.*Request, all in one
62
// In the case of the NET implementation, these all point to the same physical request object.
63
protected Request request_;
64     public NetConnectionRequest netConnectionRequest_;
65     public NetPackageRequest netPackageRequest_;
66     public NetStatementRequest netStatementRequest_;
67     public NetResultSetRequest netResultSetRequest_;
68
69     // Alias for (Reply) super.*Reply, all in one.
70
// In the case of the NET implementation, these all point to the same physical reply object.
71
protected Reply reply_;
72     public NetConnectionReply netConnectionReply_;
73     public NetPackageReply netPackageReply_;
74     public NetStatementReply netStatementReply_;
75     public NetResultSetReply netResultSetReply_;
76
77     //-----------------------------state------------------------------------------
78

79     java.net.Socket JavaDoc socket_;
80     java.io.InputStream JavaDoc rawSocketInputStream_;
81     java.io.OutputStream JavaDoc rawSocketOutputStream_;
82
83     String JavaDoc server_;
84     int port_;
85     public CcsidManager sourceCcsidManager_;
86     public CcsidManager targetCcsidManager_;
87     public Typdef typdef_;
88     public Typdef targetTypdef_;
89     public Typdef originalTargetTypdef_; // added to support typdef overrides
90

91     protected int svrcod_;
92
93     public int orignalTargetSqlam_ = NetConfiguration.MGRLVL_7;
94     public int targetSqlam_ = orignalTargetSqlam_;
95
96     public SqlException exceptionOpeningSocket_ = null;
97
98     //---------------------constructors/finalizer---------------------------------
99
public NetAgent(NetConnection netConnection,
100                     org.apache.derby.client.am.LogWriter logWriter) throws SqlException {
101         super(netConnection, logWriter);
102         this.netConnection_ = netConnection;
103     }
104
105     NetAgent(NetConnection netConnection,
106              org.apache.derby.client.am.LogWriter netLogWriter,
107              int loginTimeout,
108              String JavaDoc server,
109              int port) throws SqlException {
110         super(netConnection, netLogWriter);
111
112         server_ = server;
113         port_ = port;
114         netConnection_ = netConnection;
115         if (server_ == null) {
116             throw new DisconnectException(this,
117                 new ClientMessageId(SQLState.CONNECT_REQUIRED_PROPERTY_NOT_SET),
118                 "serverName");
119         }
120
121         try {
122             socket_ = (java.net.Socket JavaDoc) java.security.AccessController.doPrivileged(new OpenSocketAction(server, port));
123         } catch (java.security.PrivilegedActionException JavaDoc e) {
124             throw new DisconnectException(this,
125                 new ClientMessageId(SQLState.CONNECT_UNABLE_TO_CONNECT_TO_SERVER),
126                 new Object JavaDoc[] { e.getException().getClass().getName(), server,
127                     Integer.toString(port), e.getException().getMessage() },
128                 e.getException());
129         }
130
131         // Set TCP/IP Socket Properties
132
try {
133             if (exceptionOpeningSocket_ == null) {
134                 socket_.setTcpNoDelay(true); // disables nagles algorithm
135
socket_.setKeepAlive(true); // PROTOCOL Manual: TCP/IP connection allocation rule #2
136
socket_.setSoTimeout(loginTimeout * 1000);
137             }
138         } catch (java.net.SocketException JavaDoc e) {
139             try {
140                 socket_.close();
141             } catch (java.io.IOException JavaDoc doNothing) {
142             }
143             exceptionOpeningSocket_ = new DisconnectException(this,
144                 new ClientMessageId(SQLState.CONNECT_SOCKET_EXCEPTION),
145                 e.getMessage(), e);
146         }
147
148         try {
149             if (exceptionOpeningSocket_ == null) {
150                 rawSocketOutputStream_ = socket_.getOutputStream();
151                 rawSocketInputStream_ = socket_.getInputStream();
152             }
153         } catch (java.io.IOException JavaDoc e) {
154             try {
155                 socket_.close();
156             } catch (java.io.IOException JavaDoc doNothing) {
157             }
158             exceptionOpeningSocket_ = new DisconnectException(this,
159                 new ClientMessageId(SQLState.CONNECT_UNABLE_TO_OPEN_SOCKET_STREAM),
160                 e.getMessage(), e);
161         }
162
163         sourceCcsidManager_ = new EbcdicCcsidManager(); // delete these
164
targetCcsidManager_ = sourceCcsidManager_; // delete these
165

166         if (netConnection_.isXAConnection()) {
167             NetXAConnectionReply netXAConnectionReply_ = new NetXAConnectionReply(this, netConnection_.commBufferSize_);
168             netResultSetReply_ = (NetResultSetReply) netXAConnectionReply_;
169             netStatementReply_ = (NetStatementReply) netResultSetReply_;
170             netPackageReply_ = (NetPackageReply) netStatementReply_;
171             netConnectionReply_ = (NetConnectionReply) netPackageReply_;
172             reply_ = (Reply) netConnectionReply_;
173
174             resultSetReply_ = new ResultSetReply(this,
175                     netResultSetReply_,
176                     netStatementReply_,
177                     netConnectionReply_);
178             statementReply_ = (StatementReply) resultSetReply_;
179             packageReply_ = (ConnectionReply) statementReply_;
180             connectionReply_ = (ConnectionReply) packageReply_;
181             NetXAConnectionRequest netXAConnectionRequest_ = new NetXAConnectionRequest(this, sourceCcsidManager_, netConnection_.commBufferSize_);
182             netResultSetRequest_ = (NetResultSetRequest) netXAConnectionRequest_;
183             netStatementRequest_ = (NetStatementRequest) netResultSetRequest_;
184             netPackageRequest_ = (NetPackageRequest) netStatementRequest_;
185             netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_;
186             request_ = (Request) netConnectionRequest_;
187
188             resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_;
189             statementRequest_ = (StatementRequestInterface) netStatementRequest_;
190             packageRequest_ = (NetConnectionRequest) netPackageRequest_;
191             connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_;
192         } else {
193             netResultSetReply_ = new NetResultSetReply(this, netConnection_.commBufferSize_);
194             netStatementReply_ = (NetStatementReply) netResultSetReply_;
195             netPackageReply_ = (NetPackageReply) netStatementReply_;
196             netConnectionReply_ = (NetConnectionReply) netPackageReply_;
197             reply_ = (Reply) netConnectionReply_;
198
199             resultSetReply_ = new ResultSetReply(this,
200                     netResultSetReply_,
201                     netStatementReply_,
202                     netConnectionReply_);
203             statementReply_ = (StatementReply) resultSetReply_;
204             packageReply_ = (ConnectionReply) statementReply_;
205             connectionReply_ = (ConnectionReply) packageReply_;
206             netResultSetRequest_ = new NetResultSetRequest(this, sourceCcsidManager_, netConnection_.commBufferSize_);
207             netStatementRequest_ = (NetStatementRequest) netResultSetRequest_;
208             netPackageRequest_ = (NetPackageRequest) netStatementRequest_;
209             netConnectionRequest_ = (NetConnectionRequest) netPackageRequest_;
210             request_ = (Request) netConnectionRequest_;
211
212             resultSetRequest_ = (ResultSetRequestInterface) netResultSetRequest_;
213             statementRequest_ = (StatementRequestInterface) netStatementRequest_;
214             packageRequest_ = (NetConnectionRequest) netPackageRequest_;
215             connectionRequest_ = (ConnectionRequestInterface) netConnectionRequest_;
216         }
217     }
218
219     protected void resetAgent_(org.apache.derby.client.am.LogWriter netLogWriter,
220                                //CcsidManager sourceCcsidManager,
221
//CcsidManager targetCcsidManager,
222
int loginTimeout,
223                                String JavaDoc server,
224                                int port) throws SqlException {
225
226         // most properties will remain unchanged on connect reset.
227
targetTypdef_ = originalTargetTypdef_;
228         svrcod_ = 0;
229
230         // Set TCP/IP Socket Properties
231
try {
232             socket_.setSoTimeout(loginTimeout * 1000);
233         } catch (java.net.SocketException JavaDoc e) {
234             try {
235                 socket_.close();
236             } catch (java.io.IOException JavaDoc doNothing) {
237             }
238             throw new SqlException(logWriter_,
239                 new ClientMessageId(SQLState.SOCKET_EXCEPTION),
240                 e.getMessage(), e);
241         }
242     }
243
244
245     void setSvrcod(int svrcod) {
246         if (svrcod > svrcod_) {
247             svrcod_ = svrcod;
248         }
249     }
250
251     void clearSvrcod() {
252         svrcod_ = CodePoint.SVRCOD_INFO;
253     }
254
255     int getSvrcod() {
256         return svrcod_;
257     }
258
259     public void flush_() throws DisconnectException {
260         sendRequest();
261         reply_.initialize();
262     }
263
264     // Close socket and its streams.
265
public void close_() throws SqlException {
266         // can we just close the socket here, do we need to close streams individually
267
SqlException accumulatedExceptions = null;
268         if (rawSocketInputStream_ != null) {
269             try {
270                 rawSocketInputStream_.close();
271             } catch (java.io.IOException JavaDoc e) {
272                 // note when {6} = 0 it indicates the socket was closed.
273
// this should be ok since we are going to go an close the socket
274
// immediately following this call.
275
// changing {4} to e.getMessage() may require pub changes
276
accumulatedExceptions = new SqlException(logWriter_,
277                     new ClientMessageId(SQLState.COMMUNICATION_ERROR),
278                     e.getMessage(), e);
279             } finally {
280                 rawSocketInputStream_ = null;
281             }
282         }
283
284         if (rawSocketOutputStream_ != null) {
285             try {
286                 rawSocketOutputStream_.close();
287             } catch (java.io.IOException JavaDoc e) {
288                 // note when {6} = 0 it indicates the socket was closed.
289
// this should be ok since we are going to go an close the socket
290
// immediately following this call.
291
// changing {4} to e.getMessage() may require pub changes
292
SqlException latestException = new SqlException(logWriter_,
293                     new ClientMessageId(SQLState.COMMUNICATION_ERROR),
294                     e.getMessage(), e);
295                 accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions);
296             } finally {
297                 rawSocketOutputStream_ = null;
298             }
299         }
300
301         if (socket_ != null) {
302             try {
303                 socket_.close();
304             } catch (java.io.IOException JavaDoc e) {
305                 // again {6} = 0, indicates the socket was closed.
306
// maybe set {4} to e.getMessage().
307
// do this for now and but may need to modify or
308
// add this to the message pubs.
309
SqlException latestException = new SqlException(logWriter_,
310                     new ClientMessageId(SQLState.COMMUNICATION_ERROR),
311                         e.getMessage(), e);
312                 accumulatedExceptions = Utils.accumulateSQLException(latestException, accumulatedExceptions);
313             } finally {
314                 socket_ = null;
315             }
316         }
317
318         if (accumulatedExceptions != null) {
319             throw accumulatedExceptions;
320         }
321     }
322
323     /**
324      * Specifies the maximum blocking time that should be used when sending
325      * and receiving messages. The timeout is implemented by using the the
326      * underlying socket implementation's timeout support.
327      *
328      * Note that the support for timeout on sockets is dependent on the OS
329      * implementation. For the same reason we ignore any exceptions thrown
330      * by the call to the socket layer.
331      *
332      * @param timeout The timeout value in seconds. A value of 0 corresponds to
333      * infinite timeout.
334      */

335     protected void setTimeout(int timeout) {
336         try {
337             // Sets a timeout on the socket
338
socket_.setSoTimeout(timeout * 1000); // convert to milliseconds
339
} catch (SocketException JavaDoc se) {
340             // Silently ignore any exceptions from the socket layer
341
if (SanityManager.DEBUG) {
342                 System.out.println("NetAgent.setTimeout: ignoring exception: " +
343                                    se);
344             }
345         }
346     }
347
348     /**
349      * Returns the current timeout value that is set on the socket.
350      *
351      * Note that the support for timeout on sockets is dependent on the OS
352      * implementation. For the same reason we ignore any exceptions thrown
353      * by the call to the socket layer.
354      *
355      * @return The timeout value in seconds. A value of 0 corresponds to
356      * that no timeout is specified on the socket.
357      */

358     protected int getTimeout() {
359         int timeout = 0; // 0 is default timeout for sockets
360

361         // Read the timeout currently set on the socket
362
try {
363             timeout = socket_.getSoTimeout();
364         } catch (SocketException JavaDoc se) {
365             // Silently ignore any exceptions from the socket layer
366
if (SanityManager.DEBUG) {
367                 System.out.println("NetAgent.getTimeout: ignoring exception: " +
368                                    se);
369             }
370         }
371
372         // Convert from milliseconds to seconds (note that this truncates
373
// the results towards zero but that should not be a problem).
374
timeout = timeout / 1000;
375         return timeout;
376     }
377
378     protected void sendRequest() throws DisconnectException {
379         try {
380             request_.flush(rawSocketOutputStream_);
381         } catch (java.io.IOException JavaDoc e) {
382             throwCommunicationsFailure(e);
383         }
384     }
385
386     public java.io.InputStream JavaDoc getInputStream() {
387         return rawSocketInputStream_;
388     }
389
390     public java.io.OutputStream JavaDoc getOutputStream() {
391         return rawSocketOutputStream_;
392     }
393
394     void setInputStream(java.io.InputStream JavaDoc inputStream) {
395         rawSocketInputStream_ = inputStream;
396     }
397
398     void setOutputStream(java.io.OutputStream JavaDoc outputStream) {
399         rawSocketOutputStream_ = outputStream;
400     }
401
402     public void throwCommunicationsFailure(Throwable JavaDoc cause)
403         throws org.apache.derby.client.am.DisconnectException {
404         //org.apache.derby.client.am.DisconnectException
405
//accumulateReadExceptionAndDisconnect
406
// note when {6} = 0 it indicates the socket was closed.
407
// need to still validate any token values against message publications.
408
accumulateChainBreakingReadExceptionAndThrow(
409             new org.apache.derby.client.am.DisconnectException(this,
410                 new ClientMessageId(SQLState.COMMUNICATION_ERROR),
411                 cause.getMessage(), cause));
412     }
413         
414     // ----------------------- call-down methods ---------------------------------
415

416     public org.apache.derby.client.am.LogWriter newLogWriter_(java.io.PrintWriter JavaDoc printWriter,
417                                                               int traceLevel) {
418         return new NetLogWriter(printWriter, traceLevel);
419     }
420
421     protected void markChainBreakingException_() {
422         setSvrcod(CodePoint.SVRCOD_ERROR);
423     }
424
425     public void checkForChainBreakingException_() throws SqlException {
426         int svrcod = getSvrcod();
427         clearSvrcod();
428         if (svrcod > CodePoint.SVRCOD_WARNING) // Not for SQL warning, if svrcod > WARNING, then its a chain breaker
429
{
430             super.checkForExceptions(); // throws the accumulated exceptions, we'll always have at least one.
431
}
432     }
433
434     private void writeDeferredResetConnection() throws SqlException {
435         if (!netConnection_.resetConnectionAtFirstSql_) {
436             return;
437         }
438         try {
439             netConnection_.writeDeferredReset();
440         } catch (SqlException sqle) {
441             DisconnectException de = new DisconnectException(this,
442                 new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET));
443             de.setNextException(sqle);
444             throw de;
445         }
446     }
447
448     public void beginWriteChainOutsideUOW() throws SqlException {
449         request_.initialize();
450         writeDeferredResetConnection();
451         super.beginWriteChainOutsideUOW();
452     }
453
454     public void beginWriteChain(org.apache.derby.client.am.Statement statement) throws SqlException {
455         request_.initialize();
456         writeDeferredResetConnection();
457         super.beginWriteChain(statement);
458     }
459
460     protected void endWriteChain() {
461         super.endWriteChain();
462     }
463
464     private void readDeferredResetConnection() throws SqlException {
465         if (!netConnection_.resetConnectionAtFirstSql_) {
466             return;
467         }
468         try {
469             netConnection_.readDeferredReset();
470             checkForExceptions();
471         } catch (SqlException sqle) {
472             DisconnectException de = new DisconnectException(this,
473                 new ClientMessageId(SQLState.CONNECTION_FAILED_ON_DEFERRED_RESET));
474             de.setNextException(sqle);
475             throw de;
476         }
477     }
478
479     protected void beginReadChain(org.apache.derby.client.am.Statement statement) throws SqlException {
480         readDeferredResetConnection();
481         super.beginReadChain(statement);
482     }
483
484     protected void beginReadChainOutsideUOW() throws SqlException {
485         readDeferredResetConnection();
486         super.beginReadChainOutsideUOW();
487     }
488
489     public void endReadChain() throws SqlException {
490         super.endReadChain();
491     }
492
493
494     public String JavaDoc convertToStringTcpIpAddress(int tcpIpAddress) {
495         StringBuffer JavaDoc ipAddrBytes = new StringBuffer JavaDoc();
496         ipAddrBytes.append((tcpIpAddress >> 24) & 0xff);
497         ipAddrBytes.append(".");
498         ipAddrBytes.append((tcpIpAddress >> 16) & 0xff);
499         ipAddrBytes.append(".");
500         ipAddrBytes.append((tcpIpAddress >> 8) & 0xff);
501         ipAddrBytes.append(".");
502         ipAddrBytes.append((tcpIpAddress) & 0xff);
503
504         return ipAddrBytes.toString();
505     }
506
507     protected int getPort() {
508         return port_;
509     }
510
511 }
512
513
514
Popular Tags