db-derby-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From fuzzylo...@apache.org
Subject svn commit: r164630 [2/3] - in /incubator/derby/code/trunk/java/demo: ./ nserverdemo/ simple/
Date Mon, 25 Apr 2005 19:29:38 GMT
Modified: incubator/derby/code/trunk/java/demo/nserverdemo/NsSampleClientThread.java
URL: http://svn.apache.org/viewcvs/incubator/derby/code/trunk/java/demo/nserverdemo/NsSampleClientThread.java?rev=164630&r1=164629&r2=164630&view=diff
==============================================================================
--- incubator/derby/code/trunk/java/demo/nserverdemo/NsSampleClientThread.java (original)
+++ incubator/derby/code/trunk/java/demo/nserverdemo/NsSampleClientThread.java 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, as 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,PrintWriter pw) {
-		this.thread_id=id;
-		this.dbUrl = dbUrl;
-		this.properties = properties;
-		this.pw = pw;
-	}
-
-   public void run() {
-	 System.out.println("[NsSampleClientThread] Thread id - "+this.thread_id + "; started.");
-	 NsSampleWork w = new NsSampleWork(this.thread_id,dbUrl,properties,pw);
-	 w.doWork();  // do all the NsSampleWork
-	 pw.println("[NsSampleClientThread] Thread id - "+this.thread_id+"; finished all tasks.");
-   }
-}
-
-
-
-/**
- * NsSampleWork class represents all the work done in the sample demo program.
- * It includes
- * getting a connection to the database, creating and loading of schema,
- * preparing and execution of SQL statements (insert, select, update, delete )
- */
-class NsSampleWork {
-
-	protected int thread_id;
-	protected String dbUrl;
-	protected Properties properties;
-	PrintWriter pw;
-	PreparedStatement select = null;
-	PreparedStatement insert = null;
-	PreparedStatement delete = null;
-	PreparedStatement update = null;
-	PreparedStatement getMaxKey = null;
-
-
-
-	public static int counter=0;
-	static Integer lock = new Integer(0);
-	 /**
-	  * dbUrl is the database url to connect to
-	  */
-	 NsSampleWork(int id, String dbURL,Properties properties,PrintWriter pw) {
-		this.thread_id = id;
-		this.dbUrl = dbURL;
-		this.pw = pw;
-		this.properties = 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 = null;
-		 try {
-			pw.println("[NsSampleWork] Thread id - "+thread_id + "; requests database connection, dbUrl ="+dbUrl);
-			conn = DriverManager.getConnection(dbUrl, properties);
-		  } catch (Exception e) {
-			 System.out.println("[NsSampleWork] Thread id - "+ thread_id + "; failed 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 +"; setIsolationLevel failed. Exception thrown: ");
-			 e.printStackTrace();
-		   }
-	 }
-
-
-	 /**
-	  * close connection
-	  */
-	 public void closeConnection(Connection conn) {
-		 try {
-			if(conn != null)
-			 	conn.close();
-			pw.println("[NsSampleWork] Thread id - "+thread_id + "; closed connection to the database.");
-		 } catch (Exception e) {
-			 pw.println("[NsSampleWork] Thread id - "+thread_id + "; error when closing connection;"+ e);
-			 e.printStackTrace();
-		   }
-	 }
-
-
-	 /**
-	  * prepare required sql statements
-	  */
-	 public void prepareStmts(Connection conn) {
-		 try {
-		 	select = conn.prepareStatement("select t_int,  t_char, t_float,t_key from SAMPLETBL where t_key = ?");
-		 	insert = conn.prepareStatement("insert into SAMPLETBL (t_int, t_char,t_float,t_key) values (?,?,?,?)");
-		 	update = conn.prepareStatement(" update SAMPLETBL set t_int = ? where t_key = ?");
-		 	delete = conn.prepareStatement("delete from SAMPLETBL where t_key = ?");
-		 	getMaxKey = 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 = 0;
-		 ResultSet rs = null;
-
-		 try {
-			 select.setLong(1,selectWhat);
-			 rs = select.executeQuery();
-
-			 while (rs.next()) {
-				 numRowsSelected++;
-
-				 int intVal = rs.getInt(1);
-				 String strVal = rs.getString(2);
-				 float floatVal = rs.getFloat(3);
-				 long longVal = rs.getLong(4); 	//t_key column
-
-				 pw.println("[NsSampleWork] Thread id - "+ thread_id +" selected "+numRowsSelected +" row ["+ intVal + ","
-				 			+ strVal +","+ floatVal +","+ longVal +"]");
-			 }
-		 } catch (Exception e) {
-			e.printStackTrace();
-		   } finally {
-			   try {
-			 	if(rs != 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 = null;
-	   ResultSet rs = null;
-	   try {
-		 conn = getConnection(dbUrl,properties);
-
-		 if(conn == 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=0; i<NsSample.ITERATIONS; i++) {
-			 // Choose between either a select or any one of (insert or update or delete ) operation
-			 int choice = (int) (Math.random() * 100) % 2;
-			 switch (choice) {
-				 case 0: { //select a row
-					rs = getMaxKey.executeQuery(); //gets max t_key value
-					long selectWhere = 0;
-					if(rs.next()) {
-						selectWhere = rs.getLong(1);
-					}
-					int numSelected = doSelectOperation(selectWhere);
-					break;
-				 }
-
-				 case 1: { //do an insert, update or delete
-					doIUDOperation();
-					break;
-				 }
-			 } //end of switch()
-		 }//enf of for()
-
-	   } catch(Exception e) {
-		   pw.println("[NsSampleWork] Thread id - "+ thread_id + "; error when performing dml operations; ");
-		   e.printStackTrace();
-	     } finally {
-		   	try {
-				if(rs != null)
-					rs.close();
-
-				closeConnection(conn);
-				cleanup();
-		    } catch(Exception ee) {
-			   pw.println("[NsSampleWork] Thread id - " + thread_id+"; error when cleaning up connection, resultset; exception is ");
-			   ee.printStackTrace();
-		      }
-	       }
-	 }//end of method doNsSampleWork()
-
-
-	/**
-	 * close resources
-	 */
-	public void cleanup() {
-	  try{
-		if(select != null)
-			select.close();
-		if(insert != null)
-			insert.close();
-		if(delete != null)
-			delete.close();
-		if(update != null)
-			update.close();
-		if(getMaxKey != null)
-			getMaxKey.close();
-  	  } catch (Exception e) {
-		  e.printStackTrace();
-	    }
-	}
-
-
-	 /**
-	  * Perform an insert or an update or delete operation
-	  */
-	 public void doIUDOperation() {
-		 int decide = (int) (Math.random() * 100) % 3;
-		 ResultSet rs = null;
-
-		 try {
-			switch (decide) {
-				 case 0: { //insert
-						int numInsert = insertRow(insert);
-						pw.println("[NsSampleWork] Thread id - "+thread_id+"; inserted "+numInsert+" row.");
-						break;
-				 }
-
-				 case 1: { //update
-						rs = getMaxKey.executeQuery();
-						long updateRow=0;
-						if(rs.next())
-							updateRow = rs.getLong(1);
-						int numUpdate = updateRow(update,updateRow);
-						System.out.println("[NsSampleWork] Thread id - "+thread_id+"; updated "+numUpdate+" row with t_key = " + updateRow);
-						break;
-				 }
-
-				 case 2: { //delete
-						rs = getMaxKey.executeQuery();
-						long deleteRow =0;
-						if(rs.next())
-							deleteRow = rs.getLong(1);
-						int numDelete = deleteRow(delete,deleteRow);
-						System.out.println("[NsSampleWork] Thread id - "+thread_id+"; deleted "+numDelete+" row with t_key = " + deleteRow);
-						break;
-				 }
-		 	}//end of switch()
-	 	} catch (Exception e) {
-			e.printStackTrace();
-		  } finally {
-			  try {
-			  	if(rs != null)
-				  rs.close();
-			  } catch (Exception e) {
-				  e.printStackTrace();
-			    }
-		    }
-	 }//end of method doIUDOperation()
-
-
-	 /**
-	  * Create necessary schema if schema not already created
-	  */
-	 public static void checkAndCreateSchema(Connection conn,PrintWriter pw) {
-		Statement stmt = null;
-		ResultSet rs = null;
-
-		try	{
-			conn.setAutoCommit(true);
-		} catch (SQLException  se) {
-			pw.println("[NsSampleWork] Error when setting autocommit on connection; exception thrown: ");
-			se.printStackTrace();
-		  }
-
-		// Check for existence of schema by quering the catalog systables
-		try {
-			stmt = conn.createStatement();
-			rs = stmt.executeQuery("select tablename from sys.systables " +
-								" where tablename = 'SAMPLETBL'");
-			if (rs.next()) {
-				pw.println("[NsSampleWork] Table 'SAMPLETBL' already exists; no need to create schema again.");
-				return;
-			}
-		} catch (SQLException  se) {
-			pw.println("[NsSampleWork] Unable to query the metadata for existence of table SAMPLETBL; exception is "+se);
-			pw.println("[NsSampleWork] Exiting the application.");
-			se.printStackTrace();
-			System.exit(1);
-		  }
-
-		// Create the necessary table and indexes
-		try {
-			pw.println("[NsSampleWork] Begin creating table - SAMPLETBL and necessary indexes. ");
-			stmt.execute("create table SAMPLETBL (" +
-						  "t_int int," +
-						  "t_char char(15),"+
-						  "t_float float," +
-						  "t_key bigint )");
-			stmt.execute("create index t_char_idx on SAMPLETBL ( t_char)");
-			stmt.execute("create index t_float_idx on SAMPLETBL ( t_float)");
-			stmt.execute("create index t_key_idx on SAMPLETBL ( t_key )" );
-		} catch (Exception  e) {
-			pw.println("[NsSampleWork] Error when creating schema; exception is " + e.toString());
-			pw.println("[NsSampleWork] Exiting the application.");
-			e.printStackTrace();
-			System.exit(1);
-		  } finally {
-			  try {
-			  	if(rs != null)
-				  rs.close();
-			  	if(stmt != null)
-				  stmt.close();
-			  } catch (Exception e) {
-				  e.printStackTrace();
-			    }
-			}
-	 }//end of method checkAndCreateSchema()
-
-
-	 /**
-	  * Loads schema , inserts 'rowsToInsert' number of rows into the table
-	  */
-	 public static void loadSchema(Connection conn,int rowsToInsert,PrintWriter pw)	 {
-		 int insertsRemaining = rowsToInsert;
-		 PreparedStatement ps=null;
-
-		 try {
-			ps = conn.prepareStatement("insert into SAMPLETBL (t_int, t_char,t_float,t_key) values (?,?,?,?)");
-			// Insert one row at a time
-			while (insertsRemaining-- >= 0)	{
-				 int numInserts = insertRow(ps);
-				 if (numInserts != 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 != 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 = 0;
-		try	{
-			// Generate random values for the datatypes in the sample table
-			Random rand = new Random();
-			int intVal = Math.abs(rand.nextInt()%1000);
-
-			String charVal = "Derby";
-
-			synchronized(lock) {
-				charVal += 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.nextInt()%30)));
-			ps.setLong(4,rand.nextLong()%10000);
-			rowsAdded = 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=0;
-		  synchronized(lock) {
-			val = 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 = 0;
-		try	{
-			ps.setLong(1, deleteRow);
-			rowsDeleted = 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, as 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,PrintWriter pw) {
+		this.thread_id=id;
+		this.dbUrl = dbUrl;
+		this.properties = properties;
+		this.pw = pw;
+	}
+
+   public void run() {
+	 System.out.println("[NsSampleClientThread] Thread id - "+this.thread_id + "; started.");
+	 NsSampleWork w = new NsSampleWork(this.thread_id,dbUrl,properties,pw);
+	 w.doWork();  // do all the NsSampleWork
+	 pw.println("[NsSampleClientThread] Thread id - "+this.thread_id+"; finished all tasks.");
+   }
+}
+
+
+
+/**
+ * NsSampleWork class represents all the work done in the sample demo program.
+ * It includes
+ * getting a connection to the database, creating and loading of schema,
+ * preparing and execution of SQL statements (insert, select, update, delete )
+ */
+class NsSampleWork {
+
+	protected int thread_id;
+	protected String dbUrl;
+	protected Properties properties;
+	PrintWriter pw;
+	PreparedStatement select = null;
+	PreparedStatement insert = null;
+	PreparedStatement delete = null;
+	PreparedStatement update = null;
+	PreparedStatement getMaxKey = null;
+
+
+
+	public static int counter=0;
+	static Integer lock = new Integer(0);
+	 /**
+	  * dbUrl is the database url to connect to
+	  */
+	 NsSampleWork(int id, String dbURL,Properties properties,PrintWriter pw) {
+		this.thread_id = id;
+		this.dbUrl = dbURL;
+		this.pw = pw;
+		this.properties = 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 = null;
+		 try {
+			pw.println("[NsSampleWork] Thread id - "+thread_id + "; requests database connection, dbUrl ="+dbUrl);
+			conn = DriverManager.getConnection(dbUrl, properties);
+		  } catch (Exception e) {
+			 System.out.println("[NsSampleWork] Thread id - "+ thread_id + "; failed 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 +"; setIsolationLevel failed. Exception thrown: ");
+			 e.printStackTrace();
+		   }
+	 }
+
+
+	 /**
+	  * close connection
+	  */
+	 public void closeConnection(Connection conn) {
+		 try {
+			if(conn != null)
+			 	conn.close();
+			pw.println("[NsSampleWork] Thread id - "+thread_id + "; closed connection to the database.");
+		 } catch (Exception e) {
+			 pw.println("[NsSampleWork] Thread id - "+thread_id + "; error when closing connection;"+ e);
+			 e.printStackTrace();
+		   }
+	 }
+
+
+	 /**
+	  * prepare required sql statements
+	  */
+	 public void prepareStmts(Connection conn) {
+		 try {
+		 	select = conn.prepareStatement("select t_int,  t_char, t_float,t_key from SAMPLETBL where t_key = ?");
+		 	insert = conn.prepareStatement("insert into SAMPLETBL (t_int, t_char,t_float,t_key) values (?,?,?,?)");
+		 	update = conn.prepareStatement(" update SAMPLETBL set t_int = ? where t_key = ?");
+		 	delete = conn.prepareStatement("delete from SAMPLETBL where t_key = ?");
+		 	getMaxKey = 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 = 0;
+		 ResultSet rs = null;
+
+		 try {
+			 select.setLong(1,selectWhat);
+			 rs = select.executeQuery();
+
+			 while (rs.next()) {
+				 numRowsSelected++;
+
+				 int intVal = rs.getInt(1);
+				 String strVal = rs.getString(2);
+				 float floatVal = rs.getFloat(3);
+				 long longVal = rs.getLong(4); 	//t_key column
+
+				 pw.println("[NsSampleWork] Thread id - "+ thread_id +" selected "+numRowsSelected +" row ["+ intVal + ","
+				 			+ strVal +","+ floatVal +","+ longVal +"]");
+			 }
+		 } catch (Exception e) {
+			e.printStackTrace();
+		   } finally {
+			   try {
+			 	if(rs != 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 = null;
+	   ResultSet rs = null;
+	   try {
+		 conn = getConnection(dbUrl,properties);
+
+		 if(conn == 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=0; i<NsSample.ITERATIONS; i++) {
+			 // Choose between either a select or any one of (insert or update or delete ) operation
+			 int choice = (int) (Math.random() * 100) % 2;
+			 switch (choice) {
+				 case 0: { //select a row
+					rs = getMaxKey.executeQuery(); //gets max t_key value
+					long selectWhere = 0;
+					if(rs.next()) {
+						selectWhere = rs.getLong(1);
+					}
+					int numSelected = doSelectOperation(selectWhere);
+					break;
+				 }
+
+				 case 1: { //do an insert, update or delete
+					doIUDOperation();
+					break;
+				 }
+			 } //end of switch()
+		 }//enf of for()
+
+	   } catch(Exception e) {
+		   pw.println("[NsSampleWork] Thread id - "+ thread_id + "; error when performing dml operations; ");
+		   e.printStackTrace();
+	     } finally {
+		   	try {
+				if(rs != null)
+					rs.close();
+
+				closeConnection(conn);
+				cleanup();
+		    } catch(Exception ee) {
+			   pw.println("[NsSampleWork] Thread id - " + thread_id+"; error when cleaning up connection, resultset; exception is ");
+			   ee.printStackTrace();
+		      }
+	       }
+	 }//end of method doNsSampleWork()
+
+
+	/**
+	 * close resources
+	 */
+	public void cleanup() {
+	  try{
+		if(select != null)
+			select.close();
+		if(insert != null)
+			insert.close();
+		if(delete != null)
+			delete.close();
+		if(update != null)
+			update.close();
+		if(getMaxKey != null)
+			getMaxKey.close();
+  	  } catch (Exception e) {
+		  e.printStackTrace();
+	    }
+	}
+
+
+	 /**
+	  * Perform an insert or an update or delete operation
+	  */
+	 public void doIUDOperation() {
+		 int decide = (int) (Math.random() * 100) % 3;
+		 ResultSet rs = null;
+
+		 try {
+			switch (decide) {
+				 case 0: { //insert
+						int numInsert = insertRow(insert);
+						pw.println("[NsSampleWork] Thread id - "+thread_id+"; inserted "+numInsert+" row.");
+						break;
+				 }
+
+				 case 1: { //update
+						rs = getMaxKey.executeQuery();
+						long updateRow=0;
+						if(rs.next())
+							updateRow = rs.getLong(1);
+						int numUpdate = updateRow(update,updateRow);
+						System.out.println("[NsSampleWork] Thread id - "+thread_id+"; updated "+numUpdate+" row with t_key = " + updateRow);
+						break;
+				 }
+
+				 case 2: { //delete
+						rs = getMaxKey.executeQuery();
+						long deleteRow =0;
+						if(rs.next())
+							deleteRow = rs.getLong(1);
+						int numDelete = deleteRow(delete,deleteRow);
+						System.out.println("[NsSampleWork] Thread id - "+thread_id+"; deleted "+numDelete+" row with t_key = " + deleteRow);
+						break;
+				 }
+		 	}//end of switch()
+	 	} catch (Exception e) {
+			e.printStackTrace();
+		  } finally {
+			  try {
+			  	if(rs != null)
+				  rs.close();
+			  } catch (Exception e) {
+				  e.printStackTrace();
+			    }
+		    }
+	 }//end of method doIUDOperation()
+
+
+	 /**
+	  * Create necessary schema if schema not already created
+	  */
+	 public static void checkAndCreateSchema(Connection conn,PrintWriter pw) {
+		Statement stmt = null;
+		ResultSet rs = null;
+
+		try	{
+			conn.setAutoCommit(true);
+		} catch (SQLException  se) {
+			pw.println("[NsSampleWork] Error when setting autocommit on connection; exception thrown: ");
+			se.printStackTrace();
+		  }
+
+		// Check for existence of schema by quering the catalog systables
+		try {
+			stmt = conn.createStatement();
+			rs = stmt.executeQuery("select tablename from sys.systables " +
+								" where tablename = 'SAMPLETBL'");
+			if (rs.next()) {
+				pw.println("[NsSampleWork] Table 'SAMPLETBL' already exists; no need to create schema again.");
+				return;
+			}
+		} catch (SQLException  se) {
+			pw.println("[NsSampleWork] Unable to query the metadata for existence of table SAMPLETBL; exception is "+se);
+			pw.println("[NsSampleWork] Exiting the application.");
+			se.printStackTrace();
+			System.exit(1);
+		  }
+
+		// Create the necessary table and indexes
+		try {
+			pw.println("[NsSampleWork] Begin creating table - SAMPLETBL and necessary indexes. ");
+			stmt.execute("create table SAMPLETBL (" +
+						  "t_int int," +
+						  "t_char char(15),"+
+						  "t_float float," +
+						  "t_key bigint )");
+			stmt.execute("create index t_char_idx on SAMPLETBL ( t_char)");
+			stmt.execute("create index t_float_idx on SAMPLETBL ( t_float)");
+			stmt.execute("create index t_key_idx on SAMPLETBL ( t_key )" );
+		} catch (Exception  e) {
+			pw.println("[NsSampleWork] Error when creating schema; exception is " + e.toString());
+			pw.println("[NsSampleWork] Exiting the application.");
+			e.printStackTrace();
+			System.exit(1);
+		  } finally {
+			  try {
+			  	if(rs != null)
+				  rs.close();
+			  	if(stmt != null)
+				  stmt.close();
+			  } catch (Exception e) {
+				  e.printStackTrace();
+			    }
+			}
+	 }//end of method checkAndCreateSchema()
+
+
+	 /**
+	  * Loads schema , inserts 'rowsToInsert' number of rows into the table
+	  */
+	 public static void loadSchema(Connection conn,int rowsToInsert,PrintWriter pw)	 {
+		 int insertsRemaining = rowsToInsert;
+		 PreparedStatement ps=null;
+
+		 try {
+			ps = conn.prepareStatement("insert into SAMPLETBL (t_int, t_char,t_float,t_key) values (?,?,?,?)");
+			// Insert one row at a time
+			while (insertsRemaining-- >= 0)	{
+				 int numInserts = insertRow(ps);
+				 if (numInserts != 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 != 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 = 0;
+		try	{
+			// Generate random values for the datatypes in the sample table
+			Random rand = new Random();
+			int intVal = Math.abs(rand.nextInt()%1000);
+
+			String charVal = "Derby";
+
+			synchronized(lock) {
+				charVal += 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.nextInt()%30)));
+			ps.setLong(4,rand.nextLong()%10000);
+			rowsAdded = 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=0;
+		  synchronized(lock) {
+			val = 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 = 0;
+		try	{
+			ps.setLong(1, deleteRow);
+			rowsDeleted = ps.executeUpdate();
+			return rowsDeleted;
+		} catch(Exception e) {
+			e.printStackTrace();
+			return 0;
+		  }
+	}
+
+}//end of class NsSampleWork

Propchange: incubator/derby/code/trunk/java/demo/nserverdemo/NsSampleClientThread.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkClientSample.java
URL: http://svn.apache.org/viewcvs/incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkClientSample.java?rev=164630&r1=164629&r2=164630&view=diff
==============================================================================
--- incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkClientSample.java (original)
+++ incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkClientSample.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, as 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 Server is up
- * and running.
- *  <P>
- *  Usage: java SimpleNetworkClientSample
- *
- */
-public class SimpleNetworkClientSample
-{
-
-	/*
-	 * The database is located in the same directory where this program is being
-	 * run. Alternately one can specify the absolute path of the database location
-	 */
-	private static String DBNAME="NSSimpleDB";
-
-	/**
-	 * Derby network server port ; default is 1527
-	 */
-	private static int NETWORKSERVER_PORT=1527;
-
-	/**
-	 * DB2 JDBC UNIVERSAL DRIVER class names
-	 */
-	private static final String DB2_JDBC_UNIVERSAL_DRIVER = "com.ibm.db2.jcc.DB2Driver";
-	private static final String DB2_JCC_DS = "com.ibm.db2.jcc.DB2SimpleDataSource";
-
-	/**
-	 * This URL is used to connect to Derby Network Server using the DriverManager.
-	 * 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= "jdbc:derby:net://localhost:"+NETWORKSERVER_PORT+"/"+DBNAME+";retrieveMessagesFromServerOnGetMessage=true;deferPrepares=true;";
-
-
-	public static void main (String[] args)
-		throws Exception
-	{
-		DataSource clientDataSource = null;
-		Connection clientConn1 = null;
-		Connection clientConn2 = 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 = getClientDriverManagerConnection();
-			System.out.println("Got a client connection via the DriverManager.");
-
-			// create a datasource with the necessary information
-			javax.sql.DataSource myDataSource = getClientDataSource(DBNAME, null, null);
-
-			// get a client connection using DataSource
-			clientConn2 = 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 by 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 != null)
-				clientConn1.close();
-			if(clientConn2 != 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 = ds.getConnection("usr2", "pass2");
-		System.out.print("connection from datasource; getDriverName = ");
-		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, String user, String
-									  password) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException
-	{
-		Class nsDataSource = Class.forName(DB2_JCC_DS);
-		DataSource ds = (DataSource) nsDataSource.newInstance();
-
-		// can also include Derby URL attributes along with the database name
-		Class[] methodParams = new Class[] {String.class};
-		Method dbname = nsDataSource.getMethod("setDatabaseName", methodParams);
-		Object[] args = new Object[] {database};
-		dbname.invoke(ds, args);
-
-		if (user != null) {
-			Method setuser = nsDataSource.getMethod("setUser", methodParams);
-			args = new Object[] {user};
-			setuser.invoke(ds, args);
-		}
-		if (password != null) {
-			Method setpw = nsDataSource.getMethod("setPassword", methodParams);
-			args = new Object[] {password};
-			setpw.invoke(ds, args);
-		}
-		// host on which network server is running
-		Method servername = nsDataSource.getMethod("setServerName", methodParams);
-		args = new Object[] {"localhost"};
-		servername.invoke(ds, args);
-
-		// port on which Network Server is listening
-		methodParams = new Class[] {int.class};
-		Method portnumber = nsDataSource.getMethod("setPortNumber", methodParams);
-		args = new Object[] {new Integer(1527)};
-		portnumber.invoke(ds, args);
-
-		// driver type must be 4 to access Derby Network Server
-		Method drivertype = nsDataSource.getMethod("setDriverType", methodParams);
-		args = 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 this 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 = 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 = DriverManager.getConnection(CS_NS_DBURL,properties); 
-
-		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 = null;
-	  ResultSet rs = null;
-	  try
-	  {
-		// To test our connection, we will try to do a select from the system catalog tables
-		stmt = conn.createStatement();
-		rs = stmt.executeQuery("select count(*) from sys.systables");
-		while(rs.next())
-			System.out.println("number of rows in sys.systables = "+ rs.getInt(1));
-
-	  }
-	  catch(SQLException sqle)
-	  {
-		  System.out.println("SQLException when querying on the database connection; "+ sqle);
-		  throw sqle;
-  	  }
-  	  finally
-  	  {
-		  if(rs != null)
-		  	rs.close();
-		  if(stmt != null)
-		  	stmt.close();
- 	  }
-	}
-}
-
-
-
-
-
-
+/*
+
+   Derby - Class SimpleNetworkClientSample
+
+   Copyright 2003, 2004 The Apache Software Foundation or its licensors, as 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 Server is up
+ * and running.
+ *  <P>
+ *  Usage: java SimpleNetworkClientSample
+ *
+ */
+public class SimpleNetworkClientSample
+{
+
+	/*
+	 * The database is located in the same directory where this program is being
+	 * run. Alternately one can specify the absolute path of the database location
+	 */
+	private static String DBNAME="NSSimpleDB";
+
+	/**
+	 * Derby network server port ; default is 1527
+	 */
+	private static int NETWORKSERVER_PORT=1527;
+
+	/**
+	 * DB2 JDBC UNIVERSAL DRIVER class names
+	 */
+	private static final String DB2_JDBC_UNIVERSAL_DRIVER = "com.ibm.db2.jcc.DB2Driver";
+	private static final String DB2_JCC_DS = "com.ibm.db2.jcc.DB2SimpleDataSource";
+
+	/**
+	 * This URL is used to connect to Derby Network Server using the DriverManager.
+	 * 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= "jdbc:derby:net://localhost:"+NETWORKSERVER_PORT+"/"+DBNAME+";retrieveMessagesFromServerOnGetMessage=true;deferPrepares=true;";
+
+
+	public static void main (String[] args)
+		throws Exception
+	{
+		DataSource clientDataSource = null;
+		Connection clientConn1 = null;
+		Connection clientConn2 = 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 = getClientDriverManagerConnection();
+			System.out.println("Got a client connection via the DriverManager.");
+
+			// create a datasource with the necessary information
+			javax.sql.DataSource myDataSource = getClientDataSource(DBNAME, null, null);
+
+			// get a client connection using DataSource
+			clientConn2 = 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 by 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 != null)
+				clientConn1.close();
+			if(clientConn2 != 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 = ds.getConnection("usr2", "pass2");
+		System.out.print("connection from datasource; getDriverName = ");
+		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, String user, String
+									  password) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException
+	{
+		Class nsDataSource = Class.forName(DB2_JCC_DS);
+		DataSource ds = (DataSource) nsDataSource.newInstance();
+
+		// can also include Derby URL attributes along with the database name
+		Class[] methodParams = new Class[] {String.class};
+		Method dbname = nsDataSource.getMethod("setDatabaseName", methodParams);
+		Object[] args = new Object[] {database};
+		dbname.invoke(ds, args);
+
+		if (user != null) {
+			Method setuser = nsDataSource.getMethod("setUser", methodParams);
+			args = new Object[] {user};
+			setuser.invoke(ds, args);
+		}
+		if (password != null) {
+			Method setpw = nsDataSource.getMethod("setPassword", methodParams);
+			args = new Object[] {password};
+			setpw.invoke(ds, args);
+		}
+		// host on which network server is running
+		Method servername = nsDataSource.getMethod("setServerName", methodParams);
+		args = new Object[] {"localhost"};
+		servername.invoke(ds, args);
+
+		// port on which Network Server is listening
+		methodParams = new Class[] {int.class};
+		Method portnumber = nsDataSource.getMethod("setPortNumber", methodParams);
+		args = new Object[] {new Integer(1527)};
+		portnumber.invoke(ds, args);
+
+		// driver type must be 4 to access Derby Network Server
+		Method drivertype = nsDataSource.getMethod("setDriverType", methodParams);
+		args = 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 this 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 = 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 = DriverManager.getConnection(CS_NS_DBURL,properties); 
+
+		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 = null;
+	  ResultSet rs = null;
+	  try
+	  {
+		// To test our connection, we will try to do a select from the system catalog tables
+		stmt = conn.createStatement();
+		rs = stmt.executeQuery("select count(*) from sys.systables");
+		while(rs.next())
+			System.out.println("number of rows in sys.systables = "+ rs.getInt(1));
+
+	  }
+	  catch(SQLException sqle)
+	  {
+		  System.out.println("SQLException when querying on the database connection; "+ sqle);
+		  throw sqle;
+  	  }
+  	  finally
+  	  {
+		  if(rs != null)
+		  	rs.close();
+		  if(stmt != null)
+		  	stmt.close();
+ 	  }
+	}
+}
+
+
+
+
+
+

Propchange: incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkClientSample.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkServerSample.java
URL: http://svn.apache.org/viewcvs/incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkServerSample.java?rev=164630&r1=164629&r2=164630&view=diff
==============================================================================
--- incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkServerSample.java (original)
+++ incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkServerSample.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, as 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 accessing
- * to serve the clients from other JVMs. This solution allows you to take
- * advantage of the performance benefits of embedded driver as well as allow
- * 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 directory
- * created if not present already and there will be a derby.log file which
- * contains messages from Derby
- *
- *  <P>
- *  Usage: java SimpleNetworkServerSample
- *
- */
-public class SimpleNetworkServerSample
-{
-
-	/*
-	 * The database is located in the same directory where this program is being
-	 * run. Alternately one can specify the absolute path of the database location
-	 */
-	private static String DBNAME="NSSimpleDB";
-
-
-	public static void main (String[] args)
-		throws Exception
-	{
-		Connection embeddedConn = 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 embedded
-			// 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 = getEmbeddedConnection(DBNAME,"create=true;");
-			System.out.println("Got an embedded connection.");
-
-
-			System.out.println("Testing embedded connection by executing a sample query ");
-			// test connections by doing some work
-			test(embeddedConn);
-
-			// print how to connect to the network server using ij
-			String howToConnect = ijUsage();
-			System.out.println(howToConnect);
-
-			waitForExit();
-
-		}
-		catch (SQLException sqle)
-		{
-			System.out.println("Failure making connection: " + sqle);
-			sqle.printStackTrace();
-		}
-		finally
-		{
-
-			if(embeddedConn != null)
-				embeddedConn.close();
-			try
-			{
-				// shutdown Derby Network Server
-				DriverManager.getConnection("jdbc:derby:;shutdown=true");
-			}
-			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 property 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 = 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 = new NetworkServerControl();
-
-		System.out.println("Testing if Network Server is up and running!");
-		for (int i = 0; i < 10 ; i ++)
-		{
-			try {
-
-				Thread.currentThread().sleep(5000);
-				server.ping();
-			}
-			catch (Exception e)
-			{
-				System.out.println("Try #" + i + " " +e.toString());
-				if (i == 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=true;
-	 *					 upgrade=true;
-	 * @return	returns embedded database connection
-	 * @throws Exception if there is any error
-	 */
-	public static Connection getEmbeddedConnection(String database,String attributes)
-		throws Exception
-	{
-		String dbUrl = "jdbc:derby:"+database +";"+attributes;
-		Connection conn = 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 = null;
-	  ResultSet rs = null;
-	  try
-	  {
-		// To test our connection, we will try to do a select from the system catalog tables
-		stmt = conn.createStatement();
-		rs = stmt.executeQuery("select count(*) from sys.systables");
-		while(rs.next())
-			System.out.println("number of rows in sys.systables = "+ rs.getInt(1));
-
-	  }
-	  catch(SQLException sqle)
-	  {
-		  System.out.println("SQLException when querying on the database connection; "+ sqle);
-		  throw sqle;
-  	  }
-  	  finally
-  	  {
-		  if(rs != null)
-		  	rs.close();
-		  if(stmt != 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 other
-	 * 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 =
- 			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 Network Server
-	 */
-	private static String ijUsage()
-	{
-
-		String ijUsage = "\nWhile my app is busy with embedded work, ";
-		ijUsage += "ij might connect like this:\n\n";
-		ijUsage +=  "\t$ java -Dij.user=me -Dij.password=pw -Dij.protocol=jdbc:derby:net://localhost:1527/ org.apache.derby.tools.ij\n";
-		ijUsage += "\tij> connect '" + DBNAME + ":retrieveMessagesFromServerOnGetMessage=true;';\n";
-		ijUsage += "Watch that punctuation.  Put a ':' before the jcc\n";
-		ijUsage += "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, as 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 accessing
+ * to serve the clients from other JVMs. This solution allows you to take
+ * advantage of the performance benefits of embedded driver as well as allow
+ * 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 directory
+ * created if not present already and there will be a derby.log file which
+ * contains messages from Derby
+ *
+ *  <P>
+ *  Usage: java SimpleNetworkServerSample
+ *
+ */
+public class SimpleNetworkServerSample
+{
+
+	/*
+	 * The database is located in the same directory where this program is being
+	 * run. Alternately one can specify the absolute path of the database location
+	 */
+	private static String DBNAME="NSSimpleDB";
+
+
+	public static void main (String[] args)
+		throws Exception
+	{
+		Connection embeddedConn = 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 embedded
+			// 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 = getEmbeddedConnection(DBNAME,"create=true;");
+			System.out.println("Got an embedded connection.");
+
+
+			System.out.println("Testing embedded connection by executing a sample query ");
+			// test connections by doing some work
+			test(embeddedConn);
+
+			// print how to connect to the network server using ij
+			String howToConnect = ijUsage();
+			System.out.println(howToConnect);
+
+			waitForExit();
+
+		}
+		catch (SQLException sqle)
+		{
+			System.out.println("Failure making connection: " + sqle);
+			sqle.printStackTrace();
+		}
+		finally
+		{
+
+			if(embeddedConn != null)
+				embeddedConn.close();
+			try
+			{
+				// shutdown Derby Network Server
+				DriverManager.getConnection("jdbc:derby:;shutdown=true");
+			}
+			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 property 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 = 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 = new NetworkServerControl();
+
+		System.out.println("Testing if Network Server is up and running!");
+		for (int i = 0; i < 10 ; i ++)
+		{
+			try {
+
+				Thread.currentThread().sleep(5000);
+				server.ping();
+			}
+			catch (Exception e)
+			{
+				System.out.println("Try #" + i + " " +e.toString());
+				if (i == 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=true;
+	 *					 upgrade=true;
+	 * @return	returns embedded database connection
+	 * @throws Exception if there is any error
+	 */
+	public static Connection getEmbeddedConnection(String database,String attributes)
+		throws Exception
+	{
+		String dbUrl = "jdbc:derby:"+database +";"+attributes;
+		Connection conn = 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 = null;
+	  ResultSet rs = null;
+	  try
+	  {
+		// To test our connection, we will try to do a select from the system catalog tables
+		stmt = conn.createStatement();
+		rs = stmt.executeQuery("select count(*) from sys.systables");
+		while(rs.next())
+			System.out.println("number of rows in sys.systables = "+ rs.getInt(1));
+
+	  }
+	  catch(SQLException sqle)
+	  {
+		  System.out.println("SQLException when querying on the database connection; "+ sqle);
+		  throw sqle;
+  	  }
+  	  finally
+  	  {
+		  if(rs != null)
+		  	rs.close();
+		  if(stmt != 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 other
+	 * 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 =
+ 			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 Network Server
+	 */
+	private static String ijUsage()
+	{
+
+		String ijUsage = "\nWhile my app is busy with embedded work, ";
+		ijUsage += "ij might connect like this:\n\n";
+		ijUsage +=  "\t$ java -Dij.user=me -Dij.password=pw -Dij.protocol=jdbc:derby:net://localhost:1527/ org.apache.derby.tools.ij\n";
+		ijUsage += "\tij> connect '" + DBNAME + ":retrieveMessagesFromServerOnGetMessage=true;';\n";
+		ijUsage += "Watch that punctuation.  Put a ':' before the jcc\n";
+		ijUsage += "attributes and a ';' after each one (even the last).\n\n";
+
+		return ijUsage;
+	}
+}
+
+
+
+
+
+

Propchange: incubator/derby/code/trunk/java/demo/nserverdemo/SimpleNetworkServerSample.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/derby/code/trunk/java/demo/nserverdemo/nserverdemo.html
URL: http://svn.apache.org/viewcvs/incubator/derby/code/trunk/java/demo/nserverdemo/nserverdemo.html?rev=164630&r1=164629&r2=164630&view=diff
==============================================================================
--- incubator/derby/code/trunk/java/demo/nserverdemo/nserverdemo.html (original)
+++ incubator/derby/code/trunk/java/demo/nserverdemo/nserverdemo.html Mon Apr 25 12:29:37 2005
@@ -1,157 +1,157 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<HTML>
-<HEAD>
-<TITLE>Derby Network Server sample program</TITLE>
-<META http-equiv=Content-Type content="text/html; charset=iso-8859-1">
-</HEAD>
-<BODY>
-<H2><A name=Top_Of_Page></A><A name=nsrun></A><A name=nssample></A>Derby 
-Network Server sample program</H2>
-<P>The Network Server sample demo program (NsSample) is a simple JDBC application that 
-interacts with the Derby Network Server. The program:</P>
-<UL>
-  <LI>starts the Derby Network Server 
-  <LI>checks if the Derby Network Server is running 
-  <LI>loads the DB2 JDBC Universal Driver 
-  <LI>creates the database '<tt>NsSampledb</tt>' if not already created 
-  <LI>checks to see if the schema is already created, and if not, 
-  creates the schema which includes the <tt>SAMPLETBL</tt> table and corresponding 
-  indexes. 
-  <LI>connects to the database 
-  <LI>loads the schema by inserting data 
-  <LI>starts client threads to perform database related operations 
-  <LI>has each of the clients perform DML operations (select, insert, delete, update) 
-  using JDBC calls, in particular one client opens an embedded connection to 
-  perform database operations while the other client opens a client connection 
-  to the Derby Network Server to perform database operations. 
-  <LI>waits for the client threads to finish the tasks 
-  <LI>shuts down the Derby Network Server at the end of the demo </LI></UL>
-<P>The following files should be installed in the <SPAN 
-class=italic>%DERBY_INSTALL%</SPAN><TT>\demo\programs\nserverdemo\</TT> directory in 
-order to run the sample program:</P>
-<UL>
-  <LI><TT>NsSample.java</tt><br>
-This is the entry point into the demo application. The program starts up two clients. One client opens an embedded 
-connection to perform database operations while the other client opens a client 
-connection to the Derby Network Server to perform database operations.  This program provides the following constants that 
-can be changed to modify the sample demo:
-<UL>
-
-    <LI><tt>NUM_ROWS</tt> - The number of rows that must be initially loaded into the schema.</li>
-    <LI><tt>ITERATIONS</tt> - The number of iterations for which each client thread does database related work.</LI>
-<LI><tt>NUM_CLIENT_THREADS</tt> - The number of clients that you want to run the program against.</li> 
-    <LI><tt>NETWORKSERVER_PORT</tt> - The port on which the network server is running.</LI>
-</UL>
-
-You can also modify the program to exclude starting the Network Server as part of the sample program. 
-Make sure to recompile the java files before running the program if you make any 
-changes to the source code.
-
-</li>
-
-<li><tt>NsSampleClientThread.java</tt></br>
-This file contains two Java classes:
-  <UL>
-    <LI>The <tt>NsSampleClientThread</tt> class extends Thread and does all the 
-necessary work by instantiating a <tt>NsSampleWork</tt> instance.</li>
-    <LI>The <tt>NsSampleWork</tt> class contains everything required to perform 
-DML operations using JDBC calls. The <tt>doWork</tt> method in 
-the <tt>NsSampleWork</tt> class represents all the work done as 
-part of this sample program.</LI>
-</UL>
-</li>
-  <LI><tt>NetworkServerUtil.java</tt><br>
-This file contains helper methods to start the Derby Network Server and to shutdown the server.
-</li>
-  <LI>Compiled class files:
-<UL>
-    <LI><tt>NsSample.class</tt></li> 
-    <LI><tt>NsSampleClientThread.class</tt></li> 
-    <LI><tt>NsSampleWork.class</tt></li> 
-    <LI><tt>NetworkServerUtil.class</tt></li> 
-</UL>
-</li>
-</ul>
-
-
-<H2>Running the Network Server demo program</H2>
-<P>To run the Derby Network Server demonstration program:</P>
-<OL>
-  <LI>Open a command prompt and change directories to the <SPAN 
-  class=italic>%DERBY_INSTALL%</SPAN><tt>\demo\programs\</tt> directory, where <SPAN 
-  class=italic>%DERBY_INSTALL%</SPAN> is the directory where you installed Derby. 
-  <LI>Set the CLASSPATH to the current directory (".") and also include the following 
-  jar files in order to use the Derby Network Server and the DB2 JDBC Universal Driver.
-<ul>
-<li><tt>derbynet.jar</tt><br>The Network Server jar file. It must be in your CLASSPATH to use any of the Derby Network 
-Server functions.</li>
-<li><tt>db2jcc.jar</tt><br>This jar file must be in your CLASSPATH to use the 
-DB2 JDBC Universal Driver.</li>
-<li><tt>db2jcc_license_c.jar</tt><br>This jar file is the license file for the Universal 
-Driver.</li>
-<li><tt>derby.jar</tt><br>The Derby database engine jar file.</li>
-</ul>
-</LI>
-<li>Test the CLASSPATH settings by running the following java command:<pre>java org.apache.derby.tools.sysinfo</pre>This command will show the Derby jar files that are in the CLASSPATH as well as 
-the DB2 JDBC Universal Driver along with their respective versions.</li>
-<li>Once you have set up your environment correctly, execute the application from the <br> <SPAN 
-  class=italic>%DERBY_INSTALL%</SPAN><tt>\demo\programs\</tt> directory:<br>
-<pre>java nserverdemo.NsSample</pre>
-</li>
-</OL>
-You should receive output similar to the following if the 
-program runs successfully:<br><br>
-
-<tt>Derby Network Server created<br>
-[NsSample] Unable to obtain a connection to network server, trying again after 3000 ms.<br>
-Server is ready to accept connections on port 1621.<br>
-Connection number: 1.<br>
-[NsSample] Derby Network Server started.<br>
-[NsSample] Sample Derby Network Server program demo starting. <br>
-Please wait .....................<br>
-Connection number: 2.<br>
-[NsSampleWork] Table 'SAMPLETBL' already exists; no need to create schema again.<br>
-[NsSampleClientThread] Thread id - 1; started.<br>
-[NsSampleWork] Thread id - 1; requests database connection, dbUrl =jdbc:derby:NSSampledb;<br>
-[NsSampleClientThread] Thread id - 2; started.<br>
-[NsSampleWork] Thread id - 2; requests database connection, dbUrl <br>=jdbc:derby:net://localhost:1621/NSSampledb;create=true:retrieveMessagesFromServerOnGetMessage=true;deferPrepares=true;<br>
-Connection number: 3.<br>
-[NsSampleWork] Thread id - 1 selected 1 row [61,Derby28        ,3.20918E21,9854]<br>
-[NsSampleWork] Thread id - 1; inserted 1 row.<br>
-[NsSampleWork] Thread id - 1; deleted 1 row with t_key = 9854<br>
-[NsSampleWork] Thread id - 1; inserted 1 row.<br>
-[NsSampleWork] Thread id - 1; deleted 1 row with t_key = 9818<br>
-[NsSampleWork] Thread id - 2; deleted 0 row with t_key = 9854<br>
-[NsSampleWork] Thread id - 1; updated 1 row with t_key = 9481<br>
-[NsSampleWork] Thread id - 1; updated 1 row with t_key = 9481<br>
-[NsSampleWork] Thread id - 1; updated 0 row with t_key = 9481<br>
-[NsSampleWork] Thread id - 2; deleted 1 row with t_key = 9481<br>
-[NsSampleWork] Thread id - 1; inserted 1 row.<br>
-[NsSampleWork] Thread id - 1; updated 1 row with t_key = 9150<br>
-[NsSampleWork] Thread id - 1; closed connection to the database.<br>
-[NsSampleClientThread] Thread id - 1; finished all tasks.<br>
-[NsSampleWork] Thread id - 2 selected 1 row [57,Derby18        ,7.873628,9150]<br>
-[NsSampleWork] Thread id - 2; updated 1 row with t_key = 9150<br>
-[NsSampleWork] Thread id - 2 selected 1 row [58,Derby18        ,7.873628,9150]<br>
-[NsSampleWork] Thread id - 2; inserted 1 row.<br>
-[NsSampleWork] Thread id - 2 selected 1 row [58,Derby18        ,7.873628,9150]<br>
-[NsSampleWork] Thread id - 2; inserted 1 row.<br>
-[NsSampleWork] Thread id - 2; updated 1 row with t_key = 9150<br>
-[NsSampleWork] Thread id - 2 selected 1 row [61,Derby18        ,7.873628,9150]<br>
-[NsSampleWork] Thread id - 2; closed connection to the database.<br>
-[NsSampleClientThread] Thread id - 2; finished all tasks.<br>
-[NsSample] Shutting down network server.<br>
-Connection number: 4.<br>
-Shutdown successful.<br>
-[NsSample] End of Network server demo.</tt>
-
-<P>Running the demo program will also create new directories and files:</P>
-<UL>
-  <LI><A name=Bot_Of_Page></A><tt>NSSampledb</tt><br>This directory makes up the 
-NSSampledb database.</li>
-  <LI><tt>derby.log</tt><br>This log file contains Derby progress and error messages.</li>
-</ul>
-
-
-</BODY>
-</HTML>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<HTML>
+<HEAD>
+<TITLE>Derby Network Server sample program</TITLE>
+<META http-equiv=Content-Type content="text/html; charset=iso-8859-1">
+</HEAD>
+<BODY>
+<H2><A name=Top_Of_Page></A><A name=nsrun></A><A name=nssample></A>Derby 
+Network Server sample program</H2>
+<P>The Network Server sample demo program (NsSample) is a simple JDBC application that 
+interacts with the Derby Network Server. The program:</P>
+<UL>
+  <LI>starts the Derby Network Server 
+  <LI>checks if the Derby Network Server is running 
+  <LI>loads the DB2 JDBC Universal Driver 
+  <LI>creates the database '<tt>NsSampledb</tt>' if not already created 
+  <LI>checks to see if the schema is already created, and if not, 
+  creates the schema which includes the <tt>SAMPLETBL</tt> table and corresponding 
+  indexes. 
+  <LI>connects to the database 
+  <LI>loads the schema by inserting data 
+  <LI>starts client threads to perform database related operations 
+  <LI>has each of the clients perform DML operations (select, insert, delete, update) 
+  using JDBC calls, in particular one client opens an embedded connection to 
+  perform database operations while the other client opens a client connection 
+  to the Derby Network Server to perform database operations. 
+  <LI>waits for the client threads to finish the tasks 
+  <LI>shuts down the Derby Network Server at the end of the demo </LI></UL>
+<P>The following files should be installed in the <SPAN 
+class=italic>%DERBY_INSTALL%</SPAN><TT>\demo\programs\nserverdemo\</TT> directory in 
+order to run the sample program:</P>
+<UL>
+  <LI><TT>NsSample.java</tt><br>
+This is the entry point into the demo application. The program starts up two clients. One client opens an embedded 
+connection to perform database operations while the other client opens a client 
+connection to the Derby Network Server to perform database operations.  This program provides the following constants that 
+can be changed to modify the sample demo:
+<UL>
+
+    <LI><tt>NUM_ROWS</tt> - The number of rows that must be initially loaded into the schema.</li>
+    <LI><tt>ITERATIONS</tt> - The number of iterations for which each client thread does database related work.</LI>
+<LI><tt>NUM_CLIENT_THREADS</tt> - The number of clients that you want to run the program against.</li> 
+    <LI><tt>NETWORKSERVER_PORT</tt> - The port on which the network server is running.</LI>
+</UL>
+
+You can also modify the program to exclude starting the Network Server as part of the sample program. 
+Make sure to recompile the java files before running the program if you make any 
+changes to the source code.
+
+</li>
+
+<li><tt>NsSampleClientThread.java</tt></br>
+This file contains two Java classes:
+  <UL>
+    <LI>The <tt>NsSampleClientThread</tt> class extends Thread and does all the 
+necessary work by instantiating a <tt>NsSampleWork</tt> instance.</li>
+    <LI>The <tt>NsSampleWork</tt> class contains everything required to perform 
+DML operations using JDBC calls. The <tt>doWork</tt> method in 
+the <tt>NsSampleWork</tt> class represents all the work done as 
+part of this sample program.</LI>
+</UL>
+</li>
+  <LI><tt>NetworkServerUtil.java</tt><br>
+This file contains helper methods to start the Derby Network Server and to shutdown the server.
+</li>
+  <LI>Compiled class files:
+<UL>
+    <LI><tt>NsSample.class</tt></li> 
+    <LI><tt>NsSampleClientThread.class</tt></li> 
+    <LI><tt>NsSampleWork.class</tt></li> 
+    <LI><tt>NetworkServerUtil.class</tt></li> 
+</UL>
+</li>
+</ul>
+
+
+<H2>Running the Network Server demo program</H2>
+<P>To run the Derby Network Server demonstration program:</P>
+<OL>
+  <LI>Open a command prompt and change directories to the <SPAN 
+  class=italic>%DERBY_INSTALL%</SPAN><tt>\demo\programs\</tt> directory, where <SPAN 
+  class=italic>%DERBY_INSTALL%</SPAN> is the directory where you installed Derby. 
+  <LI>Set the CLASSPATH to the current directory (".") and also include the following 
+  jar files in order to use the Derby Network Server and the DB2 JDBC Universal Driver.
+<ul>
+<li><tt>derbynet.jar</tt><br>The Network Server jar file. It must be in your CLASSPATH to use any of the Derby Network 
+Server functions.</li>
+<li><tt>db2jcc.jar</tt><br>This jar file must be in your CLASSPATH to use the 
+DB2 JDBC Universal Driver.</li>
+<li><tt>db2jcc_license_c.jar</tt><br>This jar file is the license file for the Universal 
+Driver.</li>
+<li><tt>derby.jar</tt><br>The Derby database engine jar file.</li>
+</ul>
+</LI>
+<li>Test the CLASSPATH settings by running the following java command:<pre>java org.apache.derby.tools.sysinfo</pre>This command will show the Derby jar files that are in the CLASSPATH as well as 
+the DB2 JDBC Universal Driver along with their respective versions.</li>
+<li>Once you have set up your environment correctly, execute the application from the <br> <SPAN 
+  class=italic>%DERBY_INSTALL%</SPAN><tt>\demo\programs\</tt> directory:<br>
+<pre>java nserverdemo.NsSample</pre>
+</li>
+</OL>
+You should receive output similar to the following if the 
+program runs successfully:<br><br>
+
+<tt>Derby Network Server created<br>
+[NsSample] Unable to obtain a connection to network server, trying again after 3000 ms.<br>
+Server is ready to accept connections on port 1621.<br>
+Connection number: 1.<br>
+[NsSample] Derby Network Server started.<br>
+[NsSample] Sample Derby Network Server program demo starting. <br>
+Please wait .....................<br>
+Connection number: 2.<br>
+[NsSampleWork] Table 'SAMPLETBL' already exists; no need to create schema again.<br>
+[NsSampleClientThread] Thread id - 1; started.<br>
+[NsSampleWork] Thread id - 1; requests database connection, dbUrl =jdbc:derby:NSSampledb;<br>
+[NsSampleClientThread] Thread id - 2; started.<br>
+[NsSampleWork] Thread id - 2; requests database connection, dbUrl <br>=jdbc:derby:net://localhost:1621/NSSampledb;create=true:retrieveMessagesFromServerOnGetMessage=true;deferPrepares=true;<br>
+Connection number: 3.<br>
+[NsSampleWork] Thread id - 1 selected 1 row [61,Derby28        ,3.20918E21,9854]<br>
+[NsSampleWork] Thread id - 1; inserted 1 row.<br>
+[NsSampleWork] Thread id - 1; deleted 1 row with t_key = 9854<br>
+[NsSampleWork] Thread id - 1; inserted 1 row.<br>
+[NsSampleWork] Thread id - 1; deleted 1 row with t_key = 9818<br>
+[NsSampleWork] Thread id - 2; deleted 0 row with t_key = 9854<br>
+[NsSampleWork] Thread id - 1; updated 1 row with t_key = 9481<br>
+[NsSampleWork] Thread id - 1; updated 1 row with t_key = 9481<br>
+[NsSampleWork] Thread id - 1; updated 0 row with t_key = 9481<br>
+[NsSampleWork] Thread id - 2; deleted 1 row with t_key = 9481<br>
+[NsSampleWork] Thread id - 1; inserted 1 row.<br>
+[NsSampleWork] Thread id - 1; updated 1 row with t_key = 9150<br>
+[NsSampleWork] Thread id - 1; closed connection to the database.<br>
+[NsSampleClientThread] Thread id - 1; finished all tasks.<br>
+[NsSampleWork] Thread id - 2 selected 1 row [57,Derby18        ,7.873628,9150]<br>
+[NsSampleWork] Thread id - 2; updated 1 row with t_key = 9150<br>
+[NsSampleWork] Thread id - 2 selected 1 row [58,Derby18        ,7.873628,9150]<br>
+[NsSampleWork] Thread id - 2; inserted 1 row.<br>
+[NsSampleWork] Thread id - 2 selected 1 row [58,Derby18        ,7.873628,9150]<br>
+[NsSampleWork] Thread id - 2; inserted 1 row.<br>
+[NsSampleWork] Thread id - 2; updated 1 row with t_key = 9150<br>
+[NsSampleWork] Thread id - 2 selected 1 row [61,Derby18        ,7.873628,9150]<br>
+[NsSampleWork] Thread id - 2; closed connection to the database.<br>
+[NsSampleClientThread] Thread id - 2; finished all tasks.<br>
+[NsSample] Shutting down network server.<br>
+Connection number: 4.<br>
+Shutdown successful.<br>
+[NsSample] End of Network server demo.</tt>
+
+<P>Running the demo program will also create new directories and files:</P>
+<UL>
+  <LI><A name=Bot_Of_Page></A><tt>NSSampledb</tt><br>This directory makes up the 
+NSSampledb database.</li>
+  <LI><tt>derby.log</tt><br>This log file contains Derby progress and error messages.</li>
+</ul>
+
+
+</BODY>
+</HTML>

Propchange: incubator/derby/code/trunk/java/demo/nserverdemo/nserverdemo.html
------------------------------------------------------------------------------
    svn:eol-style = native



Mime
View raw message