KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hsqldb > HSQLClientConnection


1 /* Copyright (c) 2001-2005, The HSQL Development Group
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * Redistributions of source code must retain the above copyright notice, this
8  * list of conditions and the following disclaimer.
9  *
10  * Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  *
14  * Neither the name of the HSQL Development Group nor the names of its
15  * contributors may be used to endorse or promote products derived from this
16  * software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
22  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */

30
31
32 package org.hsqldb;
33
34 import java.io.BufferedInputStream JavaDoc;
35 import java.io.BufferedOutputStream JavaDoc;
36 import java.io.DataInputStream JavaDoc;
37 import java.io.IOException JavaDoc;
38 import java.io.OutputStream JavaDoc;
39 import java.net.Socket JavaDoc;
40
41 import org.hsqldb.lib.ArrayUtil;
42 import org.hsqldb.rowio.RowInputBinary;
43 import org.hsqldb.rowio.RowOutputBinary;
44 import org.hsqldb.store.ValuePool;
45
46 /**
47  * Base remote session proxy implementation. Uses instances of Result to
48  * transmit and recieve data. This implementation utilises the updated HSQL
49  * protocol.
50  *
51  * @author fredt@users
52  * @version 1.8.0
53  * @since 1.7.2
54  */

55 public class HSQLClientConnection implements SessionInterface {
56
57     static final int BUFFER_SIZE = 0x1000;
58     final byte[] mainBuffer = new byte[BUFFER_SIZE];
59     private boolean isClosed;
60     private Socket JavaDoc socket;
61     protected OutputStream JavaDoc dataOutput;
62     protected DataInputStream JavaDoc dataInput;
63     protected RowOutputBinary rowOut;
64     protected RowInputBinary rowIn;
65     private Result resultOut;
66     private int sessionID;
67
68     //
69
private boolean isReadOnly = false;
70     private boolean isAutoCommit = true;
71
72     //
73
String JavaDoc host;
74     int port;
75     String JavaDoc path;
76     String JavaDoc database;
77     boolean isTLS;
78     int databaseID;
79
80     public HSQLClientConnection(String JavaDoc host, int port, String JavaDoc path,
81                                 String JavaDoc database, boolean isTLS, String JavaDoc user,
82                                 String JavaDoc password) throws HsqlException {
83
84         this.host = host;
85         this.port = port;
86         this.path = path;
87         this.database = database;
88         this.isTLS = isTLS;
89
90         initStructures();
91
92         Result login = new Result(ResultConstants.SQLCONNECT);
93
94         login.mainString = user;
95         login.subString = password;
96         login.subSubString = database;
97
98         initConnection(host, port, isTLS);
99
100         Result resultIn = execute(login);
101
102         if (resultIn.isError()) {
103
104 /** @todo fredt - review error message */
105             throw Trace.error(resultIn);
106         }
107
108         sessionID = resultIn.sessionID;
109         databaseID = resultIn.databaseID;
110     }
111
112     /**
113      * resultOut is reused to trasmit all remote calls for session management.
114      * Here the structure is preset for sending attributes.
115      */

116     private void initStructures() {
117
118         rowOut = new RowOutputBinary(mainBuffer);
119         rowIn = new RowInputBinary(rowOut);
120         resultOut = Result.newSessionAttributesResult();
121
122         resultOut.add(new Object JavaDoc[7]);
123     }
124
125     protected void initConnection(String JavaDoc host, int port,
126                                   boolean isTLS) throws HsqlException {
127         openConnection(host, port, isTLS);
128     }
129
130     protected void openConnection(String JavaDoc host, int port,
131                                   boolean isTLS) throws HsqlException {
132
133         try {
134             socket = HsqlSocketFactory.getInstance(isTLS).createSocket(host,
135                                                    port);
136             dataOutput = new BufferedOutputStream JavaDoc(socket.getOutputStream());
137             dataInput = new DataInputStream JavaDoc(
138                 new BufferedInputStream JavaDoc(socket.getInputStream()));
139         } catch (Exception JavaDoc e) {
140
141 /** @todo fredt - change error to no connetion established */
142             throw Trace.error(Trace.SOCKET_ERROR);
143         }
144     }
145
146     protected void closeConnection() {
147
148         try {
149             if (socket != null) {
150                 socket.close();
151             }
152         } catch (Exception JavaDoc e) {}
153
154         socket = null;
155     }
156
157     public synchronized Result execute(Result r) throws HsqlException {
158
159         try {
160             r.sessionID = sessionID;
161             r.databaseID = databaseID;
162
163             write(r);
164
165             return read();
166         } catch (Throwable JavaDoc e) {
167             throw Trace.error(Trace.CONNECTION_IS_BROKEN, e.toString());
168         }
169     }
170
171     public void close() {
172
173         if (isClosed) {
174             return;
175         }
176
177         isClosed = true;
178
179         try {
180             resultOut.setResultType(ResultConstants.SQLDISCONNECT);
181             execute(resultOut);
182         } catch (Exception JavaDoc e) {}
183
184         try {
185             closeConnection();
186         } catch (Exception JavaDoc e) {}
187     }
188
189     private Object JavaDoc getAttribute(int id) throws HsqlException {
190
191         resultOut.setResultType(ResultConstants.GETSESSIONATTR);
192
193         Result in = execute(resultOut);
194
195         if (in.isError()) {
196             throw Trace.error(in);
197         }
198
199         return in.rRoot.data[id];
200     }
201
202     private void setAttribute(Object JavaDoc property, int id) throws HsqlException {
203
204         resultOut.setResultType(ResultConstants.SETSESSIONATTR);
205         ArrayUtil.fillArray(resultOut.rRoot.data, null);
206
207         resultOut.rRoot.data[id] = property;
208
209         Result resultIn = execute(resultOut);
210
211         if (resultIn.isError()) {
212             throw Trace.error(resultIn);
213         }
214     }
215
216     public boolean isReadOnly() throws HsqlException {
217
218         Object JavaDoc info = getAttribute(Session.INFO_CONNECTION_READONLY);
219
220         isReadOnly = ((Boolean JavaDoc) info).booleanValue();
221
222         return isReadOnly;
223     }
224
225     public void setReadOnly(boolean mode) throws HsqlException {
226
227         if (mode != isReadOnly) {
228             setAttribute(mode ? Boolean.TRUE
229                               : Boolean.FALSE, Session
230                                   .INFO_CONNECTION_READONLY);
231
232             isReadOnly = mode;
233         }
234     }
235
236     public boolean isAutoCommit() throws HsqlException {
237
238         Object JavaDoc info = getAttribute(SessionInterface.INFO_AUTOCOMMIT);
239
240         isAutoCommit = ((Boolean JavaDoc) info).booleanValue();
241
242         return isAutoCommit;
243     }
244
245     public void setAutoCommit(boolean mode) throws HsqlException {
246
247         if (mode != isAutoCommit) {
248             setAttribute(mode ? Boolean.TRUE
249                               : Boolean.FALSE, SessionInterface
250                                   .INFO_AUTOCOMMIT);
251
252             isAutoCommit = mode;
253         }
254     }
255
256     public void setIsolation(int level) throws HsqlException {
257         setAttribute(ValuePool.getInt(level),
258                      SessionInterface.INFO_ISOLATION);
259     }
260
261     public int getIsolation() throws HsqlException {
262
263         Object JavaDoc info = getAttribute(Session.INFO_ISOLATION);
264
265         return ((Integer JavaDoc) info).intValue();
266     }
267
268     public boolean isClosed() {
269         return isClosed;
270     }
271
272     public Session getSession() {
273         return null;
274     }
275
276     public void startPhasedTransaction() throws HsqlException {}
277
278     public void prepareCommit() throws HsqlException {
279
280         resultOut.setResultType(ResultConstants.SQLENDTRAN);
281
282         resultOut.updateCount = ResultConstants.HSQLPREPARECOMMIT;
283
284         resultOut.setMainString("");
285         execute(resultOut);
286     }
287
288     public void commit() throws HsqlException {
289
290         resultOut.setResultType(ResultConstants.SQLENDTRAN);
291
292         resultOut.updateCount = ResultConstants.COMMIT;
293
294         resultOut.setMainString("");
295         execute(resultOut);
296     }
297
298     public void rollback() throws HsqlException {
299
300         resultOut.setResultType(ResultConstants.SQLENDTRAN);
301
302         resultOut.updateCount = ResultConstants.ROLLBACK;
303
304         resultOut.setMainString("");
305         execute(resultOut);
306     }
307
308     public int getId() {
309         return sessionID;
310     }
311
312     /**
313      * Used by pooled connections to reset the server-side session to a new
314      * one. In case of failure, the connection is closed.
315      *
316      * When the Connection.close() method is called, a pooled connection calls
317      * this method instead of HSQLClientConnection.close(). It can then
318      * reuse the HSQLClientConnection object with no further initialisation.
319      *
320      */

321     public void resetSession() throws HsqlException {
322
323         Result login = new Result(ResultConstants.HSQLRESETSESSION);
324         Result resultIn = execute(login);
325
326         if (resultIn.isError()) {
327             isClosed = true;
328
329             closeConnection();
330
331             throw Trace.error(resultIn);
332         }
333
334         sessionID = resultIn.sessionID;
335         databaseID = resultIn.databaseID;
336     }
337
338     protected void write(Result r) throws IOException JavaDoc, HsqlException {
339         Result.write(r, rowOut, dataOutput);
340     }
341
342     protected Result read() throws IOException JavaDoc, HsqlException {
343
344         Result r = Result.read(rowIn, dataInput);
345
346         rowOut.setBuffer(mainBuffer);
347         rowIn.resetRow(mainBuffer.length);
348
349         return r;
350     }
351 }
352
Popular Tags