KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > nserverdemo > NsSample


1 /*
2
3    Derby - Class nserverdemo.NsSample
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 nserverdemo;
23
24
25 import java.util.Properties JavaDoc;
26 import java.sql.SQLException JavaDoc;
27 import java.sql.DriverManager JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.sql.Connection JavaDoc;
30 import java.sql.Statement JavaDoc;
31 import java.sql.ResultSet JavaDoc;
32 import java.sql.SQLException JavaDoc;
33 import java.sql.SQLWarning JavaDoc;
34 import java.io.PrintWriter JavaDoc;
35
36
37 /**
38
39  The Network Server sample demo program is a
40  simple JDBC application that interacts with the Derby Network Server.
41  The program:
42
43  1. starts the Derby Network Server
44  2. loads the IBM DB2 JDBC Universal driver or derby client JDBC driver
45         (default is the derby client JDBC driver)
46  3. creates the database if not already created
47  4. checks to see if the schema is already created, and if not,
48  5. creates the schema which includes the table SAMPLETBL and corresponding indexes.
49  6. connects to the database
50  7. loads the schema by inserting data
51  8. starts client threads to perform database related operations
52  9. has each of the clients perform DML operations (select, insert, delete, update) using JDBC calls,
53     i) one client opens an embedded connection to perform database operations
54          You can open an embedded connection in the same JVM that starts the Derby Network
55          Server.
56     ii) one client opens a client connection to the Derby Network Server to perform database operations.
57  10.waits for the client threads to finish the tasks
58  11.shuts down the Derby Network Server at the end of the demo
59
60  <P>
61  Usage: java nserverdemo.NsSample
62  <P>
63  Please note, a file derby.log is created in the directory you run this program.
64  This file contains the logging of connections made with the derby network server
65  */

66
67 public class NsSample {
68
69     public static final String JavaDoc DB2_JDBC_UNIVERSAL_DRIVER = new String JavaDoc("com.ibm.db2.jcc.DB2Driver");
70         public static final String JavaDoc DERBY_CLIENT_DRIVER = "org.apache.derby.jdbc.ClientDriver";
71     public static int NUM_ROWS = 50; /* Number of rows to load initially */
72     public static int ITERATIONS = 10; //Each client does these many iterations
73
public static int NUM_CLIENT_THREADS = 2;
74
75
76     // network server control specific
77
private static int NETWORKSERVER_PORT=1621;
78
79     // Derby database connection URL for embedded environment
80
public static final String JavaDoc CS_EMBED_DBURL="jdbc:derby:NSSampledb;";
81
82     // To connect to Derby Network Server
83
// This URL describes the target database for type 4 connectivity
84
// Notice that the properties may be established via the URL syntax
85
private static final String JavaDoc CS_NS_DBURL= "jdbc:derby:net://localhost:"+NETWORKSERVER_PORT+"/NSSampledb;create=true;retrieveMessagesFromServerOnGetMessage=true;deferPrepares=true;";
86         // URL for the Derby client JDBC driver.
87
private static final String JavaDoc DERBY_CLIENT_URL= "jdbc:derby://localhost:"+NETWORKSERVER_PORT+"/NSSampledb;create=true;";
88
89         // Default to using the Derby Client JDBC Driver for database connections
90
String JavaDoc url = DERBY_CLIENT_URL;
91         String JavaDoc jdbcDriver = DERBY_CLIENT_DRIVER;
92
93     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
94
95                    new nserverdemo.NsSample().startSample(args);
96         }
97     public void startSample(String JavaDoc[] args) throws Exception JavaDoc {
98       NetworkServerUtil nwServer;
99
100       Connection JavaDoc conn = null;
101
102       PrintWriter JavaDoc pw = null;
103           
104       
105
106       try {
107
108                 // Determine which JDBC driver we are using with Derby
109
parseArguments(args);
110
111         pw = new PrintWriter JavaDoc(System.out,true); // to print messages
112
pw.println("Using JDBC driver: " + jdbcDriver);
113
114         /* Start - In order to start the network server do the following
115            In case you want to start the server as a script or another program
116            comment out the next block of code (i.e. until the comment line 'End - network server started')
117            Also, comment out the 'Shutdown Derby Network Server' line of code at the bottom
118            In case you decide to comment out the starting of the network server, make sure that the
119            client thread is not making an embedded connection but instead making only a client connection.
120            Also note, the server logs messages to the file derby.log in the
121            directory you run this program
122          */

123
124             {
125                 nwServer = new NetworkServerUtil(NETWORKSERVER_PORT,pw);
126                 nwServer.start();
127
128                 boolean knowIfServerUp = false; //do we know if server is ready to accept connections
129
int numTimes = 5;
130
131                 // Test to see if server is ready for connections, for 15 seconds.
132
while(!knowIfServerUp && (numTimes >0)) {
133                     try {
134                         // testing for connection to see if the network server is up and running
135
// if server is not ready yet, this method will throw an exception
136
numTimes--;
137                         nwServer.testForConnection();
138                         knowIfServerUp = true;
139                     }
140                     catch(Exception JavaDoc e) {
141                         System.out.println("[NsSample] Unable to obtain a connection to network server, trying again after 3000 ms.");
142                         Thread.currentThread().sleep(3000);
143                     }
144                 }
145                 if(!knowIfServerUp) {
146                     pw.println("[NsSample] Exiting, since unable to connect to Derby Network Server.");
147                     pw.println("[NsSample] Please try to increase the amount of time to keep trying to connect to the Server.");
148                     System.exit(1);
149                 }
150
151                 pw.println("[NsSample] Derby Network Server started.");
152             }
153         /*End - network server started*/
154
155         pw.println("[NsSample] Sample Derby Network Server program demo starting. ");
156         pw.println("Please wait .....................");
157
158         // Load the JDBC Driver
159
try {
160             Class.forName(jdbcDriver).newInstance();
161         } catch (Exception JavaDoc e) {
162             pw.println("[NsSample] Unable to load the JDBC driver. Following exception was thrown");
163             e.printStackTrace();
164             System.exit(1); //critical error, so exit
165
}
166
167
168         // See Derby documentation for description of properties that may be set
169
// in the context of the network server.
170
Properties JavaDoc properties = new java.util.Properties JavaDoc();
171
172         // The user and password properties are a must, required by JCC
173
properties.setProperty("user","cloud");
174         properties.setProperty("password","scape");
175
176         // Get database connection via DriverManager api
177
try {
178             
179             conn = (Connection JavaDoc) DriverManager.getConnection(url, properties);
180         } catch(Exception JavaDoc e) {
181             pw.println("[NsSample] Connection request unsuccessful, exception thrown was: ");
182             pw.println("[NsSample] Please check if all the jar files are in the classpath and the dbUrl is set correctly.");
183             e.printStackTrace();
184             System.exit(1); //critical error, so exit
185
}
186
187         NsSampleWork.checkAndCreateSchema(conn,pw); // Check and create the necessary schema if not already created
188
NsSampleWork.loadSchema(conn,NUM_ROWS,pw); // Insert rows into the table
189
conn.close();
190
191         // Start client threads to perform database related sql operations
192
NsSampleClientThread clientThreads[] = new NsSampleClientThread[NUM_CLIENT_THREADS];
193
194
195         /* Only the JVM that starts the Derby Network Server can obtain an embedded connection
196            Please pay attention to the database URL
197            Also, you need not load the org.apache.derby.jdbc.EmbeddedDriver since it is already loaded when
198            the network server starts up.
199            1. Derby embedded database url - jdbc:derby:databasename
200         */

201         clientThreads[0] = new NsSampleClientThread(1,CS_EMBED_DBURL,properties,pw);
202         clientThreads[0].start();
203
204
205         /*
206            2. The below client threads obtain a client connection to Derby Network Server
207            One can also get a client connection from another JVM
208            Please be aware of the database URL for obtaining a client connection
209          */

210         for (int i=1; i<NUM_CLIENT_THREADS; i++) {
211             clientThreads[i] = new NsSampleClientThread(i+1,url,properties,pw);
212             clientThreads[i].start();
213
214         }
215
216         // Wait for the client threads to complete all the work
217
for (int i = 0; i < NUM_CLIENT_THREADS; i++)
218            clientThreads[i].join();
219
220          // Shutdown Derby network server
221
pw.println("[NsSample] Shutting down network server.");
222          nwServer.shutdown();
223          pw.println("[NsSample] End of Network server demo.");
224
225       } catch (Exception JavaDoc e) {
226           e.printStackTrace();
227         }
228       finally
229       {
230         if(pw != null) pw.close();
231       }
232      }
233
234     /**
235      * Determine which jdbc driver to use by parsing the command line args.
236      * Accepted values:
237      * jccjdbclient - The DB2 type 4 universal driver
238      * derbyclient - The Derby network driver (default).
239      * Note: because this is just a sample, we only care about whether
240      * the above values are specified. If they are not, then we default
241      * to the Derby network driver.
242      */

243     private void parseArguments(String JavaDoc[] args)
244     {
245         int length = args.length;
246
247         for (int index = 0; index < length; index++)
248         {
249             if (args[index].equalsIgnoreCase("jccjdbcclient"))
250             {
251                 jdbcDriver = DB2_JDBC_UNIVERSAL_DRIVER;
252                 url = CS_NS_DBURL;
253                 break;
254             } else if (args[index].equalsIgnoreCase("derbyClient"))
255             {
256                 jdbcDriver = DERBY_CLIENT_DRIVER;
257                 url = DERBY_CLIENT_URL;
258                 break;
259             }
260         }
261     }
262
263 }
264
Popular Tags