KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SimpleNetworkClientSample


1 /*
2
3    Derby - Class SimpleNetworkClientSample
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.lang.reflect.InvocationTargetException JavaDoc;
23 import java.lang.reflect.Method JavaDoc;
24 import java.sql.Connection JavaDoc;
25 import java.sql.DriverManager JavaDoc;
26 import java.sql.ResultSet JavaDoc;
27 import java.sql.SQLException JavaDoc;
28 import java.sql.Statement JavaDoc;
29 import java.util.Properties JavaDoc;
30
31 import javax.sql.DataSource JavaDoc;
32
33 /**
34  * The primary purpose of this program is to demonstrate how to obtain
35  * client connections using DriverManager or a DataSource
36  * and interact with Derby Network Server
37  *
38  * In particular,this sample program
39  * 1) loads the DB2 Universal JDBC Driver or the Derby Network Client driver
40    (default is the derby network client driver)
41  * 2) obtains a client connection using the Driver Manager
42  * 3) obtains a client connection using a DataSource
43  * 4) tests the database connections by executing a sample query
44  * and then exits the program
45  *
46  * Before running this program, please make sure that Clouscape Network Server is up
47  * and running.
48  * <P>
49  * Usage: java SimpleNetworkClientSample
50  *
51  */

52 public class SimpleNetworkClientSample
53 {
54
55     /*
56      * The database is located in the same directory where this program is being
57      * run. Alternately one can specify the absolute path of the database location
58      */

59     private static String JavaDoc DBNAME="NSSampleDB";
60
61     /**
62      * Derby network server port ; default is 1527
63      */

64     private static int NETWORKSERVER_PORT=1527;
65
66     /**
67      * DB2 JDBC UNIVERSAL DRIVER class names
68      */

69     private static final String JavaDoc DB2_JDBC_UNIVERSAL_DRIVER = "com.ibm.db2.jcc.DB2Driver";
70     private static final String JavaDoc DB2_JCC_DS = "com.ibm.db2.jcc.DB2SimpleDataSource";
71     /**
72      * Derby Network Client Driver class names
73      */

74
75 public static final String JavaDoc DERBY_CLIENT_DRIVER = "org.apache.derby.jdbc.ClientDriver";
76     private static final String JavaDoc DERBY_CLIENT_DS = "org.apache.derby.jdbc.ClientDataSource";
77
78     /**
79      * This URL is used to connect to Derby Network Server using the DriverManager.
80      * This URL is for the DB2 JDBC Universal Driver
81      * Notice that the properties may be established via the URL syntax
82      */

83     private static final String JavaDoc CS_NS_DBURL= "jdbc:derby:net://localhost:"+NETWORKSERVER_PORT+"/"+DBNAME+";retrieveMessagesFromServerOnGetMessage=true;deferPrepares=true;";
84
85         // URL for the Derby client JDBC driver.
86
private static final String JavaDoc DERBY_CLIENT_URL= "jdbc:derby://localhost:"+ NETWORKSERVER_PORT+"/"+DBNAME+";create=true";
87
88         // Default to using the Derby Client JDBC Driver for database connections
89
String JavaDoc url = DERBY_CLIENT_URL;
90         String JavaDoc jdbcDriver = DERBY_CLIENT_DRIVER;
91         String JavaDoc jdbcDataSource = DERBY_CLIENT_DS;
92
93     public static void main (String JavaDoc[] args) throws Exception JavaDoc
94         {
95
96                    new SimpleNetworkClientSample().startSample(args);
97
98         }
99     public void startSample (String JavaDoc[] args) throws Exception JavaDoc
100     {
101         DataSource JavaDoc clientDataSource = null;
102         Connection JavaDoc clientConn1 = null;
103         Connection JavaDoc clientConn2 = null;
104
105
106         try
107         {
108             System.out.println("Starting Sample client program ");
109                         // Determine which JDBC driver to use
110
parseArguments(args);
111
112             // load the appropriate JDBC Driver
113
loadDriver();
114
115             // get a client connection using DriverManager
116
clientConn1 = getClientDriverManagerConnection();
117             System.out.println("Got a client connection via the DriverManager.");
118
119             // create a datasource with the necessary information
120
javax.sql.DataSource JavaDoc myDataSource = getClientDataSource(DBNAME, null, null);
121
122             // get a client connection using DataSource
123
clientConn2 = getClientDataSourceConn(myDataSource);
124             System.out.println("Got a client connection via a DataSource.");
125
126             // test connections by doing some work
127
System.out.println("Testing the connection obtained via DriverManager by executing a sample query ");
128             test(clientConn1);
129             System.out.println("Testing the connection obtained via a DataSource by executing a sample query ");
130             test(clientConn2);
131
132             System.out.println("Goodbye!");
133         }
134         catch (SQLException JavaDoc sqle)
135         {
136             System.out.println("Failure making connection: " + sqle);
137             sqle.printStackTrace();
138         }
139         finally
140         {
141
142             if(clientConn1 != null)
143                 clientConn1.close();
144             if(clientConn2 != null)
145                 clientConn2.close();
146         }
147     }
148
149     /**
150      * Get a database connection from DataSource
151      * @pre Derby Network Server is started
152      * @param ds data source
153      * @return returns database connection
154      * @throws Exception if there is any error
155      */

156     public Connection JavaDoc getClientDataSourceConn(javax.sql.DataSource JavaDoc ds)
157         throws Exception JavaDoc
158     {
159         Connection JavaDoc conn = ds.getConnection("usr2", "pass2");
160         System.out.print("connection from datasource; getDriverName = ");
161         System.out.println(conn.getMetaData().getDriverName());
162         return conn;
163     }
164
165     /**
166      * Creates a client data source and sets all the necessary properties in order to
167      * connect to Derby Network Server
168      * The server is assumed to be running on 1527 and on the localhost
169      * @param database database name; can include Derby URL attributes
170      * @param user database user
171      * @param password
172      * @return returns DataSource
173      * @throws Exception if there is any error
174      */

175     public javax.sql.DataSource JavaDoc getClientDataSource(String JavaDoc database, String JavaDoc user, String JavaDoc
176                                       password) throws SQLException JavaDoc, ClassNotFoundException JavaDoc, InstantiationException JavaDoc, IllegalAccessException JavaDoc, NoSuchMethodException JavaDoc, InvocationTargetException JavaDoc
177     {
178         Class JavaDoc nsDataSource = Class.forName(jdbcDataSource);
179         DataSource JavaDoc ds = (DataSource JavaDoc) nsDataSource.newInstance();
180
181         // can also include Derby URL attributes along with the database name
182
Class JavaDoc[] methodParams = new Class JavaDoc[] {String JavaDoc.class};
183         Method JavaDoc dbname = nsDataSource.getMethod("setDatabaseName", methodParams);
184         Object JavaDoc[] args = new Object JavaDoc[] {database};
185         dbname.invoke(ds, args);
186
187         if (user != null) {
188             Method JavaDoc setuser = nsDataSource.getMethod("setUser", methodParams);
189             args = new Object JavaDoc[] {user};
190             setuser.invoke(ds, args);
191         }
192         if (password != null) {
193             Method JavaDoc setpw = nsDataSource.getMethod("setPassword", methodParams);
194             args = new Object JavaDoc[] {password};
195             setpw.invoke(ds, args);
196         }
197         // host on which network server is running
198
Method JavaDoc servername = nsDataSource.getMethod("setServerName", methodParams);
199         args = new Object JavaDoc[] {"localhost"};
200         servername.invoke(ds, args);
201
202         // port on which Network Server is listening
203
methodParams = new Class JavaDoc[] {int.class};
204         Method JavaDoc portnumber = nsDataSource.getMethod("setPortNumber", methodParams);
205         args = new Object JavaDoc[] {new Integer JavaDoc(1527)};
206         portnumber.invoke(ds, args);
207
208                 // The following is only applicable to the DB2 JDBC driver
209
if(jdbcDataSource.equals( DB2_JCC_DS))
210                 {
211             // driver type must be 4 to access Derby Network Server
212
Method JavaDoc drivertype = nsDataSource.getMethod("setDriverType", methodParams);
213             args = new Object JavaDoc[] {new Integer JavaDoc(4)};
214             drivertype.invoke(ds, args);
215                 }
216
217         return ds;
218
219     }
220
221
222     /**
223      * Load the appropriate JDBC driver
224      */

225     public void loadDriver()
226         throws Exception JavaDoc
227     {
228         // Load the Driver
229
Class.forName(jdbcDriver).newInstance();
230     }
231
232     /**
233      * Get a client connection using the DriverManager
234      * @pre The JDBC driver must have been loaded before calling this method
235      * @return Connection client database connection
236      */

237     public Connection JavaDoc getClientDriverManagerConnection()
238         throws Exception JavaDoc
239     {
240
241         // See Derby documentation for description of properties that may be set
242
// in the context of the network server.
243
Properties JavaDoc properties = new java.util.Properties JavaDoc();
244
245         // The user and password properties are a must, required by JCC
246
properties.setProperty("user","cloud");
247         properties.setProperty("password","scape");
248
249         // Get database connection via DriverManager api
250
Connection JavaDoc conn = DriverManager.getConnection(url,properties);
251
252         return conn;
253     }
254
255
256     /**
257      * Test a connection by executing a sample query
258      * @param conn database connection
259      * @throws Exception if there is any error
260      */

261     public void test(Connection JavaDoc conn)
262         throws Exception JavaDoc
263     {
264
265       Statement JavaDoc stmt = null;
266       ResultSet JavaDoc rs = null;
267       try
268       {
269         // To test our connection, we will try to do a select from the system catalog tables
270
stmt = conn.createStatement();
271         rs = stmt.executeQuery("select count(*) from sys.systables");
272         while(rs.next())
273             System.out.println("number of rows in sys.systables = "+ rs.getInt(1));
274
275       }
276       catch(SQLException JavaDoc sqle)
277       {
278           System.out.println("SQLException when querying on the database connection; "+ sqle);
279           throw sqle;
280       }
281       finally
282       {
283           if(rs != null)
284             rs.close();
285           if(stmt != null)
286             stmt.close();
287       }
288     }
289    /**
290      * Determine which jdbc driver to use by parsing the command line args.
291      * Accepted values:
292      * jccjdbclient - The DB2 type 4 universal driver
293      * derbyclient - The Derby network driver (default).
294      * Note: because this is just a sample, we only care about whether
295      * the above values are specified. If they are not, then we default
296      * to the Derby network driver.
297      */

298     private void parseArguments(String JavaDoc[] args)
299     {
300         int length = args.length;
301
302         for (int index = 0; index < length; index++)
303         {
304             if (args[index].equalsIgnoreCase("jccjdbcclient"))
305             {
306
307                 jdbcDriver = DB2_JDBC_UNIVERSAL_DRIVER;
308                 jdbcDataSource = DB2_JCC_DS;
309                 url = CS_NS_DBURL;
310                 break;
311             } else if (args[index].equalsIgnoreCase("derbyClient"))
312             {
313                 jdbcDriver = DERBY_CLIENT_DRIVER;
314                 jdbcDataSource = DERBY_CLIENT_DS;
315                 url = DERBY_CLIENT_URL;
316                 break;
317             }
318         }
319     }
320
321 }
322
323
324
325
326
327
328
Popular Tags