KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SimpleNetworkServerSample


1 /*
2
3    Derby - Class SimpleNetworkServerSample
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 import java.sql.*;
23 import javax.sql.DataSource JavaDoc;
24 import org.apache.derby.drda.NetworkServerControl;
25 import java.util.Properties JavaDoc;
26 import java.io.BufferedReader JavaDoc;
27 import java.io.InputStreamReader JavaDoc;
28
29 /**
30  * In order for a database to be consistent, only one JVM is allowed
31  * to access it at a time. The embedded driver is loaded when the Network Server
32  * is started. Hence, the JVM that starts the Network Server can get an
33  * embedded connection to the same database that Network Server is accessing
34  * to serve the clients from other JVMs. This solution allows you to take
35  * advantage of the performance benefits of embedded driver as well as allow
36  * for client connections from other JVMs to connect to the same database.
37  *
38  *
39  * In particular,this sample program
40  * 1) starts the Derby Network Server using a property and
41  * also loads the embedded driver
42  * 2) checks if the Derby Network Server is up and running
43  * 3) creates the database 'NSSimpleDB' if not already created
44  * 4) obtains an embedded database connection
45  * 5) tests the database connection by executing a sample query
46  * 6) allows for client connections to connect to the server until
47  * the user decides to stop the server and exit the program
48  * 7) closes the connections
49  * 8) shuts down the Derby Network Server before exiting the program.
50  *
51  * Note, on running this program, there will be a NSSimpleDB database directory
52  * created if not present already and there will be a derby.log file which
53  * contains messages from Derby
54  *
55  * <P>
56  * Usage: java SimpleNetworkServerSample
57  *
58  */

59 public class SimpleNetworkServerSample
60 {
61
62     /*
63      * The database is located in the same directory where this program is being
64      * run. Alternately one can specify the absolute path of the database location
65      */

66     private static String JavaDoc DBNAME="NSSimpleDB";
67
68
69     public static void main (String JavaDoc[] args)
70         throws Exception JavaDoc
71     {
72         Connection embeddedConn = null;
73
74         try
75         {
76             startNetworkServer();
77
78             /*
79               Can now spawn threads to do many wonderous things with
80               embedded connections but allow others to connect via
81               Network Server. But for sample purposes, an embedded connection
82               will be obtained and a sample query executed before waiting for
83               the user to give input to shutdown the server.
84             */

85
86         }
87         catch (Exception JavaDoc e)
88         {
89             System.out.println("Failed to start NetworkServer: " + e);
90             System.exit(1);
91         }
92
93         try
94         {
95             // get an embedded connection
96
// Since Network Server was started in this jvm, this JVM can get an embedded
97
// connection to the same database that Network Server
98
// is accessing to serve clients from other JVM's.
99
// The embedded connection will be faster than going across the
100
// network
101
embeddedConn = getEmbeddedConnection(DBNAME,"create=true;");
102             System.out.println("Got an embedded connection.");
103
104
105             System.out.println("Testing embedded connection by executing a sample query ");
106             // test connections by doing some work
107
test(embeddedConn);
108
109             // print how to connect to the network server using ij
110
String JavaDoc howToConnect = ijUsage();
111             System.out.println(howToConnect);
112
113             waitForExit();
114
115         }
116         catch (SQLException sqle)
117         {
118             System.out.println("Failure making connection: " + sqle);
119             sqle.printStackTrace();
120         }
121         finally
122         {
123
124             if(embeddedConn != null)
125                 embeddedConn.close();
126             try
127             {
128                 // shutdown Derby Network Server
129
DriverManager.getConnection("jdbc:derby:;shutdown=true");
130             }
131             catch(SQLException se)
132             {
133                 //ignore se
134
}
135
136         }
137
138     }
139
140     /**
141      * Setting the derby.drda.startNetworkServer property to true,
142      * either in the System properties as we do here or in
143      * the derby.properties file will cause Network Server to
144      * start as soon as Derby is loaded.
145      *
146      * To load Derby we just need to load the embedded
147      * Driver with:
148      * Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
149      *
150      * Then we will test for a while and make sure it is up, before
151      * we give up.
152      *
153      * Alternately Network Server might be started from the command
154      * line or from some other program. Note: only the JVM that starts
155      * Network Server can make an embedded connection.
156      */

157
158     public static void startNetworkServer() throws Exception JavaDoc
159     {
160         // Start network server using the property
161
// and then wait for the server to start by testing a connection
162
startWithProperty();
163         waitForStart();
164     }
165
166     /**
167      * Start Derby Network Server using the property
168      * derby.drda.startNetworkServer. This property can be set as a system property or
169      * or by setting in derby.properties file.
170      * Setting this property to true , starts the Network Server when
171      * Derby boots up.
172      * The port at which the Derby Network Server listens to can be changed
173      * by setting the derby.drda.portNumber property. By default, the server starts
174      * at port 1527
175      * Server output goes to derby.log
176      */

177
178     private static void startWithProperty() throws Exception JavaDoc
179     {
180         System.out.println("Starting Network Server");
181         System.setProperty("derby.drda.startNetworkServer","true");
182
183         // Booting derby
184
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
185     }
186
187
188
189     /**
190      * Tries to check if the Network Server is up and running by calling ping
191      * If successful, then it returns else tries for 50 seconds before giving up and throwing
192      * an exception.
193      * @throws Exception when there is a problem with testing if the Network Server is up
194      * and running
195      */

196     private static void waitForStart() throws Exception JavaDoc
197     {
198
199         // Server instance for testing connection
200
org.apache.derby.drda.NetworkServerControl server = null;
201
202         // Use NetworkServerControl.ping() to wait for
203
// NetworkServer to come up. We could have used
204
// NetworkServerControl to start the server but the property is
205
// easier.
206
server = new NetworkServerControl();
207
208         System.out.println("Testing if Network Server is up and running!");
209         for (int i = 0; i < 10 ; i ++)
210         {
211             try {
212
213                 Thread.currentThread().sleep(5000);
214                 server.ping();
215             }
216             catch (Exception JavaDoc e)
217             {
218                 System.out.println("Try #" + i + " " +e.toString());
219                 if (i == 9 )
220                 {
221                     System.out.println("Giving up trying to connect to Network Server!");
222                     throw e;
223                 }
224             }
225         }
226         System.out.println("Derby Network Server now running");
227
228     }
229
230     /**
231      * Used to return an embedded Derby connection
232      * The protocol used is "jdbc:derby:dbName" where dbName is the database name
233      * @pre the derby embedded jdbc driver must be loaded before calling this method
234      * Alternately, if the derby network server is started in this jvm, then the embedded driver
235      * org.apache.derby.jdbc.EmbeddedDriver is already loaded and it need not be loaded again.
236      * @param dbName database name (ie location of the database)
237      * @param attributes attributes for the database connection
238      * example, create=true;
239      * upgrade=true;
240      * @return returns embedded database connection
241      * @throws Exception if there is any error
242      */

243     public static Connection getEmbeddedConnection(String JavaDoc database,String JavaDoc attributes)
244         throws Exception JavaDoc
245     {
246         String JavaDoc dbUrl = "jdbc:derby:"+database +";"+attributes;
247         Connection conn = DriverManager.getConnection(dbUrl);
248         return conn;
249     }
250
251
252
253     /**
254      * Test a connection by executing a sample query
255      * @param conn database connection
256      * @throws Exception if there is any error
257      */

258     public static void test(Connection conn)
259         throws Exception JavaDoc
260     {
261
262       Statement stmt = null;
263       ResultSet rs = null;
264       try
265       {
266         // To test our connection, we will try to do a select from the system catalog tables
267
stmt = conn.createStatement();
268         rs = stmt.executeQuery("select count(*) from sys.systables");
269         while(rs.next())
270             System.out.println("number of rows in sys.systables = "+ rs.getInt(1));
271
272       }
273       catch(SQLException sqle)
274       {
275           System.out.println("SQLException when querying on the database connection; "+ sqle);
276           throw sqle;
277       }
278       finally
279       {
280           if(rs != null)
281             rs.close();
282           if(stmt != null)
283             stmt.close();
284       }
285
286     }
287
288
289     /**
290      * This method waits until the user hits enter to stop the server
291      * and eventually exit this program
292      * Allows clients to continue to connect using client connections from other
293      * jvms to Derby Network Server that was started in this program
294      */

295     private static void waitForExit() throws Exception JavaDoc
296     {
297         System.out.println("Clients can continue to connect: ");
298         BufferedReader JavaDoc in =
299             new BufferedReader JavaDoc(new InputStreamReader JavaDoc(System.in));
300         System.out.println("Press [Enter] to stop Server");
301         in.readLine();
302     }
303
304     /**
305      * Returns a string with information as to how to connect to Derby Network Server
306      */

307     private static String JavaDoc ijUsage()
308     {
309
310         String JavaDoc ijUsage = "\nWhile my app is busy with embedded work, ";
311         ijUsage += "ij might connect like this:\n\n";
312         ijUsage += "\t$ java -Dij.user=me -Dij.password=pw -Dij.protocol=jdbc:derby://localhost:1527/ org.apache.derby.tools.ij\n";
313         ijUsage += "\tij> connect '" + DBNAME + "';\n\n";
314
315         return ijUsage;
316     }
317 }
318
319
320
321
322
323
324
Popular Tags