Return-Path: Delivered-To: apmail-db-derby-commits-archive@www.apache.org Received: (qmail 6617 invoked from network); 25 Apr 2005 19:29:48 -0000 Received: from hermes.apache.org (HELO mail.apache.org) (209.237.227.199) by minotaur.apache.org with SMTP; 25 Apr 2005 19:29:48 -0000 Received: (qmail 92713 invoked by uid 500); 25 Apr 2005 19:30:20 -0000 Delivered-To: apmail-db-derby-commits-archive@db.apache.org Received: (qmail 92677 invoked by uid 500); 25 Apr 2005 19:30:20 -0000 Mailing-List: contact derby-commits-help@db.apache.org; run by ezmlm Precedence: bulk list-help: list-unsubscribe: List-Post: Reply-To: "Derby Development" Delivered-To: mailing list derby-commits@db.apache.org Received: (qmail 92663 invoked by uid 500); 25 Apr 2005 19:30:20 -0000 Delivered-To: apmail-incubator-derby-cvs@incubator.apache.org Received: (qmail 92619 invoked by uid 99); 25 Apr 2005 19:30:19 -0000 X-ASF-Spam-Status: No, hits=0.2 required=10.0 tests=NO_REAL_NAME X-Spam-Check-By: apache.org Received: from minotaur.apache.org (HELO minotaur.apache.org) (209.237.227.194) by apache.org (qpsmtpd/0.28) with SMTP; Mon, 25 Apr 2005 12:30:15 -0700 Received: (qmail 6493 invoked by uid 65534); 25 Apr 2005 19:29:41 -0000 Message-ID: <20050425192941.6491.qmail@minotaur.apache.org> Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Subject: svn commit: r164630 [2/3] - in /incubator/derby/code/trunk/java/demo: ./ nserverdemo/ simple/ Date: Mon, 25 Apr 2005 19:29:38 -0000 To: derby-cvs@incubator.apache.org From: fuzzylogic@apache.org X-Mailer: svnmailer-1.0.0-dev X-Virus-Checked: Checked X-Spam-Rating: minotaur.apache.org 1.6.2 0/1000/N Modified: incubator/derby/code/trunk/java/demo/nserverdemo/NsSampleClientTh= read.java URL: http://svn.apache.org/viewcvs/incubator/derby/code/trunk/java/demo/nse= rverdemo/NsSampleClientThread.java?rev=3D164630&r1=3D164629&r2=3D164630&vie= w=3Ddiff =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D --- incubator/derby/code/trunk/java/demo/nserverdemo/NsSampleClientThread.j= ava (original) +++ incubator/derby/code/trunk/java/demo/nserverdemo/NsSampleClientThread.j= ava Mon Apr 25 12:29:37 2005 @@ -1,487 +1,487 @@ -/* - - Derby - Class nserverdemo.NsSampleClientThread - - Copyright 2003, 2004 The Apache Software Foundation or its licensors, a= s applicable. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied= . - See the License for the specific language governing permissions and - limitations under the License. - - */ - -package nserverdemo; - -import java.util.Properties; -import java.sql.SQLException; -import java.sql.DriverManager; -import java.io.IOException; -import java.sql.Statement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.io.PrintWriter; -import java.util.Properties; -import java.sql.PreparedStatement; -import java.sql.Connection; -import java.util.Random; -import java.lang.Math; -/** - * NsSampleClientThread thread to perform the NsSampleWork - */ -public class NsSampleClientThread extends Thread { - - protected int thread_id; - protected Properties properties; - protected PrintWriter pw; - protected String dbUrl; - - NsSampleClientThread(int id,String dbUrl, Properties properties,PrintWri= ter pw) { - this.thread_id=3Did; - this.dbUrl =3D dbUrl; - this.properties =3D properties; - this.pw =3D pw; - } - - public void run() { - System.out.println("[NsSampleClientThread] Thread id - "+this.thread_id = + "; started."); - NsSampleWork w =3D new NsSampleWork(this.thread_id,dbUrl,properties,pw); - w.doWork(); // do all the NsSampleWork - pw.println("[NsSampleClientThread] Thread id - "+this.thread_id+"; finis= hed all tasks."); - } -} - - - -/** - * NsSampleWork class represents all the work done in the sample demo prog= ram. - * It includes - * getting a connection to the database, creating and loading of schema, - * preparing and execution of SQL statements (insert, select, update, dele= te ) - */ -class NsSampleWork { - - protected int thread_id; - protected String dbUrl; - protected Properties properties; - PrintWriter pw; - PreparedStatement select =3D null; - PreparedStatement insert =3D null; - PreparedStatement delete =3D null; - PreparedStatement update =3D null; - PreparedStatement getMaxKey =3D null; - - - - public static int counter=3D0; - static Integer lock =3D new Integer(0); - /** - * dbUrl is the database url to connect to - */ - NsSampleWork(int id, String dbURL,Properties properties,PrintWriter pw) = { - this.thread_id =3D id; - this.dbUrl =3D dbURL; - this.pw =3D pw; - this.properties =3D properties; - } - - - /** - * gets a database connection - * If the dbUrl is trying to connect to the Derby NetNsSampleWork server= using JCC - * then the jcc driver must be already loaded before calling this method= , - * else there will be an error - * return jcc connection if no error, else null - */ - public Connection getConnection(String dbUrl, Properties properties) { - Connection conn =3D null; - try { - pw.println("[NsSampleWork] Thread id - "+thread_id + "; requests databa= se connection, dbUrl =3D"+dbUrl); - conn =3D DriverManager.getConnection(dbUrl, properties); - } catch (Exception e) { - System.out.println("[NsSampleWork] Thread id - "+ thread_id + "; faile= d to get database connection. Exception thrown:"); - e.printStackTrace(); - } - return conn; - } - - - /** - * set the connection to this isolation level - */ - public void setIsolationLevel(Connection conn, int level) { - try { - conn.setTransactionIsolation(level); - } catch (Exception e) { - pw.println("[NsSampleWork] Thread id - "+ thread_id +"; setIsolationLe= vel failed. Exception thrown: "); - e.printStackTrace(); - } - } - - - /** - * close connection - */ - public void closeConnection(Connection conn) { - try { - if(conn !=3D null) - conn.close(); - pw.println("[NsSampleWork] Thread id - "+thread_id + "; closed connecti= on to the database."); - } catch (Exception e) { - pw.println("[NsSampleWork] Thread id - "+thread_id + "; error when clo= sing connection;"+ e); - e.printStackTrace(); - } - } - - - /** - * prepare required sql statements - */ - public void prepareStmts(Connection conn) { - try { - select =3D conn.prepareStatement("select t_int, t_char, t_float,t_key= from SAMPLETBL where t_key =3D ?"); - insert =3D conn.prepareStatement("insert into SAMPLETBL (t_int, t_char= ,t_float,t_key) values (?,?,?,?)"); - update =3D conn.prepareStatement(" update SAMPLETBL set t_int =3D ? wh= ere t_key =3D ?"); - delete =3D conn.prepareStatement("delete from SAMPLETBL where t_key = =3D ?"); - getMaxKey =3D conn.prepareStatement("select max(t_key) from SAMPLETBL"= ); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * executing a select and retrieving the results - * select the row with t_key value as 'selectWhat' - */ - public int doSelectOperation(long selectWhat) { - int numRowsSelected =3D 0; - ResultSet rs =3D null; - - try { - select.setLong(1,selectWhat); - rs =3D select.executeQuery(); - - while (rs.next()) { - numRowsSelected++; - - int intVal =3D rs.getInt(1); - String strVal =3D rs.getString(2); - float floatVal =3D rs.getFloat(3); - long longVal =3D rs.getLong(4); //t_key column - - pw.println("[NsSampleWork] Thread id - "+ thread_id +" selected "+num= RowsSelected +" row ["+ intVal + "," - + strVal +","+ floatVal +","+ longVal +"]"); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if(rs !=3D null) - rs.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - return numRowsSelected; - } - - - /** - * Opens a connection and executes DML (insert, select, update, delete)= operations - */ - public void doWork() { - - Connection conn =3D null; - ResultSet rs =3D null; - try { - conn =3D getConnection(dbUrl,properties); - - if(conn =3D=3D null) - throw new Exception("Failed to obtain connection!"); - - conn.setAutoCommit(true); - - // Setting isolation level to read uncommitted, since this is a sample = application. - // Please set the isolation level depending on the requirements of your= application - setIsolationLevel(conn,Connection.TRANSACTION_READ_UNCOMMITTED); - - prepareStmts(conn); - - // Perform the DML operations - for (int i=3D0; i=3D 0) { - int numInserts =3D insertRow(ps); - if (numInserts !=3D 1) - pw.println("[NsSampleWork] Failed to insert row."); - } - } catch (Exception e) { - pw.println("[NsSampleWork] Error when loading schema; exception is "+ = e); - e.printStackTrace(); - } finally { - try { - if(ps !=3D null) - ps.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }//end of method loadSchema() - - - - /** - * Generates random values and performs the inserts into the database - */ - public static int insertRow(PreparedStatement ps) { - - int rowsAdded =3D 0; - try { - // Generate random values for the datatypes in the sample table - Random rand =3D new Random(); - int intVal =3D Math.abs(rand.nextInt()%1000); - - String charVal =3D "Derby"; - - synchronized(lock) { - charVal +=3D counter; - counter++; - } - - // Set parameter values - ps.setInt(1, intVal); - ps.setString(2,charVal); - ps.setFloat(3, rand.nextFloat()*(float)Math.pow(10,Math.abs(rand.nextIn= t()%30))); - ps.setLong(4,rand.nextLong()%10000); - rowsAdded =3D ps.executeUpdate(); - return rowsAdded; - } catch (Exception e) { - e.printStackTrace(); - return 0; - } - } - - - /** - * update a row in the table - * updateWhere is the value of the t_key row which needs to be updated - * return number of rows updated - */ - public static int updateRow (PreparedStatement ps,long updateWhere) { - try { - int val=3D0; - synchronized(lock) { - val =3D counter++; - } - ps.setInt(1,val); - ps.setLong(2,updateWhere); - return(ps.executeUpdate()); - } catch (SQLException se) { - se.printStackTrace(); - return 0; - } - } - - - /** - * Delete row from table - * deleteRow is the value of the t_key of the row to be deleted - * return number of rows deleted - */ - public static int deleteRow(PreparedStatement ps,long deleteRow) { - int rowsDeleted =3D 0; - try { - ps.setLong(1, deleteRow); - rowsDeleted =3D ps.executeUpdate(); - return rowsDeleted; - } catch(Exception e) { - e.printStackTrace(); - return 0; - } - } - -}//end of class NsSampleWork +/* + + Derby - Class nserverdemo.NsSampleClientThread + + Copyright 2003, 2004 The Apache Software Foundation or its licensors, a= s applicable. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + */ + +package nserverdemo; + +import java.util.Properties; +import java.sql.SQLException; +import java.sql.DriverManager; +import java.io.IOException; +import java.sql.Statement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.io.PrintWriter; +import java.util.Properties; +import java.sql.PreparedStatement; +import java.sql.Connection; +import java.util.Random; +import java.lang.Math; +/** + * NsSampleClientThread thread to perform the NsSampleWork + */ +public class NsSampleClientThread extends Thread { + + protected int thread_id; + protected Properties properties; + protected PrintWriter pw; + protected String dbUrl; + + NsSampleClientThread(int id,String dbUrl, Properties properties,PrintWri= ter pw) { + this.thread_id=3Did; + this.dbUrl =3D dbUrl; + this.properties =3D properties; + this.pw =3D pw; + } + + public void run() { + System.out.println("[NsSampleClientThread] Thread id - "+this.thread_id = + "; started."); + NsSampleWork w =3D new NsSampleWork(this.thread_id,dbUrl,properties,pw); + w.doWork(); // do all the NsSampleWork + pw.println("[NsSampleClientThread] Thread id - "+this.thread_id+"; finis= hed all tasks."); + } +} + + + +/** + * NsSampleWork class represents all the work done in the sample demo prog= ram. + * It includes + * getting a connection to the database, creating and loading of schema, + * preparing and execution of SQL statements (insert, select, update, dele= te ) + */ +class NsSampleWork { + + protected int thread_id; + protected String dbUrl; + protected Properties properties; + PrintWriter pw; + PreparedStatement select =3D null; + PreparedStatement insert =3D null; + PreparedStatement delete =3D null; + PreparedStatement update =3D null; + PreparedStatement getMaxKey =3D null; + + + + public static int counter=3D0; + static Integer lock =3D new Integer(0); + /** + * dbUrl is the database url to connect to + */ + NsSampleWork(int id, String dbURL,Properties properties,PrintWriter pw) { + this.thread_id =3D id; + this.dbUrl =3D dbURL; + this.pw =3D pw; + this.properties =3D properties; + } + + + /** + * gets a database connection + * If the dbUrl is trying to connect to the Derby NetNsSampleWork server= using JCC + * then the jcc driver must be already loaded before calling this method, + * else there will be an error + * return jcc connection if no error, else null + */ + public Connection getConnection(String dbUrl, Properties properties) { + Connection conn =3D null; + try { + pw.println("[NsSampleWork] Thread id - "+thread_id + "; requests databa= se connection, dbUrl =3D"+dbUrl); + conn =3D DriverManager.getConnection(dbUrl, properties); + } catch (Exception e) { + System.out.println("[NsSampleWork] Thread id - "+ thread_id + "; faile= d to get database connection. Exception thrown:"); + e.printStackTrace(); + } + return conn; + } + + + /** + * set the connection to this isolation level + */ + public void setIsolationLevel(Connection conn, int level) { + try { + conn.setTransactionIsolation(level); + } catch (Exception e) { + pw.println("[NsSampleWork] Thread id - "+ thread_id +"; setIsolationLe= vel failed. Exception thrown: "); + e.printStackTrace(); + } + } + + + /** + * close connection + */ + public void closeConnection(Connection conn) { + try { + if(conn !=3D null) + conn.close(); + pw.println("[NsSampleWork] Thread id - "+thread_id + "; closed connecti= on to the database."); + } catch (Exception e) { + pw.println("[NsSampleWork] Thread id - "+thread_id + "; error when clo= sing connection;"+ e); + e.printStackTrace(); + } + } + + + /** + * prepare required sql statements + */ + public void prepareStmts(Connection conn) { + try { + select =3D conn.prepareStatement("select t_int, t_char, t_float,t_key= from SAMPLETBL where t_key =3D ?"); + insert =3D conn.prepareStatement("insert into SAMPLETBL (t_int, t_char= ,t_float,t_key) values (?,?,?,?)"); + update =3D conn.prepareStatement(" update SAMPLETBL set t_int =3D ? wh= ere t_key =3D ?"); + delete =3D conn.prepareStatement("delete from SAMPLETBL where t_key = =3D ?"); + getMaxKey =3D conn.prepareStatement("select max(t_key) from SAMPLETBL"= ); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * executing a select and retrieving the results + * select the row with t_key value as 'selectWhat' + */ + public int doSelectOperation(long selectWhat) { + int numRowsSelected =3D 0; + ResultSet rs =3D null; + + try { + select.setLong(1,selectWhat); + rs =3D select.executeQuery(); + + while (rs.next()) { + numRowsSelected++; + + int intVal =3D rs.getInt(1); + String strVal =3D rs.getString(2); + float floatVal =3D rs.getFloat(3); + long longVal =3D rs.getLong(4); //t_key column + + pw.println("[NsSampleWork] Thread id - "+ thread_id +" selected "+num= RowsSelected +" row ["+ intVal + "," + + strVal +","+ floatVal +","+ longVal +"]"); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if(rs !=3D null) + rs.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + return numRowsSelected; + } + + + /** + * Opens a connection and executes DML (insert, select, update, delete)= operations + */ + public void doWork() { + + Connection conn =3D null; + ResultSet rs =3D null; + try { + conn =3D getConnection(dbUrl,properties); + + if(conn =3D=3D null) + throw new Exception("Failed to obtain connection!"); + + conn.setAutoCommit(true); + + // Setting isolation level to read uncommitted, since this is a sample = application. + // Please set the isolation level depending on the requirements of your= application + setIsolationLevel(conn,Connection.TRANSACTION_READ_UNCOMMITTED); + + prepareStmts(conn); + + // Perform the DML operations + for (int i=3D0; i=3D 0) { + int numInserts =3D insertRow(ps); + if (numInserts !=3D 1) + pw.println("[NsSampleWork] Failed to insert row."); + } + } catch (Exception e) { + pw.println("[NsSampleWork] Error when loading schema; exception is "+ = e); + e.printStackTrace(); + } finally { + try { + if(ps !=3D null) + ps.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }//end of method loadSchema() + + + + /** + * Generates random values and performs the inserts into the database + */ + public static int insertRow(PreparedStatement ps) { + + int rowsAdded =3D 0; + try { + // Generate random values for the datatypes in the sample table + Random rand =3D new Random(); + int intVal =3D Math.abs(rand.nextInt()%1000); + + String charVal =3D "Derby"; + + synchronized(lock) { + charVal +=3D counter; + counter++; + } + + // Set parameter values + ps.setInt(1, intVal); + ps.setString(2,charVal); + ps.setFloat(3, rand.nextFloat()*(float)Math.pow(10,Math.abs(rand.nextIn= t()%30))); + ps.setLong(4,rand.nextLong()%10000); + rowsAdded =3D ps.executeUpdate(); + return rowsAdded; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + + /** + * update a row in the table + * updateWhere is the value of the t_key row which needs to be updated + * return number of rows updated + */ + public static int updateRow (PreparedStatement ps,long updateWhere) { + try { + int val=3D0; + synchronized(lock) { + val =3D counter++; + } + ps.setInt(1,val); + ps.setLong(2,updateWhere); + return(ps.executeUpdate()); + } catch (SQLException se) { + se.printStackTrace(); + return 0; + } + } + + + /** + * Delete row from table + * deleteRow is the value of the t_key of the row to be deleted + * return number of rows deleted + */ + public static int deleteRow(PreparedStatement ps,long deleteRow) { + int rowsDeleted =3D 0; + try { + ps.setLong(1, deleteRow); + rowsDeleted =3D ps.executeUpdate(); + return rowsDeleted; + } catch(Exception e) { + e.printStackTrace(); + return 0; + } + } + +}//end of class NsSampleWork Propchange: incubator/derby/code/trunk/java/demo/nserverdemo/NsSampleClient= Thread.java ---------------------------------------------------------------------------= --- svn:eol-style =3D native Modified: incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkCli= entSample.java URL: http://svn.apache.org/viewcvs/incubator/derby/code/trunk/java/demo/nse= rverdemo/SimpleNetworkClientSample.java?rev=3D164630&r1=3D164629&r2=3D16463= 0&view=3Ddiff =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D --- incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkClientSam= ple.java (original) +++ incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkClientSam= ple.java Mon Apr 25 12:29:37 2005 @@ -1,266 +1,266 @@ -/* - - Derby - Class SimpleNetworkClientSample - - Copyright 2003, 2004 The Apache Software Foundation or its licensors, a= s applicable. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied= . - See the License for the specific language governing permissions and - limitations under the License. - - */ - -import java.sql.*; -import java.lang.reflect.*; -import javax.sql.DataSource; -import java.util.Properties; -import java.io.BufferedReader; -import java.io.InputStreamReader; - -/** - * The primary purpose of this program is to demonstrate how to obtain - * client connections using DriverManager or a DataSource - * and interact with Derby Network Server - * - * In particular,this sample program - * 1) loads the DB2 Universal JDBC Driver - * 2) obtains a client connection using the Driver Manager - * 3) obtains a client connection using a DataSource - * 4) tests the database connections by executing a sample query - * and then exits the program - * - * Before running this program, please make sure that Clouscape Network Se= rver is up - * and running. - *

- * Usage: java SimpleNetworkClientSample - * - */ -public class SimpleNetworkClientSample -{ - - /* - * The database is located in the same directory where this program is be= ing - * run. Alternately one can specify the absolute path of the database loc= ation - */ - private static String DBNAME=3D"NSSimpleDB"; - - /** - * Derby network server port ; default is 1527 - */ - private static int NETWORKSERVER_PORT=3D1527; - - /** - * DB2 JDBC UNIVERSAL DRIVER class names - */ - private static final String DB2_JDBC_UNIVERSAL_DRIVER =3D "com.ibm.db2.jc= c=2EDB2Driver"; - private static final String DB2_JCC_DS =3D "com.ibm.db2.jcc.DB2SimpleData= Source"; - - /** - * This URL is used to connect to Derby Network Server using the DriverMa= nager. - * Also, this url describes the target database for type 4 connectivity - * Notice that the properties may be established via the URL syntax - */ - private static final String CS_NS_DBURL=3D "jdbc:derby:net://localhost:"+= NETWORKSERVER_PORT+"/"+DBNAME+";retrieveMessagesFromServerOnGetMessage=3Dtr= ue;deferPrepares=3Dtrue;"; - - - public static void main (String[] args) - throws Exception - { - DataSource clientDataSource =3D null; - Connection clientConn1 =3D null; - Connection clientConn2 =3D null; - - - try - { - System.out.println("Starting Sample client program "); - - // load DB2 JDBC UNIVERSAL DRIVER to enable client connections to - // Derby Network Server - loadJCCDriver(); - - // get a client connection using DriverManager - clientConn1 =3D getClientDriverManagerConnection(); - System.out.println("Got a client connection via the DriverManager."); - - // create a datasource with the necessary information - javax.sql.DataSource myDataSource =3D getClientDataSource(DBNAME, null,= null); - - // get a client connection using DataSource - clientConn2 =3D getClientDataSourceConn(myDataSource); - System.out.println("Got a client connection via a DataSource."); - - // test connections by doing some work - System.out.println("Testing the connection obtained via DriverManager b= y executing a sample query "); - test(clientConn1); - System.out.println("Testing the connection obtained via a DataSource by= executing a sample query "); - test(clientConn2); - - System.out.println("Goodbye!"); - } - catch (SQLException sqle) - { - System.out.println("Failure making connection: " + sqle); - sqle.printStackTrace(); - } - finally - { - - if(clientConn1 !=3D null) - clientConn1.close(); - if(clientConn2 !=3D null) - clientConn2.close(); - } - } - - /** - * Get a database connection from DataSource - * @pre Derby Network Server is started - * @param ds data source - * @return returns database connection - * @throws Exception if there is any error - */ - public static Connection getClientDataSourceConn(javax.sql.DataSource ds) - throws Exception - { - Connection conn =3D ds.getConnection("usr2", "pass2"); - System.out.print("connection from datasource; getDriverName =3D "); - System.out.println(conn.getMetaData().getDriverName()); - return conn; - } - - /** - * Creates a client data source and sets all the necessary properties in = order to - * connect to Derby Network Server - * The server is assumed to be running on 1527 and on the localhost - * @param database database name; can include Derby URL attributes - * @param user database user - * @param password - * @return returns DataSource - * @throws Exception if there is any error - */ - public static javax.sql.DataSource getClientDataSource(String database, S= tring user, String - password) throws SQLException, ClassNotFoundException, Instanti= ationException, IllegalAccessException, NoSuchMethodException, InvocationTa= rgetException - { - Class nsDataSource =3D Class.forName(DB2_JCC_DS); - DataSource ds =3D (DataSource) nsDataSource.newInstance(); - - // can also include Derby URL attributes along with the database name - Class[] methodParams =3D new Class[] {String.class}; - Method dbname =3D nsDataSource.getMethod("setDatabaseName", methodParams= ); - Object[] args =3D new Object[] {database}; - dbname.invoke(ds, args); - - if (user !=3D null) { - Method setuser =3D nsDataSource.getMethod("setUser", methodParams); - args =3D new Object[] {user}; - setuser.invoke(ds, args); - } - if (password !=3D null) { - Method setpw =3D nsDataSource.getMethod("setPassword", methodParams); - args =3D new Object[] {password}; - setpw.invoke(ds, args); - } - // host on which network server is running - Method servername =3D nsDataSource.getMethod("setServerName", methodPara= ms); - args =3D new Object[] {"localhost"}; - servername.invoke(ds, args); - - // port on which Network Server is listening - methodParams =3D new Class[] {int.class}; - Method portnumber =3D nsDataSource.getMethod("setPortNumber", methodPara= ms); - args =3D new Object[] {new Integer(1527)}; - portnumber.invoke(ds, args); - - // driver type must be 4 to access Derby Network Server - Method drivertype =3D nsDataSource.getMethod("setDriverType", methodPara= ms); - args =3D new Object[] {new Integer(4)}; - drivertype.invoke(ds, args); - - return ds; - - } - - - /** - * Load DB2 JDBC UNIVERSAL DRIVER - */ - public static void loadJCCDriver() - throws Exception - { - // Load the JCC Driver - Class.forName(DB2_JDBC_UNIVERSAL_DRIVER).newInstance(); - } - - /** - * Get a client connection using the DriverManager - * @pre DB2 JDBC Universal driver must have been loaded before calling th= is method - * @return Connection client database connection - */ - public static Connection getClientDriverManagerConnection() - throws Exception - { - - // See Derby documentation for description of properties that may be set - // in the context of the network server. - Properties properties =3D new java.util.Properties(); - - // The user and password properties are a must, required by JCC - properties.setProperty("user","cloud"); - properties.setProperty("password","scape"); - - // Get database connection using the JCC client via DriverManager api - Connection conn =3D DriverManager.getConnection(CS_NS_DBURL,properties);= =20 - - return conn; - } - - - /** - * Test a connection by executing a sample query - * @param conn database connection - * @throws Exception if there is any error - */ - public static void test(Connection conn) - throws Exception - { - - Statement stmt =3D null; - ResultSet rs =3D null; - try - { - // To test our connection, we will try to do a select from the system ca= talog tables - stmt =3D conn.createStatement(); - rs =3D stmt.executeQuery("select count(*) from sys.systables"); - while(rs.next()) - System.out.println("number of rows in sys.systables =3D "+ rs.getInt(1)= ); - - } - catch(SQLException sqle) - { - System.out.println("SQLException when querying on the database connect= ion; "+ sqle); - throw sqle; - } - finally - { - if(rs !=3D null) - rs.close(); - if(stmt !=3D null) - stmt.close(); - } - } -} - - - - - - +/* + + Derby - Class SimpleNetworkClientSample + + Copyright 2003, 2004 The Apache Software Foundation or its licensors, a= s applicable. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + */ + +import java.sql.*; +import java.lang.reflect.*; +import javax.sql.DataSource; +import java.util.Properties; +import java.io.BufferedReader; +import java.io.InputStreamReader; + +/** + * The primary purpose of this program is to demonstrate how to obtain + * client connections using DriverManager or a DataSource + * and interact with Derby Network Server + * + * In particular,this sample program + * 1) loads the DB2 Universal JDBC Driver + * 2) obtains a client connection using the Driver Manager + * 3) obtains a client connection using a DataSource + * 4) tests the database connections by executing a sample query + * and then exits the program + * + * Before running this program, please make sure that Clouscape Network Se= rver is up + * and running. + *

+ * Usage: java SimpleNetworkClientSample + * + */ +public class SimpleNetworkClientSample +{ + + /* + * The database is located in the same directory where this program is be= ing + * run. Alternately one can specify the absolute path of the database loc= ation + */ + private static String DBNAME=3D"NSSimpleDB"; + + /** + * Derby network server port ; default is 1527 + */ + private static int NETWORKSERVER_PORT=3D1527; + + /** + * DB2 JDBC UNIVERSAL DRIVER class names + */ + private static final String DB2_JDBC_UNIVERSAL_DRIVER =3D "com.ibm.db2.jc= c=2EDB2Driver"; + private static final String DB2_JCC_DS =3D "com.ibm.db2.jcc.DB2SimpleData= Source"; + + /** + * This URL is used to connect to Derby Network Server using the DriverMa= nager. + * Also, this url describes the target database for type 4 connectivity + * Notice that the properties may be established via the URL syntax + */ + private static final String CS_NS_DBURL=3D "jdbc:derby:net://localhost:"+= NETWORKSERVER_PORT+"/"+DBNAME+";retrieveMessagesFromServerOnGetMessage=3Dtr= ue;deferPrepares=3Dtrue;"; + + + public static void main (String[] args) + throws Exception + { + DataSource clientDataSource =3D null; + Connection clientConn1 =3D null; + Connection clientConn2 =3D null; + + + try + { + System.out.println("Starting Sample client program "); + + // load DB2 JDBC UNIVERSAL DRIVER to enable client connections to + // Derby Network Server + loadJCCDriver(); + + // get a client connection using DriverManager + clientConn1 =3D getClientDriverManagerConnection(); + System.out.println("Got a client connection via the DriverManager."); + + // create a datasource with the necessary information + javax.sql.DataSource myDataSource =3D getClientDataSource(DBNAME, null,= null); + + // get a client connection using DataSource + clientConn2 =3D getClientDataSourceConn(myDataSource); + System.out.println("Got a client connection via a DataSource."); + + // test connections by doing some work + System.out.println("Testing the connection obtained via DriverManager b= y executing a sample query "); + test(clientConn1); + System.out.println("Testing the connection obtained via a DataSource by= executing a sample query "); + test(clientConn2); + + System.out.println("Goodbye!"); + } + catch (SQLException sqle) + { + System.out.println("Failure making connection: " + sqle); + sqle.printStackTrace(); + } + finally + { + + if(clientConn1 !=3D null) + clientConn1.close(); + if(clientConn2 !=3D null) + clientConn2.close(); + } + } + + /** + * Get a database connection from DataSource + * @pre Derby Network Server is started + * @param ds data source + * @return returns database connection + * @throws Exception if there is any error + */ + public static Connection getClientDataSourceConn(javax.sql.DataSource ds) + throws Exception + { + Connection conn =3D ds.getConnection("usr2", "pass2"); + System.out.print("connection from datasource; getDriverName =3D "); + System.out.println(conn.getMetaData().getDriverName()); + return conn; + } + + /** + * Creates a client data source and sets all the necessary properties in = order to + * connect to Derby Network Server + * The server is assumed to be running on 1527 and on the localhost + * @param database database name; can include Derby URL attributes + * @param user database user + * @param password + * @return returns DataSource + * @throws Exception if there is any error + */ + public static javax.sql.DataSource getClientDataSource(String database, S= tring user, String + password) throws SQLException, ClassNotFoundException, Instanti= ationException, IllegalAccessException, NoSuchMethodException, InvocationTa= rgetException + { + Class nsDataSource =3D Class.forName(DB2_JCC_DS); + DataSource ds =3D (DataSource) nsDataSource.newInstance(); + + // can also include Derby URL attributes along with the database name + Class[] methodParams =3D new Class[] {String.class}; + Method dbname =3D nsDataSource.getMethod("setDatabaseName", methodParams= ); + Object[] args =3D new Object[] {database}; + dbname.invoke(ds, args); + + if (user !=3D null) { + Method setuser =3D nsDataSource.getMethod("setUser", methodParams); + args =3D new Object[] {user}; + setuser.invoke(ds, args); + } + if (password !=3D null) { + Method setpw =3D nsDataSource.getMethod("setPassword", methodParams); + args =3D new Object[] {password}; + setpw.invoke(ds, args); + } + // host on which network server is running + Method servername =3D nsDataSource.getMethod("setServerName", methodPara= ms); + args =3D new Object[] {"localhost"}; + servername.invoke(ds, args); + + // port on which Network Server is listening + methodParams =3D new Class[] {int.class}; + Method portnumber =3D nsDataSource.getMethod("setPortNumber", methodPara= ms); + args =3D new Object[] {new Integer(1527)}; + portnumber.invoke(ds, args); + + // driver type must be 4 to access Derby Network Server + Method drivertype =3D nsDataSource.getMethod("setDriverType", methodPara= ms); + args =3D new Object[] {new Integer(4)}; + drivertype.invoke(ds, args); + + return ds; + + } + + + /** + * Load DB2 JDBC UNIVERSAL DRIVER + */ + public static void loadJCCDriver() + throws Exception + { + // Load the JCC Driver + Class.forName(DB2_JDBC_UNIVERSAL_DRIVER).newInstance(); + } + + /** + * Get a client connection using the DriverManager + * @pre DB2 JDBC Universal driver must have been loaded before calling th= is method + * @return Connection client database connection + */ + public static Connection getClientDriverManagerConnection() + throws Exception + { + + // See Derby documentation for description of properties that may be set + // in the context of the network server. + Properties properties =3D new java.util.Properties(); + + // The user and password properties are a must, required by JCC + properties.setProperty("user","cloud"); + properties.setProperty("password","scape"); + + // Get database connection using the JCC client via DriverManager api + Connection conn =3D DriverManager.getConnection(CS_NS_DBURL,properties);=20 + + return conn; + } + + + /** + * Test a connection by executing a sample query + * @param conn database connection + * @throws Exception if there is any error + */ + public static void test(Connection conn) + throws Exception + { + + Statement stmt =3D null; + ResultSet rs =3D null; + try + { + // To test our connection, we will try to do a select from the system ca= talog tables + stmt =3D conn.createStatement(); + rs =3D stmt.executeQuery("select count(*) from sys.systables"); + while(rs.next()) + System.out.println("number of rows in sys.systables =3D "+ rs.getInt(1)= ); + + } + catch(SQLException sqle) + { + System.out.println("SQLException when querying on the database connect= ion; "+ sqle); + throw sqle; + } + finally + { + if(rs !=3D null) + rs.close(); + if(stmt !=3D null) + stmt.close(); + } + } +} + + + + + + Propchange: incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkC= lientSample.java ---------------------------------------------------------------------------= --- svn:eol-style =3D native Modified: incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkSer= verSample.java URL: http://svn.apache.org/viewcvs/incubator/derby/code/trunk/java/demo/nse= rverdemo/SimpleNetworkServerSample.java?rev=3D164630&r1=3D164629&r2=3D16463= 0&view=3Ddiff =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D --- incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkServerSam= ple.java (original) +++ incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkServerSam= ple.java Mon Apr 25 12:29:37 2005 @@ -1,324 +1,324 @@ -/* - - Derby - Class SimpleNetworkServerSample - - Copyright 2003, 2004 The Apache Software Foundation or its licensors, a= s applicable. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied= . - See the License for the specific language governing permissions and - limitations under the License. - - */ - -import java.sql.*; -import javax.sql.DataSource; -import org.apache.derby.drda.NetworkServerControl; -import java.util.Properties; -import java.io.BufferedReader; -import java.io.InputStreamReader; - -/** - * In order for a database to be consistent, only one JVM is allowed - * to access it at a time. The embedded driver is loaded when the Network = Server - * is started. Hence, the JVM that starts the Network Server can get an - * embedded connection to the same database that Network Server is accessi= ng - * to serve the clients from other JVMs. This solution allows you to take - * advantage of the performance benefits of embedded driver as well as all= ow - * for client connections from other JVMs to connect to the same database. - * - * - * In particular,this sample program - * 1) starts the Derby Network Server using a property and - * also loads the embedded driver - * 2) checks if the Derby Network Server is up and running - * 3) creates the database 'NSSimpleDB' if not already created - * 4) obtains an embedded database connection - * 5) tests the database connection by executing a sample query - * 6) allows for client connections to connect to the server until - * the user decides to stop the server and exit the program - * 7) closes the connections - * 8) shuts down the Derby Network Server before exiting the program. - * - * Note, on running this program, there will be a NSSimpleDB database dire= ctory - * created if not present already and there will be a derby.log file which - * contains messages from Derby - * - *

- * Usage: java SimpleNetworkServerSample - * - */ -public class SimpleNetworkServerSample -{ - - /* - * The database is located in the same directory where this program is be= ing - * run. Alternately one can specify the absolute path of the database loc= ation - */ - private static String DBNAME=3D"NSSimpleDB"; - - - public static void main (String[] args) - throws Exception - { - Connection embeddedConn =3D null; - - try - { - startNetworkServer(); - - /* - Can now spawn threads to do many wonderous things with - embedded connections but allow others to connect via - Network Server. But for sample purposes, an embedded connection - will be obtained and a sample query executed before waiting for - the user to give input to shutdown the server. - */ - - } - catch (Exception e) - { - System.out.println("Failed to start NetworkServer: " + e); - System.exit(1); - } - - try - { - // get an embedded connection - // Since Network Server was started in this jvm, this JVM can get an e= mbedded - // connection to the same database that Network Server - // is accessing to serve clients from other JVM's. - // The embedded connection will be faster than going across the - // network - embeddedConn =3D getEmbeddedConnection(DBNAME,"create=3Dtrue;"); - System.out.println("Got an embedded connection."); - - - System.out.println("Testing embedded connection by executing a sample q= uery "); - // test connections by doing some work - test(embeddedConn); - - // print how to connect to the network server using ij - String howToConnect =3D ijUsage(); - System.out.println(howToConnect); - - waitForExit(); - - } - catch (SQLException sqle) - { - System.out.println("Failure making connection: " + sqle); - sqle.printStackTrace(); - } - finally - { - - if(embeddedConn !=3D null) - embeddedConn.close(); - try - { - // shutdown Derby Network Server - DriverManager.getConnection("jdbc:derby:;shutdown=3Dtrue"); - } - catch(SQLException se) - { - //ignore se - } - - } - - } - - /** - * Setting the derby.drda.startNetworkServer property to true, - * either in the System properties as we do here or in - * the derby.properties file will cause Network Server to - * start as soon as Derby is loaded. - * - * To load Derby we just need to load the embedded - * Driver with: - * Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - * - * Then we will test for a while and make sure it is up, before - * we give up. - * - * Alternately Network Server might be started from the command - * line or from some other program. Note: only the JVM that starts - * Network Server can make an embedded connection. - */ - - public static void startNetworkServer() throws Exception - { - // Start network server using the property - // and then wait for the server to start by testing a connection - startWithProperty(); - waitForStart(); - } - - /** - * Start Derby Network Server using the property - * derby.drda.startNetworkServer. This property can be set as a system pr= operty or - * or by setting in derby.properties file. - * Setting this property to true , starts the Network Server when - * Derby boots up. - * The port at which the Derby Network Server listens to can be changed - * by setting the derby.drda.portNumber property. By default, the server = starts - * at port 1527 - * Server output goes to derby.log - */ - - private static void startWithProperty() throws Exception - { - System.out.println("Starting Network Server"); - System.setProperty("derby.drda.startNetworkServer","true"); - - // Booting derby - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - } - - - - /** - * Tries to check if the Network Server is up and running by calling ping - * If successful, then it returns else tries for 50 seconds before giving= up and throwing - * an exception. - * @throws Exception when there is a problem with testing if the Network = Server is up - * and running - */ - private static void waitForStart() throws Exception - { - - // Server instance for testing connection - org.apache.derby.drda.NetworkServerControl server =3D null; - - // Use NetworkServerControl.ping() to wait for - // NetworkServer to come up. We could have used - // NetworkServerControl to start the server but the property is - // easier. - server =3D new NetworkServerControl(); - - System.out.println("Testing if Network Server is up and running!"); - for (int i =3D 0; i < 10 ; i ++) - { - try { - - Thread.currentThread().sleep(5000); - server.ping(); - } - catch (Exception e) - { - System.out.println("Try #" + i + " " +e.toString()); - if (i =3D=3D 9 ) - { - System.out.println("Giving up trying to connect to Network Server!"); - throw e; - } - } - } - System.out.println("Derby Network Server now running"); - - } - - /** - * Used to return an embedded Derby connection - * The protocol used is "jdbc:derby:dbName" where dbName is the database = name - * @pre the derby embedded jdbc driver must be loaded before calling this= method - * Alternately, if the derby network server is started in this jvm, then = the embedded driver - * org.apache.derby.jdbc.EmbeddedDriver is already loaded and it need not= be loaded again. - * @param dbName database name (ie location of the database) - * @param attributes attributes for the database connection - * example, create=3Dtrue; - * upgrade=3Dtrue; - * @return returns embedded database connection - * @throws Exception if there is any error - */ - public static Connection getEmbeddedConnection(String database,String att= ributes) - throws Exception - { - String dbUrl =3D "jdbc:derby:"+database +";"+attributes; - Connection conn =3D DriverManager.getConnection(dbUrl); - return conn; - } - - - - /** - * Test a connection by executing a sample query - * @param conn database connection - * @throws Exception if there is any error - */ - public static void test(Connection conn) - throws Exception - { - - Statement stmt =3D null; - ResultSet rs =3D null; - try - { - // To test our connection, we will try to do a select from the system ca= talog tables - stmt =3D conn.createStatement(); - rs =3D stmt.executeQuery("select count(*) from sys.systables"); - while(rs.next()) - System.out.println("number of rows in sys.systables =3D "+ rs.getInt(1)= ); - - } - catch(SQLException sqle) - { - System.out.println("SQLException when querying on the database connect= ion; "+ sqle); - throw sqle; - } - finally - { - if(rs !=3D null) - rs.close(); - if(stmt !=3D null) - stmt.close(); - } - - } - - - /** - * This method waits until the user hits enter to stop the server - * and eventually exit this program - * Allows clients to continue to connect using client connections from ot= her - * jvms to Derby Network Server that was started in this program - */ - private static void waitForExit() throws Exception - { - System.out.println("Clients can continue to connect: "); - BufferedReader in =3D - new BufferedReader(new InputStreamReader(System.in)); - System.out.println("Press [Enter] to stop Server"); - in.readLine(); - } - - /** - * Returns a string with information as to how to connect to Derby Networ= k Server - */ - private static String ijUsage() - { - - String ijUsage =3D "\nWhile my app is busy with embedded work, "; - ijUsage +=3D "ij might connect like this:\n\n"; - ijUsage +=3D "\t$ java -Dij.user=3Dme -Dij.password=3Dpw -Dij.protocol= =3Djdbc:derby:net://localhost:1527/ org.apache.derby.tools.ij\n"; - ijUsage +=3D "\tij> connect '" + DBNAME + ":retrieveMessagesFromServerOn= GetMessage=3Dtrue;';\n"; - ijUsage +=3D "Watch that punctuation. Put a ':' before the jcc\n"; - ijUsage +=3D "attributes and a ';' after each one (even the last).\n\n"; - - return ijUsage; - } -} - - - - - - +/* + + Derby - Class SimpleNetworkServerSample + + Copyright 2003, 2004 The Apache Software Foundation or its licensors, a= s applicable. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + */ + +import java.sql.*; +import javax.sql.DataSource; +import org.apache.derby.drda.NetworkServerControl; +import java.util.Properties; +import java.io.BufferedReader; +import java.io.InputStreamReader; + +/** + * In order for a database to be consistent, only one JVM is allowed + * to access it at a time. The embedded driver is loaded when the Network = Server + * is started. Hence, the JVM that starts the Network Server can get an + * embedded connection to the same database that Network Server is accessi= ng + * to serve the clients from other JVMs. This solution allows you to take + * advantage of the performance benefits of embedded driver as well as all= ow + * for client connections from other JVMs to connect to the same database. + * + * + * In particular,this sample program + * 1) starts the Derby Network Server using a property and + * also loads the embedded driver + * 2) checks if the Derby Network Server is up and running + * 3) creates the database 'NSSimpleDB' if not already created + * 4) obtains an embedded database connection + * 5) tests the database connection by executing a sample query + * 6) allows for client connections to connect to the server until + * the user decides to stop the server and exit the program + * 7) closes the connections + * 8) shuts down the Derby Network Server before exiting the program. + * + * Note, on running this program, there will be a NSSimpleDB database dire= ctory + * created if not present already and there will be a derby.log file which + * contains messages from Derby + * + *

+ * Usage: java SimpleNetworkServerSample + * + */ +public class SimpleNetworkServerSample +{ + + /* + * The database is located in the same directory where this program is be= ing + * run. Alternately one can specify the absolute path of the database loc= ation + */ + private static String DBNAME=3D"NSSimpleDB"; + + + public static void main (String[] args) + throws Exception + { + Connection embeddedConn =3D null; + + try + { + startNetworkServer(); + + /* + Can now spawn threads to do many wonderous things with + embedded connections but allow others to connect via + Network Server. But for sample purposes, an embedded connection + will be obtained and a sample query executed before waiting for + the user to give input to shutdown the server. + */ + + } + catch (Exception e) + { + System.out.println("Failed to start NetworkServer: " + e); + System.exit(1); + } + + try + { + // get an embedded connection + // Since Network Server was started in this jvm, this JVM can get an e= mbedded + // connection to the same database that Network Server + // is accessing to serve clients from other JVM's. + // The embedded connection will be faster than going across the + // network + embeddedConn =3D getEmbeddedConnection(DBNAME,"create=3Dtrue;"); + System.out.println("Got an embedded connection."); + + + System.out.println("Testing embedded connection by executing a sample q= uery "); + // test connections by doing some work + test(embeddedConn); + + // print how to connect to the network server using ij + String howToConnect =3D ijUsage(); + System.out.println(howToConnect); + + waitForExit(); + + } + catch (SQLException sqle) + { + System.out.println("Failure making connection: " + sqle); + sqle.printStackTrace(); + } + finally + { + + if(embeddedConn !=3D null) + embeddedConn.close(); + try + { + // shutdown Derby Network Server + DriverManager.getConnection("jdbc:derby:;shutdown=3Dtrue"); + } + catch(SQLException se) + { + //ignore se + } + + } + + } + + /** + * Setting the derby.drda.startNetworkServer property to true, + * either in the System properties as we do here or in + * the derby.properties file will cause Network Server to + * start as soon as Derby is loaded. + * + * To load Derby we just need to load the embedded + * Driver with: + * Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + * + * Then we will test for a while and make sure it is up, before + * we give up. + * + * Alternately Network Server might be started from the command + * line or from some other program. Note: only the JVM that starts + * Network Server can make an embedded connection. + */ + + public static void startNetworkServer() throws Exception + { + // Start network server using the property + // and then wait for the server to start by testing a connection + startWithProperty(); + waitForStart(); + } + + /** + * Start Derby Network Server using the property + * derby.drda.startNetworkServer. This property can be set as a system pr= operty or + * or by setting in derby.properties file. + * Setting this property to true , starts the Network Server when + * Derby boots up. + * The port at which the Derby Network Server listens to can be changed + * by setting the derby.drda.portNumber property. By default, the server = starts + * at port 1527 + * Server output goes to derby.log + */ + + private static void startWithProperty() throws Exception + { + System.out.println("Starting Network Server"); + System.setProperty("derby.drda.startNetworkServer","true"); + + // Booting derby + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + } + + + + /** + * Tries to check if the Network Server is up and running by calling ping + * If successful, then it returns else tries for 50 seconds before giving= up and throwing + * an exception. + * @throws Exception when there is a problem with testing if the Network = Server is up + * and running + */ + private static void waitForStart() throws Exception + { + + // Server instance for testing connection + org.apache.derby.drda.NetworkServerControl server =3D null; + + // Use NetworkServerControl.ping() to wait for + // NetworkServer to come up. We could have used + // NetworkServerControl to start the server but the property is + // easier. + server =3D new NetworkServerControl(); + + System.out.println("Testing if Network Server is up and running!"); + for (int i =3D 0; i < 10 ; i ++) + { + try { + + Thread.currentThread().sleep(5000); + server.ping(); + } + catch (Exception e) + { + System.out.println("Try #" + i + " " +e.toString()); + if (i =3D=3D 9 ) + { + System.out.println("Giving up trying to connect to Network Server!"); + throw e; + } + } + } + System.out.println("Derby Network Server now running"); + + } + + /** + * Used to return an embedded Derby connection + * The protocol used is "jdbc:derby:dbName" where dbName is the database = name + * @pre the derby embedded jdbc driver must be loaded before calling this= method + * Alternately, if the derby network server is started in this jvm, then = the embedded driver + * org.apache.derby.jdbc.EmbeddedDriver is already loaded and it need not= be loaded again. + * @param dbName database name (ie location of the database) + * @param attributes attributes for the database connection + * example, create=3Dtrue; + * upgrade=3Dtrue; + * @return returns embedded database connection + * @throws Exception if there is any error + */ + public static Connection getEmbeddedConnection(String database,String att= ributes) + throws Exception + { + String dbUrl =3D "jdbc:derby:"+database +";"+attributes; + Connection conn =3D DriverManager.getConnection(dbUrl); + return conn; + } + + + + /** + * Test a connection by executing a sample query + * @param conn database connection + * @throws Exception if there is any error + */ + public static void test(Connection conn) + throws Exception + { + + Statement stmt =3D null; + ResultSet rs =3D null; + try + { + // To test our connection, we will try to do a select from the system ca= talog tables + stmt =3D conn.createStatement(); + rs =3D stmt.executeQuery("select count(*) from sys.systables"); + while(rs.next()) + System.out.println("number of rows in sys.systables =3D "+ rs.getInt(1)= ); + + } + catch(SQLException sqle) + { + System.out.println("SQLException when querying on the database connect= ion; "+ sqle); + throw sqle; + } + finally + { + if(rs !=3D null) + rs.close(); + if(stmt !=3D null) + stmt.close(); + } + + } + + + /** + * This method waits until the user hits enter to stop the server + * and eventually exit this program + * Allows clients to continue to connect using client connections from ot= her + * jvms to Derby Network Server that was started in this program + */ + private static void waitForExit() throws Exception + { + System.out.println("Clients can continue to connect: "); + BufferedReader in =3D + new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Press [Enter] to stop Server"); + in.readLine(); + } + + /** + * Returns a string with information as to how to connect to Derby Networ= k Server + */ + private static String ijUsage() + { + + String ijUsage =3D "\nWhile my app is busy with embedded work, "; + ijUsage +=3D "ij might connect like this:\n\n"; + ijUsage +=3D "\t$ java -Dij.user=3Dme -Dij.password=3Dpw -Dij.protocol= =3Djdbc:derby:net://localhost:1527/ org.apache.derby.tools.ij\n"; + ijUsage +=3D "\tij> connect '" + DBNAME + ":retrieveMessagesFromServerOn= GetMessage=3Dtrue;';\n"; + ijUsage +=3D "Watch that punctuation. Put a ':' before the jcc\n"; + ijUsage +=3D "attributes and a ';' after each one (even the last).\n\n"; + + return ijUsage; + } +} + + + + + + Propchange: incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkS= erverSample.java ---------------------------------------------------------------------------= --- svn:eol-style =3D native Modified: incubator/derby/code/trunk/java/demo/nserverdemo/nserverdemo.html URL: http://svn.apache.org/viewcvs/incubator/derby/code/trunk/java/demo/nse= rverdemo/nserverdemo.html?rev=3D164630&r1=3D164629&r2=3D164630&view=3Ddiff =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D --- incubator/derby/code/trunk/java/demo/nserverdemo/nserverdemo.html (orig= inal) +++ incubator/derby/code/trunk/java/demo/nserverdemo/nserverdemo.html Mon A= pr 25 12:29:37 2005 @@ -1,157 +1,157 @@ - - - -Derby Network Server sample program - - - -

D= erby=20 -Network Server sample program

-

The Network Server sample demo program (NsSample) is a simple JDBC appl= ication that=20 -interacts with the Derby Network Server. The program:

-
    -
  • starts the Derby Network Server=20 -
  • checks if the Derby Network Server is running=20 -
  • loads the DB2 JDBC Universal Driver=20 -
  • creates the database 'NsSampledb' if not already created=20 -
  • checks to see if the schema is already created, and if not,=20 - creates the schema which includes the SAMPLETBL table and corre= sponding=20 - indexes.=20 -
  • connects to the database=20 -
  • loads the schema by inserting data=20 -
  • starts client threads to perform database related operations=20 -
  • has each of the clients perform DML operations (select, insert, dele= te, update)=20 - using JDBC calls, in particular one client opens an embedded connection = to=20 - perform database operations while the other client opens a client connec= tion=20 - to the Derby Network Server to perform database operations.=20 -
  • waits for the client threads to finish the tasks=20 -
  • shuts down the Derby Network Server at the end of the demo
  • -

    The following files should be installed in the %DERBY_INSTALL%\demo\programs\nserverdemo\ = directory in=20 -order to run the sample program:

    -
      -
    • NsSample.java
      -This is the entry point into the demo application. The program starts up t= wo clients. One client opens an embedded=20 -connection to perform database operations while the other client opens a c= lient=20 -connection to the Derby Network Server to perform database operations. Th= is program provides the following constants that=20 -can be changed to modify the sample demo: -
        - -
      • NUM_ROWS - The number of rows that must be initially load= ed into the schema.
      • -
      • ITERATIONS - The number of iterations for which each clie= nt thread does database related work.
      • -
      • NUM_CLIENT_THREADS - The number of clients that you want to r= un the program against.
      • =20 -
      • NETWORKSERVER_PORT - The port on which the network server= is running.
      • -
      - -You can also modify the program to exclude starting the Network Server as = part of the sample program.=20 -Make sure to recompile the java files before running the program if you ma= ke any=20 -changes to the source code. - -
    • - -
    • NsSampleClientThread.java
      -This file contains two Java classes: -
        -
      • The NsSampleClientThread class extends Thread and does al= l the=20 -necessary work by instantiating a NsSampleWork instance.
      • -
      • The NsSampleWork class contains everything required to pe= rform=20 -DML operations using JDBC calls. The doWork method in=20 -the NsSampleWork class represents all the work done as=20 -part of this sample program.
      • -
      -
    • -
    • NetworkServerUtil.java
      -This file contains helper methods to start the Derby Network Server and to= shutdown the server. -
    • -
    • Compiled class files: -
        -
      • NsSample.class
      • =20 -
      • NsSampleClientThread.class
      • =20 -
      • NsSampleWork.class
      • =20 -
      • NetworkServerUtil.class
      • =20 -
      -
    • -
    - - -

    Running the Network Server demo program

    -

    To run the Derby Network Server demonstration program:

    -
      -
    1. Open a command prompt and change directories to the %DERBY_INSTALL%\demo\programs\ directory,= where %DERBY_INSTALL% is the directory where you install= ed Derby.=20 -
    2. Set the CLASSPATH to the current directory (".") and also include th= e following=20 - jar files in order to use the Derby Network Server and the DB2 JDBC Univ= ersal Driver. -
        -
      • derbynet.jar
        The Network Server jar file. It must be in yo= ur CLASSPATH to use any of the Derby Network=20 -Server functions.
      • -
      • db2jcc.jar
        This jar file must be in your CLASSPATH to use = the=20 -DB2 JDBC Universal Driver.
      • -
      • db2jcc_license_c.jar
        This jar file is the license file for= the Universal=20 -Driver.
      • -
      • derby.jar
        The Derby database engine jar file.
      • -
      -
    3. -
    4. Test the CLASSPATH settings by running the following java command:java org.apache.derby.tools.sysinfoThis command will show the Derby = jar files that are in the CLASSPATH as well as=20 -the DB2 JDBC Universal Driver along with their respective versions.
    5. -
    6. Once you have set up your environment correctly, execute the applicati= on from the
      %DERBY_INSTALL%\demo\programs\ directory:=
      -
      java nserverdemo.NsSample
      -
    7. -
    -You should receive output similar to the following if the=20 -program runs successfully:

    - -Derby Network Server created
    -[NsSample] Unable to obtain a connection to network server, trying again a= fter 3000 ms.
    -Server is ready to accept connections on port 1621.
    -Connection number: 1.
    -[NsSample] Derby Network Server started.
    -[NsSample] Sample Derby Network Server program demo starting.
    -Please wait .....................
    -Connection number: 2.
    -[NsSampleWork] Table 'SAMPLETBL' already exists; no need to create schema = again.
    -[NsSampleClientThread] Thread id - 1; started.
    -[NsSampleWork] Thread id - 1; requests database connection, dbUrl =3Djdbc:= derby:NSSampledb;
    -[NsSampleClientThread] Thread id - 2; started.
    -[NsSampleWork] Thread id - 2; requests database connection, dbUrl
    =3Dj= dbc:derby:net://localhost:1621/NSSampledb;create=3Dtrue:retrieveMessagesFro= mServerOnGetMessage=3Dtrue;deferPrepares=3Dtrue;
    -Connection number: 3.
    -[NsSampleWork] Thread id - 1 selected 1 row [61,Derby28 ,3.20918E21= ,9854]
    -[NsSampleWork] Thread id - 1; inserted 1 row.
    -[NsSampleWork] Thread id - 1; deleted 1 row with t_key =3D 9854
    -[NsSampleWork] Thread id - 1; inserted 1 row.
    -[NsSampleWork] Thread id - 1; deleted 1 row with t_key =3D 9818
    -[NsSampleWork] Thread id - 2; deleted 0 row with t_key =3D 9854
    -[NsSampleWork] Thread id - 1; updated 1 row with t_key =3D 9481
    -[NsSampleWork] Thread id - 1; updated 1 row with t_key =3D 9481
    -[NsSampleWork] Thread id - 1; updated 0 row with t_key =3D 9481
    -[NsSampleWork] Thread id - 2; deleted 1 row with t_key =3D 9481
    -[NsSampleWork] Thread id - 1; inserted 1 row.
    -[NsSampleWork] Thread id - 1; updated 1 row with t_key =3D 9150
    -[NsSampleWork] Thread id - 1; closed connection to the database.
    -[NsSampleClientThread] Thread id - 1; finished all tasks.
    -[NsSampleWork] Thread id - 2 selected 1 row [57,Derby18 ,7.873628,9= 150]
    -[NsSampleWork] Thread id - 2; updated 1 row with t_key =3D 9150
    -[NsSampleWork] Thread id - 2 selected 1 row [58,Derby18 ,7.873628,9= 150]
    -[NsSampleWork] Thread id - 2; inserted 1 row.
    -[NsSampleWork] Thread id - 2 selected 1 row [58,Derby18 ,7.873628,9= 150]
    -[NsSampleWork] Thread id - 2; inserted 1 row.
    -[NsSampleWork] Thread id - 2; updated 1 row with t_key =3D 9150
    -[NsSampleWork] Thread id - 2 selected 1 row [61,Derby18 ,7.873628,9= 150]
    -[NsSampleWork] Thread id - 2; closed connection to the database.
    -[NsSampleClientThread] Thread id - 2; finished all tasks.
    -[NsSample] Shutting down network server.
    -Connection number: 4.
    -Shutdown successful.
    -[NsSample] End of Network server demo.
    - -

    Running the demo program will also create new directories and files: -

      -
    • NSSampledb
      This directory make= s up the=20 -NSSampledb database.
    • -
    • derby.log
      This log file contains Derby progress and erro= r messages.
    • -
    - - - - + + + +Derby Network Server sample program + + + +

    D= erby=20 +Network Server sample program

    +

    The Network Server sample demo program (NsSample) is a simple JDBC appl= ication that=20 +interacts with the Derby Network Server. The program:

    +
      +
    • starts the Derby Network Server=20 +
    • checks if the Derby Network Server is running=20 +
    • loads the DB2 JDBC Universal Driver=20 +
    • creates the database 'NsSampledb' if not already created=20 +
    • checks to see if the schema is already created, and if not,=20 + creates the schema which includes the SAMPLETBL table and corre= sponding=20 + indexes.=20 +
    • connects to the database=20 +
    • loads the schema by inserting data=20 +
    • starts client threads to perform database related operations=20 +
    • has each of the clients perform DML operations (select, insert, dele= te, update)=20 + using JDBC calls, in particular one client opens an embedded connection = to=20 + perform database operations while the other client opens a client connec= tion=20 + to the Derby Network Server to perform database operations.=20 +
    • waits for the client threads to finish the tasks=20 +
    • shuts down the Derby Network Server at the end of the demo
    +

    The following files should be installed in the %DERBY_INSTALL%\demo\programs\nserverdemo\ = directory in=20 +order to run the sample program:

    +
      +
    • NsSample.java
      +This is the entry point into the demo application. The program starts up t= wo clients. One client opens an embedded=20 +connection to perform database operations while the other client opens a c= lient=20 +connection to the Derby Network Server to perform database operations. Th= is program provides the following constants that=20 +can be changed to modify the sample demo: +
        + +
      • NUM_ROWS - The number of rows that must be initially load= ed into the schema.
      • +
      • ITERATIONS - The number of iterations for which each clie= nt thread does database related work.
      • +
      • NUM_CLIENT_THREADS - The number of clients that you want to r= un the program against.
      • =20 +
      • NETWORKSERVER_PORT - The port on which the network server= is running.
      • +
      + +You can also modify the program to exclude starting the Network Server as = part of the sample program.=20 +Make sure to recompile the java files before running the program if you ma= ke any=20 +changes to the source code. + +
    • + +
    • NsSampleClientThread.java
      +This file contains two Java classes: +
        +
      • The NsSampleClientThread class extends Thread and does al= l the=20 +necessary work by instantiating a NsSampleWork instance.
      • +
      • The NsSampleWork class contains everything required to pe= rform=20 +DML operations using JDBC calls. The doWork method in=20 +the NsSampleWork class represents all the work done as=20 +part of this sample program.
      • +
      +
    • +
    • NetworkServerUtil.java
      +This file contains helper methods to start the Derby Network Server and to= shutdown the server. +
    • +
    • Compiled class files: +
        +
      • NsSample.class
      • =20 +
      • NsSampleClientThread.class
      • =20 +
      • NsSampleWork.class
      • =20 +
      • NetworkServerUtil.class
      • =20 +
      +
    • +
    + + +

    Running the Network Server demo program

    +

    To run the Derby Network Server demonstration program:

    +
      +
    1. Open a command prompt and change directories to the %DERBY_INSTALL%\demo\programs\ directory,= where %DERBY_INSTALL% is the directory where you install= ed Derby.=20 +
    2. Set the CLASSPATH to the current directory (".") and also include th= e following=20 + jar files in order to use the Derby Network Server and the DB2 JDBC Univ= ersal Driver. +
        +
      • derbynet.jar
        The Network Server jar file. It must be in yo= ur CLASSPATH to use any of the Derby Network=20 +Server functions.
      • +
      • db2jcc.jar
        This jar file must be in your CLASSPATH to use = the=20 +DB2 JDBC Universal Driver.
      • +
      • db2jcc_license_c.jar
        This jar file is the license file for= the Universal=20 +Driver.
      • +
      • derby.jar
        The Derby database engine jar file.
      • +
      +
    3. +
    4. Test the CLASSPATH settings by running the following java command:java org.apache.derby.tools.sysinfoThis command will show the Derby = jar files that are in the CLASSPATH as well as=20 +the DB2 JDBC Universal Driver along with their respective versions.
    5. +
    6. Once you have set up your environment correctly, execute the applicati= on from the
      %DERBY_INSTALL%\demo\programs\ directory:=
      +
      java nserverdemo.NsSample
      +
    7. +
    +You should receive output similar to the following if the=20 +program runs successfully:

    + +Derby Network Server created
    +[NsSample] Unable to obtain a connection to network server, trying again a= fter 3000 ms.
    +Server is ready to accept connections on port 1621.
    +Connection number: 1.
    +[NsSample] Derby Network Server started.
    +[NsSample] Sample Derby Network Server program demo starting.
    +Please wait .....................
    +Connection number: 2.
    +[NsSampleWork] Table 'SAMPLETBL' already exists; no need to create schema = again.
    +[NsSampleClientThread] Thread id - 1; started.
    +[NsSampleWork] Thread id - 1; requests database connection, dbUrl =3Djdbc:= derby:NSSampledb;
    +[NsSampleClientThread] Thread id - 2; started.
    +[NsSampleWork] Thread id - 2; requests database connection, dbUrl
    =3Dj= dbc:derby:net://localhost:1621/NSSampledb;create=3Dtrue:retrieveMessagesFro= mServerOnGetMessage=3Dtrue;deferPrepares=3Dtrue;
    +Connection number: 3.
    +[NsSampleWork] Thread id - 1 selected 1 row [61,Derby28 ,3.20918E21= ,9854]
    +[NsSampleWork] Thread id - 1; inserted 1 row.
    +[NsSampleWork] Thread id - 1; deleted 1 row with t_key =3D 9854
    +[NsSampleWork] Thread id - 1; inserted 1 row.
    +[NsSampleWork] Thread id - 1; deleted 1 row with t_key =3D 9818
    +[NsSampleWork] Thread id - 2; deleted 0 row with t_key =3D 9854
    +[NsSampleWork] Thread id - 1; updated 1 row with t_key =3D 9481
    +[NsSampleWork] Thread id - 1; updated 1 row with t_key =3D 9481
    +[NsSampleWork] Thread id - 1; updated 0 row with t_key =3D 9481
    +[NsSampleWork] Thread id - 2; deleted 1 row with t_key =3D 9481
    +[NsSampleWork] Thread id - 1; inserted 1 row.
    +[NsSampleWork] Thread id - 1; updated 1 row with t_key =3D 9150
    +[NsSampleWork] Thread id - 1; closed connection to the database.
    +[NsSampleClientThread] Thread id - 1; finished all tasks.
    +[NsSampleWork] Thread id - 2 selected 1 row [57,Derby18 ,7.873628,9= 150]
    +[NsSampleWork] Thread id - 2; updated 1 row with t_key =3D 9150
    +[NsSampleWork] Thread id - 2 selected 1 row [58,Derby18 ,7.873628,9= 150]
    +[NsSampleWork] Thread id - 2; inserted 1 row.
    +[NsSampleWork] Thread id - 2 selected 1 row [58,Derby18 ,7.873628,9= 150]
    +[NsSampleWork] Thread id - 2; inserted 1 row.
    +[NsSampleWork] Thread id - 2; updated 1 row with t_key =3D 9150
    +[NsSampleWork] Thread id - 2 selected 1 row [61,Derby18 ,7.873628,9= 150]
    +[NsSampleWork] Thread id - 2; closed connection to the database.
    +[NsSampleClientThread] Thread id - 2; finished all tasks.
    +[NsSample] Shutting down network server.
    +Connection number: 4.
    +Shutdown successful.
    +[NsSample] End of Network server demo.
    + +

    Running the demo program will also create new directories and files:

    +
      +
    • NSSampledb
      This directory make= s up the=20 +NSSampledb database.
    • +
    • derby.log
      This log file contains Derby progress and erro= r messages.
    • +
    + + + + Propchange: incubator/derby/code/trunk/java/demo/nserverdemo/nserverdemo.ht= ml ---------------------------------------------------------------------------= --- svn:eol-style =3D native