Commit d2e27b06 authored by Bruce Momjian's avatar Bruce Momjian

pgjindent jdbc files. First time jdbc files were formatted.

parent b81844b1
...@@ -19,7 +19,8 @@ import java.util.*; ...@@ -19,7 +19,8 @@ import java.util.*;
* *
* @author William Webber <william@live.com.au> * @author William Webber <william@live.com.au>
*/ */
public class Unicode { public class Unicode
{
/** /**
* The url for the database to connect to. * The url for the database to connect to.
...@@ -36,21 +37,25 @@ public class Unicode { ...@@ -36,21 +37,25 @@ public class Unicode {
*/ */
private String password; private String password;
private static void usage() { private static void usage()
{
log("usage: example.Unicode <url> <user> <password>"); log("usage: example.Unicode <url> <user> <password>");
} }
private static void log(String message) { private static void log(String message)
{
System.err.println(message); System.err.println(message);
} }
private static void log(String message, Exception e) { private static void log(String message, Exception e)
{
System.err.println(message); System.err.println(message);
e.printStackTrace(); e.printStackTrace();
} }
public Unicode(String url, String user, String password) { public Unicode(String url, String user, String password)
{
this.url = url; this.url = url;
this.user = user; this.user = user;
this.password = password; this.password = password;
...@@ -60,7 +65,8 @@ public class Unicode { ...@@ -60,7 +65,8 @@ public class Unicode {
* Establish and return a connection to the database. * Establish and return a connection to the database.
*/ */
private Connection getConnection() throws SQLException, private Connection getConnection() throws SQLException,
ClassNotFoundException { ClassNotFoundException
{
Class.forName("org.postgresql.Driver"); Class.forName("org.postgresql.Driver");
Properties info = new Properties(); Properties info = new Properties();
info.put("user", user); info.put("user", user);
...@@ -73,14 +79,16 @@ public class Unicode { ...@@ -73,14 +79,16 @@ public class Unicode {
* Get string representing a block of 256 consecutive unicode characters. * Get string representing a block of 256 consecutive unicode characters.
* We exclude the null character, "'", and "\". * We exclude the null character, "'", and "\".
*/ */
private String getSqlSafeUnicodeBlock(int blockNum) { private String getSqlSafeUnicodeBlock(int blockNum)
{
if (blockNum < 0 || blockNum > 255) if (blockNum < 0 || blockNum > 255)
throw new IllegalArgumentException("blockNum must be from 0 to " throw new IllegalArgumentException("blockNum must be from 0 to "
+ "255: " + blockNum); + "255: " + blockNum);
StringBuffer sb = new StringBuffer(256); StringBuffer sb = new StringBuffer(256);
int blockFirst = blockNum * 256; int blockFirst = blockNum * 256;
int blockLast = blockFirst + 256; int blockLast = blockFirst + 256;
for (int i = blockFirst; i < blockLast; i++) { for (int i = blockFirst; i < blockLast; i++)
{
char c = (char) i; char c = (char) i;
if (c == '\0' || c == '\'' || c == '\\') if (c == '\0' || c == '\'' || c == '\\')
continue; continue;
...@@ -96,7 +104,8 @@ public class Unicode { ...@@ -96,7 +104,8 @@ public class Unicode {
* These should not be used in actual Unicode strings; * These should not be used in actual Unicode strings;
* at least, jdk1.2 will not convert them to utf-8. * at least, jdk1.2 will not convert them to utf-8.
*/ */
private boolean isValidUnicodeBlock(int blockNum) { private boolean isValidUnicodeBlock(int blockNum)
{
if (blockNum >= 0xd8 && blockNum <= 0xdb) if (blockNum >= 0xd8 && blockNum <= 0xdb)
return false; return false;
else else
...@@ -107,14 +116,19 @@ public class Unicode { ...@@ -107,14 +116,19 @@ public class Unicode {
* Report incorrect block retrieval. * Report incorrect block retrieval.
*/ */
private void reportRetrievalError(int blockNum, String block, private void reportRetrievalError(int blockNum, String block,
String retrieved) { String retrieved)
{
String message = "Block " + blockNum + " returned incorrectly: "; String message = "Block " + blockNum + " returned incorrectly: ";
int i = 0; int i = 0;
for (i = 0; i < block.length(); i++) { for (i = 0; i < block.length(); i++)
if (i >= retrieved.length()) { {
if (i >= retrieved.length())
{
message += "too short"; message += "too short";
break; break;
} else if (retrieved.charAt(i) != block.charAt(i)) { }
else if (retrieved.charAt(i) != block.charAt(i))
{
message += message +=
"first changed character at position " + i + ", sent as 0x" "first changed character at position " + i + ", sent as 0x"
+ Integer.toHexString((int) block.charAt(i)) + Integer.toHexString((int) block.charAt(i))
...@@ -131,7 +145,8 @@ public class Unicode { ...@@ -131,7 +145,8 @@ public class Unicode {
/** /**
* Do the testing. * Do the testing.
*/ */
public void runTest() { public void runTest()
{
Connection connection = null; Connection connection = null;
Statement statement = null; Statement statement = null;
int blockNum = 0; int blockNum = 0;
...@@ -140,15 +155,18 @@ public class Unicode { ...@@ -140,15 +155,18 @@ public class Unicode {
final int SELECT = 2; final int SELECT = 2;
final int LIKE = 3; final int LIKE = 3;
int mode = CREATE; int mode = CREATE;
try { try
{
connection = getConnection(); connection = getConnection();
statement = connection.createStatement(); statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE test_unicode " statement.executeUpdate("CREATE TABLE test_unicode "
+ "( blockNum INT PRIMARY KEY, " + "( blockNum INT PRIMARY KEY, "
+ "block TEXT );"); + "block TEXT );");
mode = INSERT; mode = INSERT;
for (blockNum = 0; blockNum < 256; blockNum++) { for (blockNum = 0; blockNum < 256; blockNum++)
if (isValidUnicodeBlock(blockNum)) { {
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum); String block = getSqlSafeUnicodeBlock(blockNum);
statement.executeUpdate statement.executeUpdate
("INSERT INTO test_unicode VALUES ( " + blockNum ("INSERT INTO test_unicode VALUES ( " + blockNum
...@@ -156,25 +174,31 @@ public class Unicode { ...@@ -156,25 +174,31 @@ public class Unicode {
} }
} }
mode = SELECT; mode = SELECT;
for (blockNum = 0; blockNum < 256; blockNum++) { for (blockNum = 0; blockNum < 256; blockNum++)
if (isValidUnicodeBlock(blockNum)) { {
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum); String block = getSqlSafeUnicodeBlock(blockNum);
ResultSet rs = statement.executeQuery ResultSet rs = statement.executeQuery
("SELECT block FROM test_unicode WHERE blockNum = " ("SELECT block FROM test_unicode WHERE blockNum = "
+ blockNum + ";"); + blockNum + ";");
if (!rs.next()) if (!rs.next())
log("Could not retrieve block " + blockNum); log("Could not retrieve block " + blockNum);
else { else
{
String retrieved = rs.getString(1); String retrieved = rs.getString(1);
if (!retrieved.equals(block)) { if (!retrieved.equals(block))
{
reportRetrievalError(blockNum, block, retrieved); reportRetrievalError(blockNum, block, retrieved);
} }
} }
} }
} }
mode = LIKE; mode = LIKE;
for (blockNum = 0; blockNum < 256; blockNum++) { for (blockNum = 0; blockNum < 256; blockNum++)
if (isValidUnicodeBlock(blockNum)) { {
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum); String block = getSqlSafeUnicodeBlock(blockNum);
String likeString = "%" + String likeString = "%" +
block.substring(2, block.length() - 3) + "%" ; block.substring(2, block.length() - 3) + "%" ;
...@@ -185,8 +209,11 @@ public class Unicode { ...@@ -185,8 +209,11 @@ public class Unicode {
log("Could get block " + blockNum + " using LIKE"); log("Could get block " + blockNum + " using LIKE");
} }
} }
} catch (SQLException sqle) { }
switch (mode) { catch (SQLException sqle)
{
switch (mode)
{
case CREATE: case CREATE:
log("Exception creating database", sqle); log("Exception creating database", sqle);
break; break;
...@@ -203,35 +230,46 @@ public class Unicode { ...@@ -203,35 +230,46 @@ public class Unicode {
log("Exception", sqle); log("Exception", sqle);
break; break;
} }
} catch (ClassNotFoundException cnfe) { }
catch (ClassNotFoundException cnfe)
{
log("Unable to load driver", cnfe); log("Unable to load driver", cnfe);
return; return ;
} }
try { try
{
if (statement != null) if (statement != null)
statement.close(); statement.close();
if (connection != null) if (connection != null)
connection.close(); connection.close();
} catch (SQLException sqle) { }
catch (SQLException sqle)
{
log("Exception closing connections", sqle); log("Exception closing connections", sqle);
} }
if (mode > CREATE) { if (mode > CREATE)
{
// If the backend gets what it regards as garbage on a connection, // If the backend gets what it regards as garbage on a connection,
// that connection may become unusable. To be safe, we create // that connection may become unusable. To be safe, we create
// a fresh connection to delete the table. // a fresh connection to delete the table.
try { try
{
connection = getConnection(); connection = getConnection();
statement = connection.createStatement(); statement = connection.createStatement();
statement.executeUpdate("DROP TABLE test_unicode;"); statement.executeUpdate("DROP TABLE test_unicode;");
} catch (Exception sqle) { }
catch (Exception sqle)
{
log("*** ERROR: unable to delete test table " log("*** ERROR: unable to delete test table "
+ "test_unicode; must be deleted manually", sqle); + "test_unicode; must be deleted manually", sqle);
} }
} }
} }
public static void main(String [] args) { public static void main(String [] args)
if (args.length != 3) { {
if (args.length != 3)
{
usage(); usage();
System.exit(1); System.exit(1);
} }
......
...@@ -6,7 +6,7 @@ import java.text.*; ...@@ -6,7 +6,7 @@ import java.text.*;
/** /**
* *
* $Id: basic.java,v 1.7 2001/01/31 09:23:45 peter Exp $ * $Id: basic.java,v 1.8 2001/10/25 05:59:58 momjian Exp $
* *
* This example tests the basic components of the JDBC driver, and shows * This example tests the basic components of the JDBC driver, and shows
* how even the simplest of queries can be implemented. * how even the simplest of queries can be implemented.
...@@ -61,9 +61,12 @@ public class basic ...@@ -61,9 +61,12 @@ public class basic
*/ */
public void cleanup() public void cleanup()
{ {
try { try
{
st.executeUpdate("drop table basic"); st.executeUpdate("drop table basic");
} catch(Exception ex) { }
catch (Exception ex)
{
// We ignore any errors here // We ignore any errors here
} }
} }
...@@ -87,15 +90,15 @@ public class basic ...@@ -87,15 +90,15 @@ public class basic
// updated for 7.1 // updated for 7.1
st.executeUpdate("insert into basic values (4,1)"); st.executeUpdate("insert into basic values (4,1)");
int insertedOID = ((org.postgresql.Statement)st).getInsertedOID(); int insertedOID = ((org.postgresql.Statement)st).getInsertedOID();
System.out.println("Inserted row with oid "+insertedOID); System.out.println("Inserted row with oid " + insertedOID);
// Now change the value of b from 1 to 8 // Now change the value of b from 1 to 8
st.executeUpdate("update basic set b=8"); st.executeUpdate("update basic set b=8");
System.out.println("Updated "+st.getUpdateCount()+" rows"); System.out.println("Updated " + st.getUpdateCount() + " rows");
// Now delete 2 rows // Now delete 2 rows
st.executeUpdate("delete from basic where a<3"); st.executeUpdate("delete from basic where a<3");
System.out.println("deleted "+st.getUpdateCount()+" rows"); System.out.println("deleted " + st.getUpdateCount() + " rows");
// For large inserts, a PreparedStatement is more efficient, because it // For large inserts, a PreparedStatement is more efficient, because it
// supports the idea of precompiling the SQL statement, and to store // supports the idea of precompiling the SQL statement, and to store
...@@ -107,9 +110,10 @@ public class basic ...@@ -107,9 +110,10 @@ public class basic
// manner. (DateStyles are PostgreSQL's way of handling different methods // manner. (DateStyles are PostgreSQL's way of handling different methods
// of representing dates in the Date data type.) // of representing dates in the Date data type.)
PreparedStatement ps = db.prepareStatement("insert into basic values (?,?)"); PreparedStatement ps = db.prepareStatement("insert into basic values (?,?)");
for(int i=2;i<5;i++) { for (int i = 2;i < 5;i++)
ps.setInt(1,4); // "column a" = 5 {
ps.setInt(2,i); // "column b" = i ps.setInt(1, 4); // "column a" = 5
ps.setInt(2, i); // "column b" = i
ps.executeUpdate(); // executeUpdate because insert returns no data ps.executeUpdate(); // executeUpdate because insert returns no data
} }
ps.close(); // Always close when we are done with it ps.close(); // Always close when we are done with it
...@@ -117,22 +121,26 @@ public class basic ...@@ -117,22 +121,26 @@ public class basic
// Finally perform a query on the table // Finally perform a query on the table
System.out.println("performing a query"); System.out.println("performing a query");
ResultSet rs = st.executeQuery("select a, b from basic"); ResultSet rs = st.executeQuery("select a, b from basic");
if(rs!=null) { if (rs != null)
{
// Now we run through the result set, printing out the result. // Now we run through the result set, printing out the result.
// Note, we must call .next() before attempting to read any results // Note, we must call .next() before attempting to read any results
while(rs.next()) { while (rs.next())
{
int a = rs.getInt("a"); // This shows how to get the value by name int a = rs.getInt("a"); // This shows how to get the value by name
int b = rs.getInt(2); // This shows how to get the value by column int b = rs.getInt(2); // This shows how to get the value by column
System.out.println(" a="+a+" b="+b); System.out.println(" a=" + a + " b=" + b);
} }
rs.close(); // again, you must close the result when done rs.close(); // again, you must close the result when done
} }
// Now run the query again, showing a more efficient way of getting the // Now run the query again, showing a more efficient way of getting the
// result if you don't know what column number a value is in // result if you don't know what column number a value is in
System.out.println("performing another query"); System.out.println("performing another query");
rs = st.executeQuery("select * from basic where b>1"); rs = st.executeQuery("select * from basic where b>1");
if(rs!=null) { if (rs != null)
{
// First find out the column numbers. // First find out the column numbers.
// //
// It's best to do this here, as calling the methods with the column // It's best to do this here, as calling the methods with the column
...@@ -144,22 +152,25 @@ public class basic ...@@ -144,22 +152,25 @@ public class basic
// Now we run through the result set, printing out the result. // Now we run through the result set, printing out the result.
// Again, we must call .next() before attempting to read any results // Again, we must call .next() before attempting to read any results
while(rs.next()) { while (rs.next())
{
int a = rs.getInt(col_a); // This shows how to get the value by name int a = rs.getInt(col_a); // This shows how to get the value by name
int b = rs.getInt(col_b); // This shows how to get the value by column int b = rs.getInt(col_b); // This shows how to get the value by column
System.out.println(" a="+a+" b="+b); System.out.println(" a=" + a + " b=" + b);
} }
rs.close(); // again, you must close the result when done rs.close(); // again, you must close the result when done
} }
// Now test maxrows by setting it to 3 rows // Now test maxrows by setting it to 3 rows
st.setMaxRows(3); st.setMaxRows(3);
System.out.println("performing a query limited to "+st.getMaxRows()); System.out.println("performing a query limited to " + st.getMaxRows());
rs = st.executeQuery("select a, b from basic"); rs = st.executeQuery("select a, b from basic");
while(rs.next()) { while (rs.next())
{
int a = rs.getInt("a"); // This shows how to get the value by name int a = rs.getInt("a"); // This shows how to get the value by name
int b = rs.getInt(2); // This shows how to get the value by column int b = rs.getInt(2); // This shows how to get the value by column
System.out.println(" a="+a+" b="+b); System.out.println(" a=" + a + " b=" + b);
} }
rs.close(); // again, you must close the result when done rs.close(); // again, you must close the result when done
...@@ -184,19 +195,22 @@ public class basic ...@@ -184,19 +195,22 @@ public class basic
{ {
System.out.println("PostgreSQL basic test v6.3 rev 1\n"); System.out.println("PostgreSQL basic test v6.3 rev 1\n");
if(args.length<3) if (args.length < 3)
instructions(); instructions();
// This line outputs debug information to stderr. To enable this, simply // This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line // add an extra parameter to the command line
if(args.length>3) if (args.length > 3)
DriverManager.setLogStream(System.err); DriverManager.setLogStream(System.err);
// Now run the tests // Now run the tests
try { try
{
basic test = new basic(args); basic test = new basic(args);
} catch(Exception ex) { }
System.err.println("Exception caught.\n"+ex); catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }
} }
......
...@@ -87,7 +87,7 @@ public class blobtest ...@@ -87,7 +87,7 @@ public class blobtest
// finally delete the large object // finally delete the large object
ownapi_test3(oid); ownapi_test3(oid);
System.out.println("\n\nOID="+oid); System.out.println("\n\nOID=" + oid);
} }
private int ownapi_test1() throws FileNotFoundException, IOException, SQLException private int ownapi_test1() throws FileNotFoundException, IOException, SQLException
...@@ -97,11 +97,11 @@ public class blobtest ...@@ -97,11 +97,11 @@ public class blobtest
// Ok, test 1 is to create a large object. To do this, we use the create // Ok, test 1 is to create a large object. To do this, we use the create
// method. // method.
System.out.println("Creating a large object"); System.out.println("Creating a large object");
int oid = lobj.create(LargeObjectManager.READ|LargeObjectManager.WRITE); int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
DriverManager.println("got large object oid="+oid); DriverManager.println("got large object oid=" + oid);
LargeObject obj = lobj.open(oid,LargeObjectManager.WRITE); LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
DriverManager.println("got large object obj="+obj); DriverManager.println("got large object obj=" + obj);
// Now open a test file - this class will do // Now open a test file - this class will do
System.out.println("Opening test source object"); System.out.println("Opening test source object");
...@@ -110,14 +110,15 @@ public class blobtest ...@@ -110,14 +110,15 @@ public class blobtest
// copy the data // copy the data
System.out.println("Copying file to large object"); System.out.println("Copying file to large object");
byte buf[] = new byte[2048]; byte buf[] = new byte[2048];
int s,tl=0; int s, tl = 0;
while((s=fis.read(buf,0,2048))>0) { while ((s = fis.read(buf, 0, 2048)) > 0)
System.out.println("Block size="+s+" offset="+tl); {
System.out.println("Block size=" + s + " offset=" + tl);
//System.out.write(buf); //System.out.write(buf);
obj.write(buf,0,s); obj.write(buf, 0, s);
tl+=s; tl += s;
} }
DriverManager.println("Copied "+tl+" bytes"); DriverManager.println("Copied " + tl + " bytes");
// Close the object // Close the object
System.out.println("Closing object"); System.out.println("Closing object");
...@@ -131,9 +132,9 @@ public class blobtest ...@@ -131,9 +132,9 @@ public class blobtest
System.out.println("Test 2 Reading a large object and save as a file\n"); System.out.println("Test 2 Reading a large object and save as a file\n");
// Now open the large object // Now open the large object
System.out.println("Opening large object "+oid); System.out.println("Opening large object " + oid);
LargeObject obj = lobj.open(oid,LargeObjectManager.READ); LargeObject obj = lobj.open(oid, LargeObjectManager.READ);
DriverManager.println("got obj="+obj); DriverManager.println("got obj=" + obj);
// Now open a test file - this class will do // Now open a test file - this class will do
System.out.println("Opening test destination object"); System.out.println("Opening test destination object");
...@@ -142,17 +143,19 @@ public class blobtest ...@@ -142,17 +143,19 @@ public class blobtest
// copy the data // copy the data
System.out.println("Copying large object to file"); System.out.println("Copying large object to file");
byte buf[] = new byte[512]; byte buf[] = new byte[512];
int s=obj.size(); int s = obj.size();
int tl=0; int tl = 0;
while(s>0) { while (s > 0)
{
int rs = buf.length; int rs = buf.length;
if(s<rs) rs=s; if (s < rs)
obj.read(buf,0,rs); rs = s;
fos.write(buf,0,rs); obj.read(buf, 0, rs);
tl+=rs; fos.write(buf, 0, rs);
s-=rs; tl += rs;
s -= rs;
} }
DriverManager.println("Copied "+tl+"/"+obj.size()+" bytes"); DriverManager.println("Copied " + tl + "/" + obj.size() + " bytes");
// Close the object // Close the object
System.out.println("Closing object"); System.out.println("Closing object");
...@@ -164,7 +167,7 @@ public class blobtest ...@@ -164,7 +167,7 @@ public class blobtest
System.out.println("Test 3 Deleting a large object\n"); System.out.println("Test 3 Deleting a large object\n");
// Now open the large object // Now open the large object
System.out.println("Deleting large object "+oid); System.out.println("Deleting large object " + oid);
lobj.unlink(oid); lobj.unlink(oid);
} }
...@@ -175,21 +178,23 @@ public class blobtest ...@@ -175,21 +178,23 @@ public class blobtest
System.out.println("Testing JDBC2 Blob interface:"); System.out.println("Testing JDBC2 Blob interface:");
jdbc2api_cleanup(); jdbc2api_cleanup();
System.out.println("Creating Blob on large object "+oid); System.out.println("Creating Blob on large object " + oid);
s.executeUpdate("create table basic (a oid)"); s.executeUpdate("create table basic (a oid)");
System.out.println("Inserting row"); System.out.println("Inserting row");
s.executeUpdate("insert into basic values ("+oid+")"); s.executeUpdate("insert into basic values (" + oid + ")");
System.out.println("Selecting row"); System.out.println("Selecting row");
ResultSet rs = s.executeQuery("select a from basic"); ResultSet rs = s.executeQuery("select a from basic");
if(rs!=null) { if (rs != null)
while(rs.next()) { {
while (rs.next())
{
System.out.println("Fetching Blob"); System.out.println("Fetching Blob");
Blob b = rs.getBlob("a"); Blob b = rs.getBlob("a");
System.out.println("Blob.length() = "+b.length()); System.out.println("Blob.length() = " + b.length());
System.out.println("Characters 400-500:"); System.out.println("Characters 400-500:");
System.out.write(b.getBytes(400l,100)); System.out.write(b.getBytes(400l, 100));
System.out.println(); System.out.println();
} }
rs.close(); rs.close();
...@@ -202,9 +207,12 @@ public class blobtest ...@@ -202,9 +207,12 @@ public class blobtest
private void jdbc2api_cleanup() throws SQLException private void jdbc2api_cleanup() throws SQLException
{ {
db.setAutoCommit(true); db.setAutoCommit(true);
try { try
{
s.executeUpdate("drop table basic"); s.executeUpdate("drop table basic");
} catch(Exception ex) { }
catch (Exception ex)
{
// We ignore any errors here // We ignore any errors here
} }
db.setAutoCommit(false); db.setAutoCommit(false);
...@@ -226,21 +234,25 @@ public class blobtest ...@@ -226,21 +234,25 @@ public class blobtest
{ {
System.out.println("PostgreSQL blobtest v7.0 rev 1\n"); System.out.println("PostgreSQL blobtest v7.0 rev 1\n");
if(args.length<3) { if (args.length < 3)
{
instructions(); instructions();
System.exit(1); System.exit(1);
} }
// This line outputs debug information to stderr. To enable this, simply // This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line // add an extra parameter to the command line
if(args.length>3) if (args.length > 3)
DriverManager.setLogStream(System.err); DriverManager.setLogStream(System.err);
// Now run the tests // Now run the tests
try { try
{
blobtest test = new blobtest(args); blobtest test = new blobtest(args);
} catch(Exception ex) { }
System.err.println("Exception caught.\n"+ex); catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }
} }
......
...@@ -9,7 +9,7 @@ import org.omg.CosNaming.*; ...@@ -9,7 +9,7 @@ import org.omg.CosNaming.*;
* *
* It has no GUI, just a text frontend to keep it simple. * It has no GUI, just a text frontend to keep it simple.
* *
* $Id: StockClient.java,v 1.1 1999/01/25 21:22:03 scrappy Exp $ * $Id: StockClient.java,v 1.2 2001/10/25 05:59:58 momjian Exp $
*/ */
public class StockClient public class StockClient
{ {
...@@ -20,55 +20,67 @@ public class StockClient ...@@ -20,55 +20,67 @@ public class StockClient
BufferedReader in; BufferedReader in;
public StockClient(String[] args) { public StockClient(String[] args)
try { {
try
{
// We need this for our IO // We need this for our IO
in = new BufferedReader(new InputStreamReader(System.in)); in = new BufferedReader(new InputStreamReader(System.in));
// Initialize the orb // Initialize the orb
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,null); org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
// Get a reference to the Naming Service // Get a reference to the Naming Service
org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService"); org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
if(nameServiceObj==null) { if (nameServiceObj == null)
{
System.err.println("nameServiceObj == null"); System.err.println("nameServiceObj == null");
return; return ;
} }
nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj); nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
if(nameService==null) { if (nameService == null)
{
System.err.println("nameService == null"); System.err.println("nameService == null");
return; return ;
} }
// Resolve the dispenser // Resolve the dispenser
NameComponent[] dispName = { NameComponent[] dispName = {
new NameComponent("StockDispenser","Stock") new NameComponent("StockDispenser", "Stock")
}; };
dispenser = stock.StockDispenserHelper.narrow(nameService.resolve(dispName)); dispenser = stock.StockDispenserHelper.narrow(nameService.resolve(dispName));
if(dispenser==null) { if (dispenser == null)
{
System.err.println("dispenser == null"); System.err.println("dispenser == null");
return; return ;
} }
// Now run the front end. // Now run the front end.
run(); run();
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
} }
} }
public static void main(String[] args) { public static void main(String[] args)
{
new StockClient(args); new StockClient(args);
} }
public void run() { public void run()
{
// First reserve a StockItem // First reserve a StockItem
try { try
{
item = dispenser.reserveItem(); item = dispenser.reserveItem();
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
...@@ -77,18 +89,23 @@ public class StockClient ...@@ -77,18 +89,23 @@ public class StockClient
mainMenu(); mainMenu();
// finally free the StockItem // finally free the StockItem
try { try
{
dispenser.releaseItem(item); dispenser.releaseItem(item);
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
} }
} }
private void mainMenu() { private void mainMenu()
boolean run=true; {
while(run) { boolean run = true;
while (run)
{
System.out.println("\nCORBA Stock System\n"); System.out.println("\nCORBA Stock System\n");
System.out.println(" 1 Display stock item"); System.out.println(" 1 Display stock item");
System.out.println(" 2 Remove item from stock"); System.out.println(" 2 Remove item from stock");
...@@ -96,11 +113,11 @@ public class StockClient ...@@ -96,11 +113,11 @@ public class StockClient
System.out.println(" 4 Order item"); System.out.println(" 4 Order item");
System.out.println(" 5 Display all items"); System.out.println(" 5 Display all items");
System.out.println(" 0 Exit"); System.out.println(" 0 Exit");
int i = getMenu("Main",5); int i = getMenu("Main", 5);
switch(i) switch (i)
{ {
case 0: case 0:
run=false; run = false;
break; break;
case 1: case 1:
...@@ -126,159 +143,202 @@ public class StockClient ...@@ -126,159 +143,202 @@ public class StockClient
} }
} }
private void displayItem() { private void displayItem()
try { {
int id = getMenu("\nStockID to display",item.getLastID()); try
if(id>0) { {
int id = getMenu("\nStockID to display", item.getLastID());
if (id > 0)
{
item.fetchItem(id); item.fetchItem(id);
System.out.println("========================================"); System.out.println("========================================");
String status = ""; String status = "";
if(!item.isItemValid()) if (!item.isItemValid())
status=" ** Superceded **"; status = " ** Superceded **";
int av = item.getAvailable(); int av = item.getAvailable();
System.out.println(" Stock ID: "+id+status+ System.out.println(" Stock ID: " + id + status +
"\nItems Available: "+av+ "\nItems Available: " + av +
"\nItems on order: "+item.getOrdered()+ "\nItems on order: " + item.getOrdered() +
"\n Description: "+item.getDescription()); "\n Description: " + item.getDescription());
System.out.println("========================================"); System.out.println("========================================");
if(av>0) if (av > 0)
if(yn("Take this item out of stock?")) { if (yn("Take this item out of stock?"))
int rem=1; {
if(av>1) int rem = 1;
rem=getMenu("How many?",av); if (av > 1)
if(rem>0) rem = getMenu("How many?", av);
if (rem > 0)
item.removeStock(rem); item.removeStock(rem);
} }
} }
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
private void bookOut() { private void bookOut()
try { {
int id = getMenu("\nStockID to take out",item.getLastID()); try
if(id>0) { {
int id = getMenu("\nStockID to take out", item.getLastID());
if (id > 0)
{
item.fetchItem(id); item.fetchItem(id);
int av = item.getAvailable(); int av = item.getAvailable();
if(av>0) if (av > 0)
if(yn("Take this item out of stock?")) { if (yn("Take this item out of stock?"))
int rem=1; {
if(av>1) int rem = 1;
rem=getMenu("How many?",av); if (av > 1)
if(rem>0) rem = getMenu("How many?", av);
if (rem > 0)
item.removeStock(rem); item.removeStock(rem);
} }
else { else
{
System.out.println("This item is not in stock."); System.out.println("This item is not in stock.");
int order = item.getOrdered(); int order = item.getOrdered();
if(order>0) if (order > 0)
System.out.println("There are "+item.getOrdered()+" items on order."); System.out.println("There are " + item.getOrdered() + " items on order.");
else { else
if(item.isItemValid()) { {
System.out.println("You will need to order some more "+item.getDescription()); if (item.isItemValid())
{
System.out.println("You will need to order some more " + item.getDescription());
order(id); order(id);
} else }
else
System.out.println("This item is now obsolete"); System.out.println("This item is now obsolete");
} }
} }
} else }
System.out.println(item.getDescription()+"\nThis item is out of stock"); else
} catch(Exception e) { System.out.println(item.getDescription() + "\nThis item is out of stock");
}
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
// book an item into stock // book an item into stock
private void bookIn() { private void bookIn()
try { {
int id = getMenu("\nStockID to book in",item.getLastID()); try
{
int id = getMenu("\nStockID to book in", item.getLastID());
item.fetchItem(id); item.fetchItem(id);
System.out.println(item.getDescription()); System.out.println(item.getDescription());
if(item.getOrdered()>0) { if (item.getOrdered() > 0)
int am = getMenu("How many do you want to book in",item.getOrdered()); {
if(am>0) int am = getMenu("How many do you want to book in", item.getOrdered());
if (am > 0)
item.addNewStock(am); item.addNewStock(am);
} else }
else
System.out.println("You don't have any of this item on ordered"); System.out.println("You don't have any of this item on ordered");
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
// Order an item // Order an item
private void order(int id) { private void order(int id)
try { {
if(id==0) try
id = getMenu("\nStockID to order",item.getLastID()); {
if (id == 0)
id = getMenu("\nStockID to order", item.getLastID());
item.fetchItem(id); item.fetchItem(id);
System.out.println(item.getDescription()); System.out.println(item.getDescription());
int am = getMenu("How many do you want to order",999); int am = getMenu("How many do you want to order", 999);
if(am>0) if (am > 0)
item.orderStock(am); item.orderStock(am);
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
private void displayAll() { private void displayAll()
try { {
boolean cont=true; try
int nr=item.getLastID(); {
boolean cont = true;
int nr = item.getLastID();
String header = "\nId\tAvail\tOrdered\tDescription"; String header = "\nId\tAvail\tOrdered\tDescription";
System.out.println(header); System.out.println(header);
for(int i=1;i<=nr && cont;i++) { for (int i = 1;i <= nr && cont;i++)
{
item.fetchItem(i); item.fetchItem(i);
System.out.println(""+i+"\t"+item.getAvailable()+"\t"+item.getOrdered()+"\t"+item.getDescription()); System.out.println("" + i + "\t" + item.getAvailable() + "\t" + item.getOrdered() + "\t" + item.getDescription());
if((i%20)==0) { if ((i % 20) == 0)
if((cont=yn("Continue?"))) {
if ((cont = yn("Continue?")))
System.out.println(header); System.out.println(header);
} }
} }
} catch(Exception e) { }
catch (Exception e)
{
System.out.println(e.toString()); System.out.println(e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
private int getMenu(String title,int max) { private int getMenu(String title, int max)
int v=-1; {
while(v<0 || v>max) { int v = -1;
while (v < 0 || v > max)
{
System.out.print(title); System.out.print(title);
System.out.print(" [0-"+max+"]: "); System.out.print(" [0-" + max + "]: ");
System.out.flush(); System.out.flush();
try { try
{
v = Integer.parseInt(in.readLine()); v = Integer.parseInt(in.readLine());
} catch(Exception nfe) { }
v=-1; catch (Exception nfe)
{
v = -1;
} }
} }
return v; return v;
} }
private boolean yn(String title) { private boolean yn(String title)
try { {
while(true) { try
{
while (true)
{
System.out.print(title); System.out.print(title);
System.out.flush(); System.out.flush();
String s = in.readLine(); String s = in.readLine();
if(s.startsWith("y") || s.startsWith("Y")) if (s.startsWith("y") || s.startsWith("Y"))
return true; return true;
if(s.startsWith("n") || s.startsWith("N")) if (s.startsWith("n") || s.startsWith("N"))
return false; return false;
} }
} catch(Exception nfe) { }
catch (Exception nfe)
{
System.out.println(nfe.toString()); System.out.println(nfe.toString());
nfe.printStackTrace(); nfe.printStackTrace();
System.exit(1); System.exit(1);
......
...@@ -13,7 +13,7 @@ import java.sql.*; ...@@ -13,7 +13,7 @@ import java.sql.*;
* that an object could be changed by another client, and we need to ensure that * that an object could be changed by another client, and we need to ensure that
* the returned data is live and accurate. * the returned data is live and accurate.
* *
* $Id: StockDB.java,v 1.2 2000/04/26 05:32:01 peter Exp $ * $Id: StockDB.java,v 1.3 2001/10/25 05:59:58 momjian Exp $
*/ */
public class StockDB public class StockDB
{ {
...@@ -23,29 +23,35 @@ public class StockDB ...@@ -23,29 +23,35 @@ public class StockDB
// the current stock number // the current stock number
int id = -1; int id = -1;
public void connect(String url,String usr,String pwd) throws Exception { public void connect(String url, String usr, String pwd) throws Exception
{
Class.forName("org.postgresql.Driver"); Class.forName("org.postgresql.Driver");
System.out.println("Connecting to "+url); System.out.println("Connecting to " + url);
con = DriverManager.getConnection(url,usr,pwd); con = DriverManager.getConnection(url, usr, pwd);
st = con.createStatement(); st = con.createStatement();
} }
public void closeConnection() throws Exception { public void closeConnection() throws Exception
{
con.close(); con.close();
} }
public void fetchItem(int id) throws Exception { public void fetchItem(int id) throws Exception
{
this.id = id; this.id = id;
} }
public int newItem() throws Exception { public int newItem() throws Exception
{
// tba // tba
return -1; return -1;
} }
public String getDescription() throws SQLException { public String getDescription() throws SQLException
ResultSet rs = st.executeQuery("select description from stock where id="+id); {
if(rs!=null) { ResultSet rs = st.executeQuery("select description from stock where id=" + id);
if (rs != null)
{
rs.next(); rs.next();
String s = rs.getString(1); String s = rs.getString(1);
rs.close(); rs.close();
...@@ -54,9 +60,11 @@ public class StockDB ...@@ -54,9 +60,11 @@ public class StockDB
throw new SQLException("No ResultSet"); throw new SQLException("No ResultSet");
} }
public int getAvailable() throws SQLException { public int getAvailable() throws SQLException
ResultSet rs = st.executeQuery("select avail from stock where id="+id); {
if(rs!=null) { ResultSet rs = st.executeQuery("select avail from stock where id=" + id);
if (rs != null)
{
rs.next(); rs.next();
int v = rs.getInt(1); int v = rs.getInt(1);
rs.close(); rs.close();
...@@ -65,9 +73,11 @@ public class StockDB ...@@ -65,9 +73,11 @@ public class StockDB
throw new SQLException("No ResultSet"); throw new SQLException("No ResultSet");
} }
public int getOrdered() throws SQLException { public int getOrdered() throws SQLException
ResultSet rs = st.executeQuery("select ordered from stock where id="+id); {
if(rs!=null) { ResultSet rs = st.executeQuery("select ordered from stock where id=" + id);
if (rs != null)
{
rs.next(); rs.next();
int v = rs.getInt(1); int v = rs.getInt(1);
rs.close(); rs.close();
...@@ -76,9 +86,11 @@ public class StockDB ...@@ -76,9 +86,11 @@ public class StockDB
throw new SQLException("No ResultSet"); throw new SQLException("No ResultSet");
} }
public boolean isItemValid() throws SQLException { public boolean isItemValid() throws SQLException
ResultSet rs = st.executeQuery("select valid from stock where id="+id); {
if(rs!=null) { ResultSet rs = st.executeQuery("select valid from stock where id=" + id);
if (rs != null)
{
rs.next(); rs.next();
boolean b = rs.getBoolean(1); boolean b = rs.getBoolean(1);
rs.close(); rs.close();
...@@ -87,25 +99,30 @@ public class StockDB ...@@ -87,25 +99,30 @@ public class StockDB
throw new SQLException("No ResultSet"); throw new SQLException("No ResultSet");
} }
public void addNewStock(int amount) throws SQLException { public void addNewStock(int amount) throws SQLException
st.executeUpdate("update stock set avail=avail+"+amount+ {
", ordered=ordered-"+amount+ st.executeUpdate("update stock set avail=avail+" + amount +
" where id="+id+" and ordered>="+amount); ", ordered=ordered-" + amount +
" where id=" + id + " and ordered>=" + amount);
} }
public void removeStock(int amount) throws SQLException { public void removeStock(int amount) throws SQLException
st.executeUpdate("update stock set avail=avail-"+amount+ {
" where id="+id); st.executeUpdate("update stock set avail=avail-" + amount +
" where id=" + id);
} }
public void orderStock(int amount) throws SQLException { public void orderStock(int amount) throws SQLException
st.executeUpdate("update stock set ordered=ordered+"+amount+ {
" where id="+id); st.executeUpdate("update stock set ordered=ordered+" + amount +
" where id=" + id);
} }
public int getLastID() throws SQLException { public int getLastID() throws SQLException
{
ResultSet rs = st.executeQuery("select max(id) from stock"); ResultSet rs = st.executeQuery("select max(id) from stock");
if(rs!=null) { if (rs != null)
{
rs.next(); rs.next();
int v = rs.getInt(1); int v = rs.getInt(1);
rs.close(); rs.close();
......
...@@ -5,7 +5,7 @@ import org.omg.CosNaming.*; ...@@ -5,7 +5,7 @@ import org.omg.CosNaming.*;
/** /**
* This class implements the server side of the example. * This class implements the server side of the example.
* *
* $Id: StockDispenserImpl.java,v 1.1 1999/01/25 21:22:03 scrappy Exp $ * $Id: StockDispenserImpl.java,v 1.2 2001/10/25 05:59:58 momjian Exp $
*/ */
public class StockDispenserImpl extends stock._StockDispenserImplBase public class StockDispenserImpl extends stock._StockDispenserImplBase
{ {
...@@ -13,24 +13,28 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase ...@@ -13,24 +13,28 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
private int numObjects = 0; private int numObjects = 0;
private StockItemStatus[] stock = new StockItemStatus[maxObjects]; private StockItemStatus[] stock = new StockItemStatus[maxObjects];
public StockDispenserImpl(String[] args,String name,int num) public StockDispenserImpl(String[] args, String name, int num)
{ {
super(); super();
try { try
{
// get reference to orb // get reference to orb
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,null); org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
// prestart num objects // prestart num objects
if(num>=maxObjects) if (num >= maxObjects)
num=maxObjects; num = maxObjects;
numObjects = num; numObjects = num;
for(int i=0;i<numObjects;i++) { for (int i = 0;i < numObjects;i++)
{
stock[i] = new StockItemStatus(); stock[i] = new StockItemStatus();
stock[i].ref = new StockItemImpl(args,"StockItem"+(i+1)); stock[i].ref = new StockItemImpl(args, "StockItem" + (i + 1));
orb.connect(stock[i].ref); orb.connect(stock[i].ref);
} }
} catch(org.omg.CORBA.SystemException e) { }
catch (org.omg.CORBA.SystemException e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
...@@ -40,10 +44,12 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase ...@@ -40,10 +44,12 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
*/ */
public stock.StockItem reserveItem() throws stock.StockException public stock.StockItem reserveItem() throws stock.StockException
{ {
for(int i=0;i<numObjects;i++) { for (int i = 0;i < numObjects;i++)
if(!stock[i].inUse) { {
if (!stock[i].inUse)
{
stock[i].inUse = true; stock[i].inUse = true;
System.out.println("Reserving slot "+i); System.out.println("Reserving slot " + i);
return stock[i].ref; return stock[i].ref;
} }
} }
...@@ -55,15 +61,17 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase ...@@ -55,15 +61,17 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
*/ */
public void releaseItem(stock.StockItem item) throws stock.StockException public void releaseItem(stock.StockItem item) throws stock.StockException
{ {
for(int i=0;i<numObjects;i++) { for (int i = 0;i < numObjects;i++)
if(stock[i].ref.getInstanceName().equals(item.getInstanceName())) { {
if (stock[i].ref.getInstanceName().equals(item.getInstanceName()))
{
stock[i].inUse = false; stock[i].inUse = false;
System.out.println("Releasing slot "+i); System.out.println("Releasing slot " + i);
return; return ;
} }
} }
System.out.println("Reserved object not a member of this dispenser"); System.out.println("Reserved object not a member of this dispenser");
return; return ;
} }
/** /**
...@@ -74,7 +82,8 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase ...@@ -74,7 +82,8 @@ public class StockDispenserImpl extends stock._StockDispenserImplBase
StockItemImpl ref; StockItemImpl ref;
boolean inUse; boolean inUse;
StockItemStatus() { StockItemStatus()
{
ref = null; ref = null;
inUse = false; inUse = false;
} }
......
...@@ -5,21 +5,25 @@ import org.omg.CosNaming.*; ...@@ -5,21 +5,25 @@ import org.omg.CosNaming.*;
/** /**
* This class implements the server side of the example. * This class implements the server side of the example.
* *
* $Id: StockItemImpl.java,v 1.1 1999/01/25 21:22:04 scrappy Exp $ * $Id: StockItemImpl.java,v 1.2 2001/10/25 05:59:58 momjian Exp $
*/ */
public class StockItemImpl extends stock._StockItemImplBase public class StockItemImpl extends stock._StockItemImplBase
{ {
private StockDB db; private StockDB db;
private String instanceName; private String instanceName;
public StockItemImpl(String[] args,String iname) { public StockItemImpl(String[] args, String iname)
{
super(); super();
try { try
db =new StockDB(); {
db.connect(args[1],args[2],args[3]); db = new StockDB();
System.out.println("StockDB object "+iname+" created"); db.connect(args[1], args[2], args[3]);
System.out.println("StockDB object " + iname + " created");
instanceName = iname; instanceName = iname;
} catch(Exception e) { }
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
...@@ -29,10 +33,14 @@ public class StockItemImpl extends stock._StockItemImplBase ...@@ -29,10 +33,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It sets the item to view * It sets the item to view
*/ */
public void fetchItem(int id) throws stock.StockException { public void fetchItem(int id) throws stock.StockException
try { {
try
{
db.fetchItem(id); db.fetchItem(id);
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
...@@ -43,10 +51,14 @@ public class StockItemImpl extends stock._StockItemImplBase ...@@ -43,10 +51,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It sets the item to view * It sets the item to view
*/ */
public int newItem() throws stock.StockException { public int newItem() throws stock.StockException
try { {
try
{
return db.newItem(); return db.newItem();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
...@@ -56,10 +68,14 @@ public class StockItemImpl extends stock._StockItemImplBase ...@@ -56,10 +68,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public String getDescription() throws stock.StockException { public String getDescription() throws stock.StockException
try { {
try
{
return db.getDescription(); return db.getDescription();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
...@@ -69,10 +85,14 @@ public class StockItemImpl extends stock._StockItemImplBase ...@@ -69,10 +85,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public int getAvailable() throws stock.StockException { public int getAvailable() throws stock.StockException
try { {
try
{
return db.getAvailable(); return db.getAvailable();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
...@@ -82,10 +102,14 @@ public class StockItemImpl extends stock._StockItemImplBase ...@@ -82,10 +102,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public int getOrdered() throws stock.StockException { public int getOrdered() throws stock.StockException
try { {
try
{
return db.getOrdered(); return db.getOrdered();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
...@@ -95,10 +119,14 @@ public class StockItemImpl extends stock._StockItemImplBase ...@@ -95,10 +119,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public boolean isItemValid() throws stock.StockException { public boolean isItemValid() throws stock.StockException
try { {
try
{
return db.isItemValid(); return db.isItemValid();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
...@@ -108,10 +136,14 @@ public class StockItemImpl extends stock._StockItemImplBase ...@@ -108,10 +136,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public void addNewStock(int id) throws stock.StockException { public void addNewStock(int id) throws stock.StockException
try { {
try
{
db.addNewStock(id); db.addNewStock(id);
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
...@@ -121,10 +153,14 @@ public class StockItemImpl extends stock._StockItemImplBase ...@@ -121,10 +153,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public void removeStock(int id) throws stock.StockException { public void removeStock(int id) throws stock.StockException
try { {
try
{
db.removeStock(id); db.removeStock(id);
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
...@@ -134,10 +170,14 @@ public class StockItemImpl extends stock._StockItemImplBase ...@@ -134,10 +170,14 @@ public class StockItemImpl extends stock._StockItemImplBase
* *
* It returns the description of a Stock item * It returns the description of a Stock item
*/ */
public void orderStock(int id) throws stock.StockException { public void orderStock(int id) throws stock.StockException
try { {
try
{
db.orderStock(id); db.orderStock(id);
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
...@@ -145,10 +185,14 @@ public class StockItemImpl extends stock._StockItemImplBase ...@@ -145,10 +185,14 @@ public class StockItemImpl extends stock._StockItemImplBase
/** /**
* This returns the highest id used, hence the number of items available * This returns the highest id used, hence the number of items available
*/ */
public int getLastID() throws stock.StockException { public int getLastID() throws stock.StockException
try { {
try
{
return db.getLastID(); return db.getLastID();
} catch(Exception e) { }
catch (Exception e)
{
throw new stock.StockException(e.toString()); throw new stock.StockException(e.toString());
} }
} }
...@@ -156,7 +200,8 @@ public class StockItemImpl extends stock._StockItemImplBase ...@@ -156,7 +200,8 @@ public class StockItemImpl extends stock._StockItemImplBase
/** /**
* This is used by our Dispenser * This is used by our Dispenser
*/ */
public String getInstanceName() { public String getInstanceName()
{
return instanceName; return instanceName;
} }
} }
......
...@@ -5,7 +5,7 @@ import org.omg.CosNaming.*; ...@@ -5,7 +5,7 @@ import org.omg.CosNaming.*;
/** /**
* This class implements the server side of the example. * This class implements the server side of the example.
* *
* $Id: StockServer.java,v 1.1 1999/01/25 21:22:04 scrappy Exp $ * $Id: StockServer.java,v 1.2 2001/10/25 05:59:58 momjian Exp $
*/ */
public class StockServer public class StockServer
{ {
...@@ -13,38 +13,43 @@ public class StockServer ...@@ -13,38 +13,43 @@ public class StockServer
{ {
int numInstances = 3; int numInstances = 3;
try { try
{
// Initialise the ORB // Initialise the ORB
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,null); org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
// Create the StockDispenser object // Create the StockDispenser object
StockDispenserImpl dispenser = new StockDispenserImpl(args,"Stock Dispenser",numInstances); StockDispenserImpl dispenser = new StockDispenserImpl(args, "Stock Dispenser", numInstances);
// Export the new object // Export the new object
orb.connect(dispenser); orb.connect(dispenser);
// Get the naming service // Get the naming service
org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService"); org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
if(nameServiceObj == null) { if (nameServiceObj == null)
{
System.err.println("nameServiceObj = null"); System.err.println("nameServiceObj = null");
return; return ;
} }
org.omg.CosNaming.NamingContext nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj); org.omg.CosNaming.NamingContext nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
if(nameService == null) { if (nameService == null)
{
System.err.println("nameService = null"); System.err.println("nameService = null");
return; return ;
} }
// bind the dispenser into the naming service // bind the dispenser into the naming service
NameComponent[] dispenserName = { NameComponent[] dispenserName = {
new NameComponent("StockDispenser","Stock") new NameComponent("StockDispenser", "Stock")
}; };
nameService.rebind(dispenserName,dispenser); nameService.rebind(dispenserName, dispenser);
// Now wait forever for the current thread to die // Now wait forever for the current thread to die
Thread.currentThread().join(); Thread.currentThread().join();
} catch(Exception e) { }
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
......
...@@ -69,9 +69,12 @@ public class datestyle ...@@ -69,9 +69,12 @@ public class datestyle
*/ */
public void cleanup() public void cleanup()
{ {
try { try
{
st.executeUpdate("drop table datestyle"); st.executeUpdate("drop table datestyle");
} catch(Exception ex) { }
catch (Exception ex)
{
// We ignore any errors here // We ignore any errors here
} }
} }
...@@ -91,7 +94,7 @@ public class datestyle ...@@ -91,7 +94,7 @@ public class datestyle
// //
// NB: January = 0 here // NB: January = 0 here
// //
standard = new java.sql.Date(98,0,8); standard = new java.sql.Date(98, 0, 8);
// Now store the result. // Now store the result.
// //
...@@ -99,7 +102,7 @@ public class datestyle ...@@ -99,7 +102,7 @@ public class datestyle
// The only way of doing this is by using a PreparedStatement. // The only way of doing this is by using a PreparedStatement.
// //
PreparedStatement ps = db.prepareStatement("insert into datestyle values (?)"); PreparedStatement ps = db.prepareStatement("insert into datestyle values (?)");
ps.setDate(1,standard); ps.setDate(1, standard);
ps.executeUpdate(); ps.executeUpdate();
ps.close(); ps.close();
...@@ -112,12 +115,13 @@ public class datestyle ...@@ -112,12 +115,13 @@ public class datestyle
{ {
System.out.println("\nRunning tests:"); System.out.println("\nRunning tests:");
for(int i=0;i<styles.length;i++) { for (int i = 0;i < styles.length;i++)
System.out.print("Test "+i+" - "+styles[i]); {
System.out.print("Test " + i + " - " + styles[i]);
System.out.flush(); System.out.flush();
// set the style // set the style
st.executeUpdate("set datestyle='"+styles[i]+"'"); st.executeUpdate("set datestyle='" + styles[i] + "'");
// Now because the driver needs to know what the current style is, // Now because the driver needs to know what the current style is,
// we have to run the following: // we have to run the following:
...@@ -129,17 +133,18 @@ public class datestyle ...@@ -129,17 +133,18 @@ public class datestyle
// Throw an exception if there is no result (if the table is empty // Throw an exception if there is no result (if the table is empty
// there should still be a result). // there should still be a result).
if(rs==null) if (rs == null)
throw new SQLException("The test query returned no data"); throw new SQLException("The test query returned no data");
while(rs.next()) { while (rs.next())
{
// The JDBC spec states we should only read each column once. // The JDBC spec states we should only read each column once.
// In the current implementation of the driver, this is not necessary. // In the current implementation of the driver, this is not necessary.
// Here we use this fact to see what the query really returned. // Here we use this fact to see what the query really returned.
if(standard.equals(rs.getDate(1))) if (standard.equals(rs.getDate(1)))
System.out.println(" passed, returned "+rs.getString(1)); System.out.println(" passed, returned " + rs.getString(1));
else else
System.out.println(" failed, returned "+rs.getString(1)); System.out.println(" failed, returned " + rs.getString(1));
} }
rs.close(); rs.close();
} }
...@@ -162,19 +167,22 @@ public class datestyle ...@@ -162,19 +167,22 @@ public class datestyle
{ {
System.out.println("PostgreSQL datestyle test v6.3 rev 1\n"); System.out.println("PostgreSQL datestyle test v6.3 rev 1\n");
if(args.length<3) if (args.length < 3)
instructions(); instructions();
// This line outputs debug information to stderr. To enable this, simply // This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line // add an extra parameter to the command line
if(args.length>3) if (args.length > 3)
DriverManager.setLogStream(System.err); DriverManager.setLogStream(System.err);
// Now run the tests // Now run the tests
try { try
{
datestyle test = new datestyle(args); datestyle test = new datestyle(args);
} catch(Exception ex) { }
System.err.println("Exception caught.\n"+ex); catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }
} }
......
...@@ -22,32 +22,33 @@ public class metadata ...@@ -22,32 +22,33 @@ public class metadata
/** /**
* These are the available tests on DatabaseMetaData * These are the available tests on DatabaseMetaData
*/ */
public void doDatabaseMetaData() throws SQLException { public void doDatabaseMetaData() throws SQLException
if(doTest("getProcedures() - should show all available procedures")) {
displayResult(dbmd.getProcedures(null,null,null)); if (doTest("getProcedures() - should show all available procedures"))
displayResult(dbmd.getProcedures(null, null, null));
if(doTest("getProcedures() with pattern - should show all circle procedures")) if (doTest("getProcedures() with pattern - should show all circle procedures"))
displayResult(dbmd.getProcedures(null,null,"circle%")); displayResult(dbmd.getProcedures(null, null, "circle%"));
if(doTest("getProcedureColumns() on circle procedures")) if (doTest("getProcedureColumns() on circle procedures"))
displayResult(dbmd.getProcedureColumns(null,null,"circle%",null)); displayResult(dbmd.getProcedureColumns(null, null, "circle%", null));
if(doTest("getTables()")) if (doTest("getTables()"))
displayResult(dbmd.getTables(null,null,null,null)); displayResult(dbmd.getTables(null, null, null, null));
if(doTest("getColumns() - should show all tables, can take a while to run")) if (doTest("getColumns() - should show all tables, can take a while to run"))
displayResult(dbmd.getColumns(null,null,null,null)); displayResult(dbmd.getColumns(null, null, null, null));
if(doTest("getColumns() - should show the test_b table")) if (doTest("getColumns() - should show the test_b table"))
displayResult(dbmd.getColumns(null,null,"test_b",null)); displayResult(dbmd.getColumns(null, null, "test_b", null));
if(doTest("getColumnPrivileges() - should show all tables")) if (doTest("getColumnPrivileges() - should show all tables"))
displayResult(dbmd.getColumnPrivileges(null,null,null,null)); displayResult(dbmd.getColumnPrivileges(null, null, null, null));
if(doTest("getPrimaryKeys()")) if (doTest("getPrimaryKeys()"))
displayResult(dbmd.getPrimaryKeys(null,null,null)); displayResult(dbmd.getPrimaryKeys(null, null, null));
if(doTest("getTypeInfo()")) if (doTest("getTypeInfo()"))
displayResult(dbmd.getTypeInfo()); displayResult(dbmd.getTypeInfo());
} }
...@@ -55,7 +56,8 @@ public class metadata ...@@ -55,7 +56,8 @@ public class metadata
/** /**
* These are the available tests on ResultSetMetaData * These are the available tests on ResultSetMetaData
*/ */
public void doResultSetMetaData() throws SQLException { public void doResultSetMetaData() throws SQLException
{
String sql = "select imagename,descr,source,cost from test_a,test_b,test_c where test_a.id=test_b.imageid and test_a.id=test_c.imageid"; String sql = "select imagename,descr,source,cost from test_a,test_b,test_c where test_a.id=test_b.imageid and test_a.id=test_c.imageid";
...@@ -63,24 +65,27 @@ public class metadata ...@@ -63,24 +65,27 @@ public class metadata
ResultSet rs = st.executeQuery(sql); ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData(); ResultSetMetaData rsmd = rs.getMetaData();
if(doTest("isCurrency()")) if (doTest("isCurrency()"))
System.out.println("isCurrency on col 1 = "+rsmd.isCurrency(1)+" should be false\nisCurrency on col 4 = "+rsmd.isCurrency(4)+" should be true"); System.out.println("isCurrency on col 1 = " + rsmd.isCurrency(1) + " should be false\nisCurrency on col 4 = " + rsmd.isCurrency(4) + " should be true");
// Finally close the query. Now give the user a chance to display the // Finally close the query. Now give the user a chance to display the
// ResultSet. // ResultSet.
// //
// NB: displayResult() actually closes the ResultSet. // NB: displayResult() actually closes the ResultSet.
if(doTest("Display query result")) { if (doTest("Display query result"))
System.out.println("Query: "+sql); {
System.out.println("Query: " + sql);
displayResult(rs); displayResult(rs);
} else }
else
rs.close(); rs.close();
} }
/** /**
* This creates some test data * This creates some test data
*/ */
public void init() throws SQLException { public void init() throws SQLException
{
System.out.println("Creating some tables"); System.out.println("Creating some tables");
cleanup(); cleanup();
st.executeUpdate("create table test_a (imagename name,image oid,id int4)"); st.executeUpdate("create table test_a (imagename name,image oid,id int4)");
...@@ -96,12 +101,16 @@ public class metadata ...@@ -96,12 +101,16 @@ public class metadata
/** /**
* This removes the test data * This removes the test data
*/ */
public void cleanup() throws SQLException { public void cleanup() throws SQLException
try { {
try
{
st.executeUpdate("drop table test_a"); st.executeUpdate("drop table test_a");
st.executeUpdate("drop table test_b"); st.executeUpdate("drop table test_b");
st.executeUpdate("drop table test_c"); st.executeUpdate("drop table test_c");
} catch(Exception ex) { }
catch (Exception ex)
{
// We ignore any errors here // We ignore any errors here
} }
} }
...@@ -123,17 +132,17 @@ public class metadata ...@@ -123,17 +132,17 @@ public class metadata
st = db.createStatement(); st = db.createStatement();
// This prints the backend's version // This prints the backend's version
System.out.println("Connected to "+dbmd.getDatabaseProductName()+" "+dbmd.getDatabaseProductVersion()); System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
init(); init();
System.out.println(); System.out.println();
// Now the tests // Now the tests
if(doTest("Test DatabaseMetaData")) if (doTest("Test DatabaseMetaData"))
doDatabaseMetaData(); doDatabaseMetaData();
if(doTest("Test ResultSetMetaData")) if (doTest("Test ResultSetMetaData"))
doResultSetMetaData(); doResultSetMetaData();
System.out.println("\nNow closing the connection"); System.out.println("\nNow closing the connection");
...@@ -146,21 +155,26 @@ public class metadata ...@@ -146,21 +155,26 @@ public class metadata
/** /**
* This asks if the user requires to run a test. * This asks if the user requires to run a test.
*/ */
public boolean doTest(String s) { public boolean doTest(String s)
{
System.out.println(); System.out.println();
System.out.print(s); System.out.print(s);
System.out.print(" Perform test? Y or N:"); System.out.print(" Perform test? Y or N:");
System.out.flush(); System.out.flush();
char c = ' '; char c = ' ';
try { try
while(!(c=='n' || c=='y' || c=='N' || c=='Y')) { {
c=(char)System.in.read(); while (!(c == 'n' || c == 'y' || c == 'N' || c == 'Y'))
{
c = (char)System.in.read();
}
} }
} catch(IOException ioe) { catch (IOException ioe)
{
return false; return false;
} }
return c=='y' || c=='Y'; return c == 'y' || c == 'Y';
} }
/** /**
...@@ -170,26 +184,28 @@ public class metadata ...@@ -170,26 +184,28 @@ public class metadata
public void displayResult(ResultSet rs) throws SQLException public void displayResult(ResultSet rs) throws SQLException
{ {
ResultSetMetaData rsmd = rs.getMetaData(); ResultSetMetaData rsmd = rs.getMetaData();
int count=0; int count = 0;
// Print the result column names // Print the result column names
int cols = rsmd.getColumnCount(); int cols = rsmd.getColumnCount();
for(int i=1;i<=cols;i++) for (int i = 1;i <= cols;i++)
System.out.print(rsmd.getColumnLabel(i)+(i<cols?"\t":"\n")); System.out.print(rsmd.getColumnLabel(i) + (i < cols ? "\t" : "\n"));
// now the results // now the results
while(rs.next()) { while (rs.next())
{
count++; count++;
for(int i=1;i<=cols;i++) { for (int i = 1;i <= cols;i++)
{
Object o = rs.getObject(i); Object o = rs.getObject(i);
if(rs.wasNull()) if (rs.wasNull())
System.out.print("{null}"+(i<cols?"\t":"\n")); System.out.print("{null}" + (i < cols ? "\t" : "\n"));
else else
System.out.print(o.toString()+(i<cols?"\t":"\n")); System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
} }
} }
System.out.println("Result returned "+count+" rows."); System.out.println("Result returned " + count + " rows.");
// finally close the result set // finally close the result set
rs.close(); rs.close();
...@@ -200,43 +216,48 @@ public class metadata ...@@ -200,43 +216,48 @@ public class metadata
*/ */
public void processSlashCommand(String line) throws SQLException public void processSlashCommand(String line) throws SQLException
{ {
if(line.startsWith("\\d")) { if (line.startsWith("\\d"))
{
if(line.startsWith("\\d ")) { if (line.startsWith("\\d "))
{
// Display details about a table // Display details about a table
String table=line.substring(3); String table = line.substring(3);
displayResult(dbmd.getColumns(null,null,table,"%")); displayResult(dbmd.getColumns(null, null, table, "%"));
} else { }
else
{
String types[] = null; String types[] = null;
if(line.equals("\\d")) if (line.equals("\\d"))
types=allUserTables; types = allUserTables;
else if(line.equals("\\di")) else if (line.equals("\\di"))
types=usrIndices; types = usrIndices;
else if(line.equals("\\dt")) else if (line.equals("\\dt"))
types=usrTables; types = usrTables;
else if(line.equals("\\ds")) else if (line.equals("\\ds"))
types=usrSequences; types = usrSequences;
else if(line.equals("\\dS")) else if (line.equals("\\dS"))
types=sysTables; types = sysTables;
else else
throw new SQLException("Unsupported \\d command: "+line); throw new SQLException("Unsupported \\d command: " + line);
// Display details about all system tables // Display details about all system tables
// //
// Note: the first two arguments are ignored. To keep to the spec, // Note: the first two arguments are ignored. To keep to the spec,
// you must put null here // you must put null here
// //
displayResult(dbmd.getTables(null,null,"%",types)); displayResult(dbmd.getTables(null, null, "%", types));
}
} }
} else else
throw new SQLException("Unsupported \\ command: "+line); throw new SQLException("Unsupported \\ command: " + line);
} }
private static final String allUserTables[] = {"TABLE","INDEX","SEQUENCE"}; private static final String allUserTables[] = {"TABLE", "INDEX", "SEQUENCE"};
private static final String usrIndices[] = {"INDEX"}; private static final String usrIndices[] = {"INDEX"};
private static final String usrTables[] = {"TABLE"}; private static final String usrTables[] = {"TABLE"};
private static final String usrSequences[] = {"SEQUENCE"}; private static final String usrSequences[] = {"SEQUENCE"};
private static final String sysTables[] = {"SYSTEM TABLE","SYSTEM INDEX"}; private static final String sysTables[] = {"SYSTEM TABLE", "SYSTEM INDEX"};
/** /**
* Display some instructions on how to run the example * Display some instructions on how to run the example
...@@ -255,19 +276,22 @@ public class metadata ...@@ -255,19 +276,22 @@ public class metadata
{ {
System.out.println("PostgreSQL metdata tester v6.4 rev 1\n"); System.out.println("PostgreSQL metdata tester v6.4 rev 1\n");
if(args.length<3) if (args.length < 3)
instructions(); instructions();
// This line outputs debug information to stderr. To enable this, simply // This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line // add an extra parameter to the command line
if(args.length>3) if (args.length > 3)
DriverManager.setLogStream(System.err); DriverManager.setLogStream(System.err);
// Now run the tests // Now run the tests
try { try
{
metadata test = new metadata(args); metadata test = new metadata(args);
} catch(Exception ex) { }
System.err.println("Exception caught.\n"+ex); catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }
} }
......
...@@ -34,7 +34,7 @@ public class psql ...@@ -34,7 +34,7 @@ public class psql
st = db.createStatement(); st = db.createStatement();
// This prints the backend's version // This prints the backend's version
System.out.println("Connected to "+dbmd.getDatabaseProductName()+" "+dbmd.getDatabaseProductVersion()); System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
System.out.println(); System.out.println();
...@@ -43,23 +43,28 @@ public class psql ...@@ -43,23 +43,28 @@ public class psql
input.resetSyntax(); input.resetSyntax();
input.slashSlashComments(true); // allow // as a comment delimiter input.slashSlashComments(true); // allow // as a comment delimiter
input.eolIsSignificant(false); // treat eol's as spaces input.eolIsSignificant(false); // treat eol's as spaces
input.wordChars(32,126); input.wordChars(32, 126);
input.whitespaceChars(59,59); input.whitespaceChars(59, 59);
// input.quoteChar(39); *** CWJ: messes up literals in query string *** // input.quoteChar(39); *** CWJ: messes up literals in query string ***
// Now the main loop. // Now the main loop.
int tt=0,lineno=1; int tt = 0, lineno = 1;
while(tt!=StreamTokenizer.TT_EOF && ! done) { // done added by CWJ to permit \q command while (tt != StreamTokenizer.TT_EOF && ! done)
System.out.print("["+lineno+"] "); { // done added by CWJ to permit \q command
System.out.print("[" + lineno + "] ");
System.out.flush(); System.out.flush();
// Here, we trap SQLException so they don't terminate the application // Here, we trap SQLException so they don't terminate the application
try { try
if((tt=input.nextToken())==StreamTokenizer.TT_WORD) { {
if ((tt = input.nextToken()) == StreamTokenizer.TT_WORD)
{
processLine(input.sval); processLine(input.sval);
lineno++; lineno++;
} }
} catch(SQLException ex) { }
catch (SQLException ex)
{
System.out.println(ex.getMessage()); System.out.println(ex.getMessage());
} }
} }
...@@ -75,31 +80,39 @@ public class psql ...@@ -75,31 +80,39 @@ public class psql
*/ */
public void processLine(String line) throws SQLException public void processLine(String line) throws SQLException
{ {
if(line.startsWith("\\")) { if (line.startsWith("\\"))
{
processSlashCommand(line); processSlashCommand(line);
return; return ;
} }
boolean type = st.execute(line); boolean type = st.execute(line);
boolean loop=true; boolean loop = true;
while(loop) { while (loop)
if(type) { {
if (type)
{
// A ResultSet was returned // A ResultSet was returned
ResultSet rs=st.getResultSet(); ResultSet rs = st.getResultSet();
displayResult(rs); displayResult(rs);
} else { }
else
{
int count = st.getUpdateCount(); int count = st.getUpdateCount();
if(count==-1) { if (count == -1)
{
// This indicates nothing left // This indicates nothing left
loop=false; loop = false;
} else { }
else
{
// An update count was returned // An update count was returned
System.out.println("Updated "+st.getUpdateCount()+" rows"); System.out.println("Updated " + st.getUpdateCount() + " rows");
} }
} }
if(loop) if (loop)
type = st.getMoreResults(); type = st.getMoreResults();
} }
} }
...@@ -114,17 +127,19 @@ public class psql ...@@ -114,17 +127,19 @@ public class psql
// Print the result column names // Print the result column names
int cols = rsmd.getColumnCount(); int cols = rsmd.getColumnCount();
for(int i=1;i<=cols;i++) for (int i = 1;i <= cols;i++)
System.out.print(rsmd.getColumnLabel(i)+(i<cols?"\t":"\n")); System.out.print(rsmd.getColumnLabel(i) + (i < cols ? "\t" : "\n"));
// now the results // now the results
while(rs.next()) { while (rs.next())
for(int i=1;i<=cols;i++) { {
for (int i = 1;i <= cols;i++)
{
Object o = rs.getObject(i); Object o = rs.getObject(i);
if(rs.wasNull()) if (rs.wasNull())
System.out.print("{null}"+(i<cols?"\t":"\n")); System.out.print("{null}" + (i < cols ? "\t" : "\n"));
else else
System.out.print(o.toString()+(i<cols?"\t":"\n")); System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
} }
} }
...@@ -137,45 +152,50 @@ public class psql ...@@ -137,45 +152,50 @@ public class psql
*/ */
public void processSlashCommand(String line) throws SQLException public void processSlashCommand(String line) throws SQLException
{ {
if(line.startsWith("\\d")) { if (line.startsWith("\\d"))
{
if(line.startsWith("\\d ")) { if (line.startsWith("\\d "))
{
// Display details about a table // Display details about a table
String table=line.substring(3); String table = line.substring(3);
displayResult(dbmd.getColumns(null,null,table,"%")); displayResult(dbmd.getColumns(null, null, table, "%"));
} else { }
else
{
String types[] = null; String types[] = null;
if(line.equals("\\d")) if (line.equals("\\d"))
types=allUserTables; types = allUserTables;
else if(line.equals("\\di")) else if (line.equals("\\di"))
types=usrIndices; types = usrIndices;
else if(line.equals("\\dt")) else if (line.equals("\\dt"))
types=usrTables; types = usrTables;
else if(line.equals("\\ds")) else if (line.equals("\\ds"))
types=usrSequences; types = usrSequences;
else if(line.equals("\\dS")) else if (line.equals("\\dS"))
types=sysTables; types = sysTables;
else else
throw new SQLException("Unsupported \\d command: "+line); throw new SQLException("Unsupported \\d command: " + line);
// Display details about all system tables // Display details about all system tables
// //
// Note: the first two arguments are ignored. To keep to the spec, // Note: the first two arguments are ignored. To keep to the spec,
// you must put null here // you must put null here
// //
displayResult(dbmd.getTables(null,null,"%",types)); displayResult(dbmd.getTables(null, null, "%", types));
}
} }
} else if(line.equals("\\q")) // Added by CWJ to permit \q command else if (line.equals("\\q")) // Added by CWJ to permit \q command
done = true; done = true;
else else
throw new SQLException("Unsupported \\ command: "+line); throw new SQLException("Unsupported \\ command: " + line);
} }
private static final String allUserTables[] = {"TABLE","INDEX","SEQUENCE"}; private static final String allUserTables[] = {"TABLE", "INDEX", "SEQUENCE"};
private static final String usrIndices[] = {"INDEX"}; private static final String usrIndices[] = {"INDEX"};
private static final String usrTables[] = {"TABLE"}; private static final String usrTables[] = {"TABLE"};
private static final String usrSequences[] = {"SEQUENCE"}; private static final String usrSequences[] = {"SEQUENCE"};
private static final String sysTables[] = {"SYSTEM TABLE","SYSTEM INDEX"}; private static final String sysTables[] = {"SYSTEM TABLE", "SYSTEM INDEX"};
/** /**
* Display some instructions on how to run the example * Display some instructions on how to run the example
...@@ -194,19 +214,22 @@ public class psql ...@@ -194,19 +214,22 @@ public class psql
{ {
System.out.println("PostgreSQL psql example v6.3 rev 1\n"); System.out.println("PostgreSQL psql example v6.3 rev 1\n");
if(args.length<3) if (args.length < 3)
instructions(); instructions();
// This line outputs debug information to stderr. To enable this, simply // This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line // add an extra parameter to the command line
if(args.length>3) if (args.length > 3)
DriverManager.setLogStream(System.err); DriverManager.setLogStream(System.err);
// Now run the tests // Now run the tests
try { try
{
psql test = new psql(args); psql test = new psql(args);
} catch(Exception ex) { }
System.err.println("Exception caught.\n"+ex); catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace(); ex.printStackTrace();
} }
} }
......
This diff is collapsed.
...@@ -28,7 +28,7 @@ public class Field ...@@ -28,7 +28,7 @@ public class Field
* @param oid the OID of the field * @param oid the OID of the field
* @param len the length of the field * @param len the length of the field
*/ */
public Field(Connection conn, String name, int oid, int length,int mod) public Field(Connection conn, String name, int oid, int length, int mod)
{ {
this.conn = conn; this.conn = conn;
this.name = name; this.name = name;
...@@ -47,7 +47,7 @@ public class Field ...@@ -47,7 +47,7 @@ public class Field
*/ */
public Field(Connection conn, String name, int oid, int length) public Field(Connection conn, String name, int oid, int length)
{ {
this(conn,name,oid,length,0); this(conn, name, oid, length, 0);
} }
/** /**
......
...@@ -10,7 +10,7 @@ import org.postgresql.core.*; ...@@ -10,7 +10,7 @@ import org.postgresql.core.*;
import org.postgresql.util.*; import org.postgresql.util.*;
/** /**
* $Id: PG_Stream.java,v 1.13 2001/08/26 17:08:48 momjian Exp $ * $Id: PG_Stream.java,v 1.14 2001/10/25 05:59:59 momjian Exp $
* *
* This class is used by Connection & PGlobj for communicating with the * This class is used by Connection & PGlobj for communicating with the
* backend. * backend.
...@@ -100,7 +100,7 @@ public class PG_Stream ...@@ -100,7 +100,7 @@ public class PG_Stream
*/ */
public void Send(byte buf[], int siz) throws IOException public void Send(byte buf[], int siz) throws IOException
{ {
Send(buf,0,siz); Send(buf, 0, siz);
} }
/** /**
...@@ -116,10 +116,10 @@ public class PG_Stream ...@@ -116,10 +116,10 @@ public class PG_Stream
{ {
int i; int i;
pg_output.write(buf, off, ((buf.length-off) < siz ? (buf.length-off) : siz)); pg_output.write(buf, off, ((buf.length - off) < siz ? (buf.length - off) : siz));
if((buf.length-off) < siz) if ((buf.length - off) < siz)
{ {
for (i = buf.length-off ; i < siz ; ++i) for (i = buf.length - off ; i < siz ; ++i)
{ {
pg_output.write(0); pg_output.write(0);
} }
...@@ -139,9 +139,12 @@ public class PG_Stream ...@@ -139,9 +139,12 @@ public class PG_Stream
try try
{ {
c = pg_input.read(); c = pg_input.read();
if (c < 0) throw new PSQLException("postgresql.stream.eof"); if (c < 0)
} catch (IOException e) { throw new PSQLException("postgresql.stream.eof");
throw new PSQLException("postgresql.stream.ioerror",e); }
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
} }
return c; return c;
} }
...@@ -167,8 +170,10 @@ public class PG_Stream ...@@ -167,8 +170,10 @@ public class PG_Stream
throw new PSQLException("postgresql.stream.eof"); throw new PSQLException("postgresql.stream.eof");
n = n | (b << (8 * i)) ; n = n | (b << (8 * i)) ;
} }
} catch (IOException e) { }
throw new PSQLException("postgresql.stream.ioerror",e); catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
} }
return n; return n;
} }
...@@ -194,8 +199,10 @@ public class PG_Stream ...@@ -194,8 +199,10 @@ public class PG_Stream
throw new PSQLException("postgresql.stream.eof"); throw new PSQLException("postgresql.stream.eof");
n = b | (n << 8); n = b | (n << 8);
} }
} catch (IOException e) { }
throw new PSQLException("postgresql.stream.ioerror",e); catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
} }
return n; return n;
} }
...@@ -213,31 +220,40 @@ public class PG_Stream ...@@ -213,31 +220,40 @@ public class PG_Stream
{ {
int s = 0; int s = 0;
byte[] rst = byte_buf; byte[] rst = byte_buf;
try { try
{
int buflen = rst.length; int buflen = rst.length;
boolean done = false; boolean done = false;
while (!done) { while (!done)
while (s < buflen) { {
while (s < buflen)
{
int c = pg_input.read(); int c = pg_input.read();
if (c < 0) if (c < 0)
throw new PSQLException("postgresql.stream.eof"); throw new PSQLException("postgresql.stream.eof");
else if (c == 0) { else if (c == 0)
{
rst[s] = 0; rst[s] = 0;
done = true; done = true;
break; break;
} else { }
else
{
rst[s++] = (byte)c; rst[s++] = (byte)c;
} }
if (s >= buflen) { // Grow the buffer if (s >= buflen)
buflen = (int)(buflen*2); // 100% bigger { // Grow the buffer
buflen = (int)(buflen * 2); // 100% bigger
byte[] newrst = new byte[buflen]; byte[] newrst = new byte[buflen];
System.arraycopy(rst, 0, newrst, 0, s); System.arraycopy(rst, 0, newrst, 0, s);
rst = newrst; rst = newrst;
} }
} }
} }
} catch (IOException e) { }
throw new PSQLException("postgresql.stream.ioerror",e); catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
} }
return encoding.decode(rst, 0, s); return encoding.decode(rst, 0, s);
} }
...@@ -254,7 +270,7 @@ public class PG_Stream ...@@ -254,7 +270,7 @@ public class PG_Stream
*/ */
public byte[][] ReceiveTuple(int nf, boolean bin) throws SQLException public byte[][] ReceiveTuple(int nf, boolean bin) throws SQLException
{ {
int i, bim = (nf + 7)/8; int i, bim = (nf + 7) / 8;
byte[] bitmask = Receive(bim); byte[] bitmask = Receive(bim);
byte[][] answer = bytePoolDim2.allocByte(nf); byte[][] answer = bytePoolDim2.allocByte(nf);
...@@ -295,7 +311,7 @@ public class PG_Stream ...@@ -295,7 +311,7 @@ public class PG_Stream
private byte[] Receive(int siz) throws SQLException private byte[] Receive(int siz) throws SQLException
{ {
byte[] answer = bytePoolDim1.allocByte(siz); byte[] answer = bytePoolDim1.allocByte(siz);
Receive(answer,0,siz); Receive(answer, 0, siz);
return answer; return answer;
} }
...@@ -307,7 +323,7 @@ public class PG_Stream ...@@ -307,7 +323,7 @@ public class PG_Stream
* @param siz number of bytes to read * @param siz number of bytes to read
* @exception SQLException if a data I/O error occurs * @exception SQLException if a data I/O error occurs
*/ */
public void Receive(byte[] b,int off,int siz) throws SQLException public void Receive(byte[] b, int off, int siz) throws SQLException
{ {
int s = 0; int s = 0;
...@@ -315,13 +331,15 @@ public class PG_Stream ...@@ -315,13 +331,15 @@ public class PG_Stream
{ {
while (s < siz) while (s < siz)
{ {
int w = pg_input.read(b, off+s, siz - s); int w = pg_input.read(b, off + s, siz - s);
if (w < 0) if (w < 0)
throw new PSQLException("postgresql.stream.eof"); throw new PSQLException("postgresql.stream.eof");
s += w; s += w;
} }
} catch (IOException e) { }
throw new PSQLException("postgresql.stream.ioerror",e); catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", e);
} }
} }
...@@ -332,10 +350,13 @@ public class PG_Stream ...@@ -332,10 +350,13 @@ public class PG_Stream
*/ */
public void flush() throws SQLException public void flush() throws SQLException
{ {
try { try
{
pg_output.flush(); pg_output.flush();
} catch (IOException e) { }
throw new PSQLException("postgresql.stream.flush",e); catch (IOException e)
{
throw new PSQLException("postgresql.stream.flush", e);
} }
} }
......
/** /**
* Redistribution and use of this software and associated documentation * Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided * ("Software"), with or without modification, are permitted provided
* that the following conditions are met: * that the following conditions are met:
* *
* 1. Redistributions of source code must retain copyright * 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a * statements and notices. Redistributions must also contain a
* copy of this document. * copy of this document.
* *
* 2. Redistributions in binary form must reproduce the * 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the * above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other * following disclaimer in the documentation and/or other
* materials provided with the distribution. * materials provided with the distribution.
* *
* 3. The name "Exolab" must not be used to endorse or promote * 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written * products derived from this Software without prior written
* permission of Exoffice Technologies. For written permission, * permission of Exoffice Technologies. For written permission,
* please contact info@exolab.org. * please contact info@exolab.org.
* *
* 4. Products derived from this Software may not be called "Exolab" * 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written * nor may "Exolab" appear in their names without prior written
* permission of Exoffice Technologies. Exolab is a registered * permission of Exoffice Technologies. Exolab is a registered
* trademark of Exoffice Technologies. * trademark of Exoffice Technologies.
* *
* 5. Due credit should be given to the Exolab Project * 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/). * (http://www.exolab.org/).
* *
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE. * OF THE POSSIBILITY OF SUCH DAMAGE.
* *
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved. * Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
* *
* $Id: PostgresqlDataSource.java,v 1.2 2000/11/10 22:06:26 momjian Exp $ * $Id: PostgresqlDataSource.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
*/ */
package org.postgresql; package org.postgresql;
...@@ -194,10 +194,10 @@ public class PostgresqlDataSource ...@@ -194,10 +194,10 @@ public class PostgresqlDataSource
* Each datasource maintains it's own driver, in case of * Each datasource maintains it's own driver, in case of
* driver-specific setup (e.g. pools, log writer). * driver-specific setup (e.g. pools, log writer).
*/ */
// FIXME // FIXME
// private transient postgresql.Driver _driver; // private transient postgresql.Driver _driver;
private transient org.postgresql.Driver _driver; private transient org.postgresql.Driver _driver;
//--------- //---------
...@@ -223,21 +223,25 @@ private transient org.postgresql.Driver _driver; ...@@ -223,21 +223,25 @@ private transient org.postgresql.Driver _driver;
Properties info; Properties info;
String url; String url;
if ( _driver == null ) { if ( _driver == null )
try { {
try
{
// Constructs a driver for use just by this data source // Constructs a driver for use just by this data source
// which will produce TwoPhaseConnection-s. This driver // which will produce TwoPhaseConnection-s. This driver
// is not registered with the driver manager. // is not registered with the driver manager.
// FIXME // FIXME
// _driver = new postgresql.Driver(); // _driver = new postgresql.Driver();
_driver = new org.postgresql.Driver(); _driver = new org.postgresql.Driver();
//----------- //-----------
//FIXME //FIXME
// _driver.setLogWriter( _logWriter ); // _driver.setLogWriter( _logWriter );
// Method seems to be unavailable. Just commented it out. // Method seems to be unavailable. Just commented it out.
//---------- //----------
} catch ( SQLException except ) { }
catch ( SQLException except )
{
if ( _logWriter != null ) if ( _logWriter != null )
_logWriter.println( "DataSource: Failed to initialize JDBC driver: " + except ); _logWriter.println( "DataSource: Failed to initialize JDBC driver: " + except );
throw except; throw except;
...@@ -249,7 +253,8 @@ _driver = new org.postgresql.Driver(); ...@@ -249,7 +253,8 @@ _driver = new org.postgresql.Driver();
info.put( "loginTimeout", Integer.toString( _loginTimeout ) ); info.put( "loginTimeout", Integer.toString( _loginTimeout ) );
// DriverManager will do that and not rely on the URL alone. // DriverManager will do that and not rely on the URL alone.
if ( user == null ) { if ( user == null )
{
user = _user; user = _user;
password = _password; password = _password;
} }
...@@ -270,17 +275,21 @@ _driver = new org.postgresql.Driver(); ...@@ -270,17 +275,21 @@ _driver = new org.postgresql.Driver();
// Attempt to establish a connection. Report a successful // Attempt to establish a connection. Report a successful
// attempt or a failure. // attempt or a failure.
try { try
{
conn = _driver.connect( url, info ); conn = _driver.connect( url, info );
// FIXME // FIXME
// if ( ! ( conn instanceof postgresql.jdbc2.Connection ) ) { // if ( ! ( conn instanceof postgresql.jdbc2.Connection ) ) {
if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) { if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) )
//-------- {
//--------
if ( _logWriter != null ) if ( _logWriter != null )
_logWriter.println( "DataSource: JDBC 1 connections not supported" ); _logWriter.println( "DataSource: JDBC 1 connections not supported" );
throw new PSQLException( "postgresql.ds.onlyjdbc2" ); throw new PSQLException( "postgresql.ds.onlyjdbc2" );
} }
} catch ( SQLException except ) { }
catch ( SQLException except )
{
if ( _logWriter != null ) if ( _logWriter != null )
_logWriter.println( "DataSource: getConnection failed " + except ); _logWriter.println( "DataSource: getConnection failed " + except );
throw except; throw except;
...@@ -302,12 +311,13 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) { ...@@ -302,12 +311,13 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) {
// Once a log writer has been set, we cannot set it since some // Once a log writer has been set, we cannot set it since some
// thread might be conditionally accessing it right now without // thread might be conditionally accessing it right now without
// synchronizing. // synchronizing.
if ( writer != null ) { if ( writer != null )
{
if ( _driver != null ) if ( _driver != null )
// FIXME // FIXME
// _driver.setLogWriter( writer ); // _driver.setLogWriter( writer );
// Method seems to be unavailable. Commented it out. // Method seems to be unavailable. Commented it out.
//---------- //----------
_logWriter = writer; _logWriter = writer;
} }
} }
...@@ -507,16 +517,19 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) { ...@@ -507,16 +517,19 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) {
{ {
if ( _description != null ) if ( _description != null )
return _description; return _description;
else { else
{
String url; String url;
url = "jdbc:postgresql:"; url = "jdbc:postgresql:";
if ( _serverName != null ) { if ( _serverName != null )
{
if ( _portNumber == DEFAULT_PORT ) if ( _portNumber == DEFAULT_PORT )
url = url + "//" + _serverName + "/"; url = url + "//" + _serverName + "/";
else else
url = url + "//" + _serverName + ":" + _portNumber + "/"; url = url + "//" + _serverName + ":" + _portNumber + "/";
} else if ( _portNumber != DEFAULT_PORT ) }
else if ( _portNumber != DEFAULT_PORT )
url = url + "//localhost:" + _portNumber + "/"; url = url + "//localhost:" + _portNumber + "/";
if ( _databaseName != null ) if ( _databaseName != null )
url = url + _databaseName; url = url + _databaseName;
...@@ -555,17 +568,22 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) { ...@@ -555,17 +568,22 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) {
Reference ref; Reference ref;
// Can only reconstruct from a reference. // Can only reconstruct from a reference.
if ( refObj instanceof Reference ) { if ( refObj instanceof Reference )
{
ref = (Reference) refObj; ref = (Reference) refObj;
// Make sure reference is of datasource class. // Make sure reference is of datasource class.
if ( ref.getClassName().equals( getClass().getName() ) ) { if ( ref.getClassName().equals( getClass().getName() ) )
{
PostgresqlDataSource ds; PostgresqlDataSource ds;
RefAddr addr; RefAddr addr;
try { try
{
ds = (PostgresqlDataSource) Class.forName( ref.getClassName() ).newInstance(); ds = (PostgresqlDataSource) Class.forName( ref.getClassName() ).newInstance();
} catch ( Exception except ) { }
catch ( Exception except )
{
throw new NamingException( except.toString() ); throw new NamingException( except.toString() );
} }
// Mandatory properties // Mandatory properties
...@@ -590,9 +608,11 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) { ...@@ -590,9 +608,11 @@ if ( ! ( conn instanceof org.postgresql.jdbc2.Connection ) ) {
setTransactionTimeout( Integer.parseInt( (String) addr.getContent() ) ); setTransactionTimeout( Integer.parseInt( (String) addr.getContent() ) );
return ds; return ds;
} else }
else
throw new NamingException( "DataSource: Reference not constructed from class " + getClass().getName() ); throw new NamingException( "DataSource: Reference not constructed from class " + getClass().getName() );
} else if ( refObj instanceof Remote ) }
else if ( refObj instanceof Remote )
return refObj; return refObj;
else else
return null; return null;
......
...@@ -42,7 +42,7 @@ public abstract class ResultSet ...@@ -42,7 +42,7 @@ public abstract class ResultSet
* @param updateCount the number of rows affected by the operation * @param updateCount the number of rows affected by the operation
* @param cursor the positioned update/delete cursor name * @param cursor the positioned update/delete cursor name
*/ */
public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount,int insertOID, boolean binaryCursor) public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount, int insertOID, boolean binaryCursor)
{ {
this.connection = conn; this.connection = conn;
this.fields = fields; this.fields = fields;
...@@ -69,7 +69,7 @@ public abstract class ResultSet ...@@ -69,7 +69,7 @@ public abstract class ResultSet
*/ */
public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount) public ResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount)
{ {
this(conn,fields,tuples,status,updateCount,0,false); this(conn, fields, tuples, status, updateCount, 0, false);
} }
/** /**
...@@ -166,7 +166,7 @@ public abstract class ResultSet ...@@ -166,7 +166,7 @@ public abstract class ResultSet
*/ */
public int getColumnOID(int field) public int getColumnOID(int field)
{ {
return fields[field-1].getOID(); return fields[field -1].getOID();
} }
/** /**
...@@ -190,20 +190,23 @@ public abstract class ResultSet ...@@ -190,20 +190,23 @@ public abstract class ResultSet
* *
* It converts ($##.##) to -##.## and $##.## to ##.## * It converts ($##.##) to -##.## and $##.## to ##.##
*/ */
public String getFixedString(int col) throws SQLException { public String getFixedString(int col) throws SQLException
{
String s = getString(col); String s = getString(col);
// Handle SQL Null // Handle SQL Null
wasNullFlag = (this_row[col - 1] == null); wasNullFlag = (this_row[col - 1] == null);
if(wasNullFlag) if (wasNullFlag)
return null; return null;
// Handle Money // Handle Money
if(s.charAt(0)=='(') { if (s.charAt(0) == '(')
s="-"+org.postgresql.util.PGtokenizer.removePara(s).substring(1); {
s = "-" + org.postgresql.util.PGtokenizer.removePara(s).substring(1);
} }
if(s.charAt(0)=='$') { if (s.charAt(0) == '$')
s=s.substring(1); {
s = s.substring(1);
} }
return s; return s;
......
...@@ -23,7 +23,8 @@ import org.postgresql.util.PSQLException; ...@@ -23,7 +23,8 @@ import org.postgresql.util.PSQLException;
* JDBC3. * JDBC3.
*/ */
public abstract class Statement { public abstract class Statement
{
/** The warnings chain. */ /** The warnings chain. */
protected SQLWarning warnings = null; protected SQLWarning warnings = null;
...@@ -42,11 +43,11 @@ public abstract class Statement { ...@@ -42,11 +43,11 @@ public abstract class Statement {
// Static variables for parsing SQL when escapeProcessing is true. // Static variables for parsing SQL when escapeProcessing is true.
private static final short IN_SQLCODE = 0; private static final short IN_SQLCODE = 0;
private static final short IN_STRING = 1; private static final short IN_STRING = 1;
private static final short BACKSLASH =2; private static final short BACKSLASH = 2;
private static final short ESC_TIMEDATE = 3; private static final short ESC_TIMEDATE = 3;
public Statement() { public Statement()
} {}
/** /**
* Returns the status message from the current Result.<p> * Returns the status message from the current Result.<p>
...@@ -54,7 +55,8 @@ public abstract class Statement { ...@@ -54,7 +55,8 @@ public abstract class Statement {
* *
* @return status message from backend * @return status message from backend
*/ */
public String getResultStatusString() { public String getResultStatusString()
{
if (result == null) if (result == null)
return null; return null;
return ((org.postgresql.ResultSet) result).getStatusString(); return ((org.postgresql.ResultSet) result).getStatusString();
...@@ -68,7 +70,8 @@ public abstract class Statement { ...@@ -68,7 +70,8 @@ public abstract class Statement {
* @return the current maximum row limit; zero means unlimited * @return the current maximum row limit; zero means unlimited
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public int getMaxRows() throws SQLException { public int getMaxRows() throws SQLException
{
return maxrows; return maxrows;
} }
...@@ -79,7 +82,8 @@ public abstract class Statement { ...@@ -79,7 +82,8 @@ public abstract class Statement {
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
* @see getMaxRows * @see getMaxRows
*/ */
public void setMaxRows(int max) throws SQLException { public void setMaxRows(int max) throws SQLException
{
maxrows = max; maxrows = max;
} }
...@@ -90,7 +94,8 @@ public abstract class Statement { ...@@ -90,7 +94,8 @@ public abstract class Statement {
* @param enable true to enable; false to disable * @param enable true to enable; false to disable
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void setEscapeProcessing(boolean enable) throws SQLException { public void setEscapeProcessing(boolean enable) throws SQLException
{
escapeProcessing = enable; escapeProcessing = enable;
} }
...@@ -102,7 +107,8 @@ public abstract class Statement { ...@@ -102,7 +107,8 @@ public abstract class Statement {
* @return the current query timeout limit in seconds; 0 = unlimited * @return the current query timeout limit in seconds; 0 = unlimited
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public int getQueryTimeout() throws SQLException { public int getQueryTimeout() throws SQLException
{
return timeout; return timeout;
} }
...@@ -112,7 +118,8 @@ public abstract class Statement { ...@@ -112,7 +118,8 @@ public abstract class Statement {
* @param seconds - the new query timeout limit in seconds * @param seconds - the new query timeout limit in seconds
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void setQueryTimeout(int seconds) throws SQLException { public void setQueryTimeout(int seconds) throws SQLException
{
timeout = seconds; timeout = seconds;
} }
...@@ -132,7 +139,8 @@ public abstract class Statement { ...@@ -132,7 +139,8 @@ public abstract class Statement {
* @return the first SQLWarning on null * @return the first SQLWarning on null
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public SQLWarning getWarnings() throws SQLException { public SQLWarning getWarnings() throws SQLException
{
return warnings; return warnings;
} }
...@@ -146,7 +154,8 @@ public abstract class Statement { ...@@ -146,7 +154,8 @@ public abstract class Statement {
* @return the current max column size limit; zero means unlimited * @return the current max column size limit; zero means unlimited
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public int getMaxFieldSize() throws SQLException { public int getMaxFieldSize() throws SQLException
{
return 8192; // We cannot change this return 8192; // We cannot change this
} }
...@@ -157,7 +166,8 @@ public abstract class Statement { ...@@ -157,7 +166,8 @@ public abstract class Statement {
* @param max the new max column size limit; zero means unlimited * @param max the new max column size limit; zero means unlimited
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void setMaxFieldSize(int max) throws SQLException { public void setMaxFieldSize(int max) throws SQLException
{
throw new PSQLException("postgresql.stat.maxfieldsize"); throw new PSQLException("postgresql.stat.maxfieldsize");
} }
...@@ -167,7 +177,8 @@ public abstract class Statement { ...@@ -167,7 +177,8 @@ public abstract class Statement {
* *
* @exception SQLException if a database access error occurs * @exception SQLException if a database access error occurs
*/ */
public void clearWarnings() throws SQLException { public void clearWarnings() throws SQLException
{
warnings = null; warnings = null;
} }
...@@ -179,7 +190,8 @@ public abstract class Statement { ...@@ -179,7 +190,8 @@ public abstract class Statement {
* *
* @exception SQLException only because thats the spec. * @exception SQLException only because thats the spec.
*/ */
public void cancel() throws SQLException { public void cancel() throws SQLException
{
// FIXME: Cancel feature has been available since 6.4. Implement it here! // FIXME: Cancel feature has been available since 6.4. Implement it here!
} }
...@@ -189,7 +201,8 @@ public abstract class Statement { ...@@ -189,7 +201,8 @@ public abstract class Statement {
* null. * null.
* @return OID of last insert * @return OID of last insert
*/ */
public int getInsertedOID() throws SQLException { public int getInsertedOID() throws SQLException
{
if (result == null) if (result == null)
return 0; return 0;
return ((org.postgresql.ResultSet) result).getInsertedOID(); return ((org.postgresql.ResultSet) result).getInsertedOID();
...@@ -202,7 +215,8 @@ public abstract class Statement { ...@@ -202,7 +215,8 @@ public abstract class Statement {
* @return the current result set; null if there are no more * @return the current result set; null if there are no more
* @exception SQLException if a database access error occurs (why?) * @exception SQLException if a database access error occurs (why?)
*/ */
public java.sql.ResultSet getResultSet() throws SQLException { public java.sql.ResultSet getResultSet() throws SQLException
{
if (result != null && ((org.postgresql.ResultSet) result).reallyResultSet()) if (result != null && ((org.postgresql.ResultSet) result).reallyResultSet())
return result; return result;
return null; return null;
...@@ -220,10 +234,11 @@ public abstract class Statement { ...@@ -220,10 +234,11 @@ public abstract class Statement {
* *
* @exception SQLException if a database access error occurs (why?) * @exception SQLException if a database access error occurs (why?)
*/ */
public void close() throws SQLException { public void close() throws SQLException
{
// Force the ResultSet to close // Force the ResultSet to close
java.sql.ResultSet rs = getResultSet(); java.sql.ResultSet rs = getResultSet();
if(rs!=null) if (rs != null)
rs.close(); rs.close();
// Disasociate it from us (For Garbage Collection) // Disasociate it from us (For Garbage Collection)
...@@ -249,28 +264,28 @@ public abstract class Statement { ...@@ -249,28 +264,28 @@ public abstract class Statement {
int i = -1; int i = -1;
int len = sql.length(); int len = sql.length();
while(++i < len) while (++i < len)
{ {
char c = sql.charAt(i); char c = sql.charAt(i);
switch(state) switch (state)
{ {
case IN_SQLCODE: case IN_SQLCODE:
if(c == '\'') // start of a string? if (c == '\'') // start of a string?
state = IN_STRING; state = IN_STRING;
else if(c == '{') // start of an escape code? else if (c == '{') // start of an escape code?
if(i+1 < len) if (i + 1 < len)
{ {
char next = sql.charAt(i+1); char next = sql.charAt(i + 1);
if(next == 'd') if (next == 'd')
{ {
state = ESC_TIMEDATE; state = ESC_TIMEDATE;
i++; i++;
break; break;
} }
else if(next == 't') else if (next == 't')
{ {
state = ESC_TIMEDATE; state = ESC_TIMEDATE;
i += (i+2 < len && sql.charAt(i+2) == 's') ? 2 : 1; i += (i + 2 < len && sql.charAt(i + 2) == 's') ? 2 : 1;
break; break;
} }
} }
...@@ -278,9 +293,9 @@ public abstract class Statement { ...@@ -278,9 +293,9 @@ public abstract class Statement {
break; break;
case IN_STRING: case IN_STRING:
if(c == '\'') // end of string? if (c == '\'') // end of string?
state = IN_SQLCODE; state = IN_SQLCODE;
else if(c == '\\') // a backslash? else if (c == '\\') // a backslash?
state = BACKSLASH; state = BACKSLASH;
newsql.append(c); newsql.append(c);
...@@ -293,7 +308,7 @@ public abstract class Statement { ...@@ -293,7 +308,7 @@ public abstract class Statement {
break; break;
case ESC_TIMEDATE: case ESC_TIMEDATE:
if(c == '}') if (c == '}')
state = IN_SQLCODE; // end of escape code. state = IN_SQLCODE; // end of escape code.
else else
newsql.append(c); newsql.append(c);
......
...@@ -4,7 +4,8 @@ package org.postgresql.core; ...@@ -4,7 +4,8 @@ package org.postgresql.core;
* A simple and efficient class to pool one dimensional byte arrays * A simple and efficient class to pool one dimensional byte arrays
* of different sizes. * of different sizes.
*/ */
public class BytePoolDim1 { public class BytePoolDim1
{
/** /**
* The maximum size of the array we manage. * The maximum size of the array we manage.
...@@ -13,21 +14,23 @@ public class BytePoolDim1 { ...@@ -13,21 +14,23 @@ public class BytePoolDim1 {
/** /**
* The pools not currently in use * The pools not currently in use
*/ */
ObjectPool notusemap[] = new ObjectPool[maxsize+1]; ObjectPool notusemap[] = new ObjectPool[maxsize + 1];
/** /**
* The pools currently in use * The pools currently in use
*/ */
ObjectPool inusemap[] = new ObjectPool[maxsize+1]; ObjectPool inusemap[] = new ObjectPool[maxsize + 1];
/** /**
* *
*/ */
byte binit[][] = new byte[maxsize+1][0]; byte binit[][] = new byte[maxsize + 1][0];
/** /**
* Construct a new pool * Construct a new pool
*/ */
public BytePoolDim1(){ public BytePoolDim1()
for(int i = 0; i <= maxsize; i++){ {
for (int i = 0; i <= maxsize; i++)
{
binit[i] = new byte[i]; binit[i] = new byte[i];
inusemap[i] = new SimpleObjectPool(); inusemap[i] = new SimpleObjectPool();
notusemap[i] = new SimpleObjectPool(); notusemap[i] = new SimpleObjectPool();
...@@ -39,7 +42,8 @@ public class BytePoolDim1 { ...@@ -39,7 +42,8 @@ public class BytePoolDim1 {
* larger than maxsize then it is not pooled. * larger than maxsize then it is not pooled.
* @return the byte[] allocated * @return the byte[] allocated
*/ */
public byte[] allocByte(int size) { public byte[] allocByte(int size)
{
// for now until the bug can be removed // for now until the bug can be removed
return new byte[size]; return new byte[size];
/* /*
...@@ -69,10 +73,11 @@ public class BytePoolDim1 { ...@@ -69,10 +73,11 @@ public class BytePoolDim1 {
* Release an array * Release an array
* @param b byte[] to release * @param b byte[] to release
*/ */
public void release(byte[] b) { public void release(byte[] b)
{
// If it's larger than maxsize then we don't touch it // If it's larger than maxsize then we don't touch it
if(b.length>maxsize) if (b.length > maxsize)
return; return ;
ObjectPool not_usel = notusemap[b.length]; ObjectPool not_usel = notusemap[b.length];
ObjectPool in_usel = inusemap[b.length]; ObjectPool in_usel = inusemap[b.length];
...@@ -85,7 +90,8 @@ public class BytePoolDim1 { ...@@ -85,7 +90,8 @@ public class BytePoolDim1 {
* Deallocate all * Deallocate all
* @deprecated Real bad things happen if this is called! * @deprecated Real bad things happen if this is called!
*/ */
public void deallocate() { public void deallocate()
{
//for(int i = 0; i <= maxsize; i++){ //for(int i = 0; i <= maxsize; i++){
// notusemap[i].addAll(inusemap[i]); // notusemap[i].addAll(inusemap[i]);
// inusemap[i].clear(); // inusemap[i].clear();
......
package org.postgresql.core; package org.postgresql.core;
public class BytePoolDim2 { public class BytePoolDim2
{
int maxsize = 32; int maxsize = 32;
ObjectPool notusemap[] = new ObjectPool[maxsize+1]; ObjectPool notusemap[] = new ObjectPool[maxsize + 1];
ObjectPool inusemap[] = new ObjectPool[maxsize+1]; ObjectPool inusemap[] = new ObjectPool[maxsize + 1];
public BytePoolDim2(){ public BytePoolDim2()
for(int i = 0; i <= maxsize; i++){ {
for (int i = 0; i <= maxsize; i++)
{
inusemap[i] = new SimpleObjectPool(); inusemap[i] = new SimpleObjectPool();
notusemap[i] = new SimpleObjectPool(); notusemap[i] = new SimpleObjectPool();
} }
} }
public byte[][] allocByte(int size){ public byte[][] allocByte(int size)
{
// For now until the bug can be removed // For now until the bug can be removed
return new byte[size][0]; return new byte[size][0];
/* /*
...@@ -34,9 +38,11 @@ public class BytePoolDim2 { ...@@ -34,9 +38,11 @@ public class BytePoolDim2 {
*/ */
} }
public void release(byte[][] b){ public void release(byte[][] b)
if(b.length > maxsize){ {
return; if (b.length > maxsize)
{
return ;
} }
ObjectPool not_usel = notusemap[b.length]; ObjectPool not_usel = notusemap[b.length];
ObjectPool in_usel = inusemap[b.length]; ObjectPool in_usel = inusemap[b.length];
...@@ -52,7 +58,8 @@ public class BytePoolDim2 { ...@@ -52,7 +58,8 @@ public class BytePoolDim2 {
* code to use some form of Statement context, so the buffers are per * code to use some form of Statement context, so the buffers are per
* Statement and not per Connection/PG_Stream as it is now. * Statement and not per Connection/PG_Stream as it is now.
*/ */
public void deallocate(){ public void deallocate()
{
//for(int i = 0; i <= maxsize; i++){ //for(int i = 0; i <= maxsize; i++){
// notusemap[i].addAll(inusemap[i]); // notusemap[i].addAll(inusemap[i]);
// inusemap[i].clear(); // inusemap[i].clear();
......
...@@ -8,10 +8,11 @@ import org.postgresql.util.*; ...@@ -8,10 +8,11 @@ import org.postgresql.util.*;
/** /**
* Converts to and from the character encoding used by the backend. * Converts to and from the character encoding used by the backend.
* *
* $Id: Encoding.java,v 1.2 2001/10/16 20:07:17 barry Exp $ * $Id: Encoding.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
*/ */
public class Encoding { public class Encoding
{
private static final Encoding DEFAULT_ENCODING = new Encoding(null); private static final Encoding DEFAULT_ENCODING = new Encoding(null);
...@@ -59,7 +60,8 @@ public class Encoding { ...@@ -59,7 +60,8 @@ public class Encoding {
private final String encoding; private final String encoding;
private Encoding(String encoding) { private Encoding(String encoding)
{
this.encoding = encoding; this.encoding = encoding;
} }
...@@ -70,13 +72,19 @@ public class Encoding { ...@@ -70,13 +72,19 @@ public class Encoding {
public static Encoding getEncoding(String databaseEncoding, public static Encoding getEncoding(String databaseEncoding,
String passedEncoding) String passedEncoding)
{ {
if (passedEncoding != null) { if (passedEncoding != null)
if (isAvailable(passedEncoding)) { {
if (isAvailable(passedEncoding))
{
return new Encoding(passedEncoding); return new Encoding(passedEncoding);
} else { }
else
{
return defaultEncoding(); return defaultEncoding();
} }
} else { }
else
{
return encodingForDatabaseEncoding(databaseEncoding); return encodingForDatabaseEncoding(databaseEncoding);
} }
} }
...@@ -84,15 +92,19 @@ public class Encoding { ...@@ -84,15 +92,19 @@ public class Encoding {
/** /**
* Get an Encoding matching the given database encoding. * Get an Encoding matching the given database encoding.
*/ */
private static Encoding encodingForDatabaseEncoding(String databaseEncoding) { private static Encoding encodingForDatabaseEncoding(String databaseEncoding)
{
// If the backend encoding is known and there is a suitable // If the backend encoding is known and there is a suitable
// encoding in the JVM we use that. Otherwise we fall back // encoding in the JVM we use that. Otherwise we fall back
// to the default encoding of the JVM. // to the default encoding of the JVM.
if (encodings.containsKey(databaseEncoding)) { if (encodings.containsKey(databaseEncoding))
{
String[] candidates = (String[]) encodings.get(databaseEncoding); String[] candidates = (String[]) encodings.get(databaseEncoding);
for (int i = 0; i < candidates.length; i++) { for (int i = 0; i < candidates.length; i++)
if (isAvailable(candidates[i])) { {
if (isAvailable(candidates[i]))
{
return new Encoding(candidates[i]); return new Encoding(candidates[i]);
} }
} }
...@@ -103,21 +115,29 @@ public class Encoding { ...@@ -103,21 +115,29 @@ public class Encoding {
/** /**
* Name of the (JVM) encoding used. * Name of the (JVM) encoding used.
*/ */
public String name() { public String name()
{
return encoding; return encoding;
} }
/** /**
* Encode a string to an array of bytes. * Encode a string to an array of bytes.
*/ */
public byte[] encode(String s) throws SQLException { public byte[] encode(String s) throws SQLException
try { {
if (encoding == null) { try
{
if (encoding == null)
{
return s.getBytes(); return s.getBytes();
} else { }
else
{
return s.getBytes(encoding); return s.getBytes(encoding);
} }
} catch (UnsupportedEncodingException e) { }
catch (UnsupportedEncodingException e)
{
throw new PSQLException("postgresql.stream.encoding", e); throw new PSQLException("postgresql.stream.encoding", e);
} }
} }
...@@ -125,14 +145,21 @@ public class Encoding { ...@@ -125,14 +145,21 @@ public class Encoding {
/** /**
* Decode an array of bytes into a string. * Decode an array of bytes into a string.
*/ */
public String decode(byte[] encodedString, int offset, int length) throws SQLException { public String decode(byte[] encodedString, int offset, int length) throws SQLException
try { {
if (encoding == null) { try
{
if (encoding == null)
{
return new String(encodedString, offset, length); return new String(encodedString, offset, length);
} else { }
else
{
return new String(encodedString, offset, length, encoding); return new String(encodedString, offset, length, encoding);
} }
} catch (UnsupportedEncodingException e) { }
catch (UnsupportedEncodingException e)
{
throw new PSQLException("postgresql.stream.encoding", e); throw new PSQLException("postgresql.stream.encoding", e);
} }
} }
...@@ -140,21 +167,29 @@ public class Encoding { ...@@ -140,21 +167,29 @@ public class Encoding {
/** /**
* Decode an array of bytes into a string. * Decode an array of bytes into a string.
*/ */
public String decode(byte[] encodedString) throws SQLException { public String decode(byte[] encodedString) throws SQLException
{
return decode(encodedString, 0, encodedString.length); return decode(encodedString, 0, encodedString.length);
} }
/** /**
* Get a Reader that decodes the given InputStream. * Get a Reader that decodes the given InputStream.
*/ */
public Reader getDecodingReader(InputStream in) throws SQLException { public Reader getDecodingReader(InputStream in) throws SQLException
try { {
if (encoding == null) { try
{
if (encoding == null)
{
return new InputStreamReader(in); return new InputStreamReader(in);
} else { }
else
{
return new InputStreamReader(in, encoding); return new InputStreamReader(in, encoding);
} }
} catch (UnsupportedEncodingException e) { }
catch (UnsupportedEncodingException e)
{
throw new PSQLException("postgresql.res.encoding", e); throw new PSQLException("postgresql.res.encoding", e);
} }
} }
...@@ -162,18 +197,23 @@ public class Encoding { ...@@ -162,18 +197,23 @@ public class Encoding {
/** /**
* Get an Encoding using the default encoding for the JVM. * Get an Encoding using the default encoding for the JVM.
*/ */
public static Encoding defaultEncoding() { public static Encoding defaultEncoding()
{
return DEFAULT_ENCODING; return DEFAULT_ENCODING;
} }
/** /**
* Test if an encoding is available in the JVM. * Test if an encoding is available in the JVM.
*/ */
private static boolean isAvailable(String encodingName) { private static boolean isAvailable(String encodingName)
try { {
try
{
"DUMMY".getBytes(encodingName); "DUMMY".getBytes(encodingName);
return true; return true;
} catch (UnsupportedEncodingException e) { }
catch (UnsupportedEncodingException e)
{
return false; return false;
} }
} }
......
...@@ -3,7 +3,8 @@ package org.postgresql.core; ...@@ -3,7 +3,8 @@ package org.postgresql.core;
/** /**
* This interface defines the methods to access the memory pool classes. * This interface defines the methods to access the memory pool classes.
*/ */
public interface MemoryPool { public interface MemoryPool
{
/** /**
* Allocate an array from the pool * Allocate an array from the pool
* @return byte[] allocated * @return byte[] allocated
......
...@@ -6,7 +6,8 @@ package org.postgresql.core; ...@@ -6,7 +6,8 @@ package org.postgresql.core;
* other for jdk1.2+ * other for jdk1.2+
*/ */
public interface ObjectPool { public interface ObjectPool
{
/** /**
* Adds an object to the pool * Adds an object to the pool
* @param o Object to add * @param o Object to add
......
...@@ -13,10 +13,11 @@ import org.postgresql.util.PSQLException; ...@@ -13,10 +13,11 @@ import org.postgresql.util.PSQLException;
* <p>The lifetime of a QueryExecutor object is from sending the query * <p>The lifetime of a QueryExecutor object is from sending the query
* until the response has been received from the backend. * until the response has been received from the backend.
* *
* $Id: QueryExecutor.java,v 1.2 2001/10/09 20:47:35 barry Exp $ * $Id: QueryExecutor.java,v 1.3 2001/10/25 05:59:59 momjian Exp $
*/ */
public class QueryExecutor { public class QueryExecutor
{
private final String sql; private final String sql;
private final java.sql.Statement statement; private final java.sql.Statement statement;
...@@ -51,16 +52,19 @@ public class QueryExecutor { ...@@ -51,16 +52,19 @@ public class QueryExecutor {
/** /**
* Execute a query on the backend. * Execute a query on the backend.
*/ */
public java.sql.ResultSet execute() throws SQLException { public java.sql.ResultSet execute() throws SQLException
{
int fqp = 0; int fqp = 0;
boolean hfr = false; boolean hfr = false;
synchronized(pg_stream) { synchronized (pg_stream)
{
sendQuery(sql); sendQuery(sql);
while (!hfr || fqp > 0) { while (!hfr || fqp > 0)
{
int c = pg_stream.ReceiveChar(); int c = pg_stream.ReceiveChar();
switch (c) switch (c)
...@@ -77,7 +81,8 @@ public class QueryExecutor { ...@@ -77,7 +81,8 @@ public class QueryExecutor {
if (fields != null) if (fields != null)
hfr = true; hfr = true;
else { else
{
sendQuery(" "); sendQuery(" ");
fqp++; fqp++;
} }
...@@ -120,14 +125,18 @@ public class QueryExecutor { ...@@ -120,14 +125,18 @@ public class QueryExecutor {
/** /**
* Send a query to the backend. * Send a query to the backend.
*/ */
private void sendQuery(String query) throws SQLException { private void sendQuery(String query) throws SQLException
try { {
try
{
pg_stream.SendChar('Q'); pg_stream.SendChar('Q');
pg_stream.Send(connection.getEncoding().encode(query)); pg_stream.Send(connection.getEncoding().encode(query));
pg_stream.SendChar(0); pg_stream.SendChar(0);
pg_stream.flush(); pg_stream.flush();
} catch (IOException e) { }
catch (IOException e)
{
throw new PSQLException("postgresql.con.ioerror", e); throw new PSQLException("postgresql.con.ioerror", e);
} }
} }
...@@ -137,11 +146,13 @@ public class QueryExecutor { ...@@ -137,11 +146,13 @@ public class QueryExecutor {
* *
* @param isBinary set if the tuple should be treated as binary data * @param isBinary set if the tuple should be treated as binary data
*/ */
private void receiveTuple(boolean isBinary) throws SQLException { private void receiveTuple(boolean isBinary) throws SQLException
{
if (fields == null) if (fields == null)
throw new PSQLException("postgresql.con.tuple"); throw new PSQLException("postgresql.con.tuple");
Object tuple = pg_stream.ReceiveTuple(fields.length, isBinary); Object tuple = pg_stream.ReceiveTuple(fields.length, isBinary);
if (isBinary) binaryCursor = true; if (isBinary)
binaryCursor = true;
if (maxRows == 0 || tuples.size() < maxRows) if (maxRows == 0 || tuples.size() < maxRows)
tuples.addElement(tuple); tuples.addElement(tuple);
} }
...@@ -149,20 +160,26 @@ public class QueryExecutor { ...@@ -149,20 +160,26 @@ public class QueryExecutor {
/** /**
* Receive command status from the backend. * Receive command status from the backend.
*/ */
private void receiveCommandStatus() throws SQLException { private void receiveCommandStatus() throws SQLException
{
status = pg_stream.ReceiveString(connection.getEncoding()); status = pg_stream.ReceiveString(connection.getEncoding());
try { try
{
// Now handle the update count correctly. // Now handle the update count correctly.
if (status.startsWith("INSERT") || status.startsWith("UPDATE") || status.startsWith("DELETE") || status.startsWith("MOVE")) { if (status.startsWith("INSERT") || status.startsWith("UPDATE") || status.startsWith("DELETE") || status.startsWith("MOVE"))
{
update_count = Integer.parseInt(status.substring(1 + status.lastIndexOf(' '))); update_count = Integer.parseInt(status.substring(1 + status.lastIndexOf(' ')));
} }
if (status.startsWith("INSERT")) { if (status.startsWith("INSERT"))
{
insert_oid = Integer.parseInt(status.substring(1 + status.indexOf(' '), insert_oid = Integer.parseInt(status.substring(1 + status.indexOf(' '),
status.lastIndexOf(' '))); status.lastIndexOf(' ')));
} }
} catch (NumberFormatException nfe) { }
catch (NumberFormatException nfe)
{
throw new PSQLException("postgresql.con.fathom", status); throw new PSQLException("postgresql.con.fathom", status);
} }
} }
...@@ -170,14 +187,16 @@ public class QueryExecutor { ...@@ -170,14 +187,16 @@ public class QueryExecutor {
/** /**
* Receive the field descriptions from the back end. * Receive the field descriptions from the back end.
*/ */
private void receiveFields() throws SQLException { private void receiveFields() throws SQLException
{
if (fields != null) if (fields != null)
throw new PSQLException("postgresql.con.multres"); throw new PSQLException("postgresql.con.multres");
int size = pg_stream.ReceiveIntegerR(2); int size = pg_stream.ReceiveIntegerR(2);
fields = new Field[size]; fields = new Field[size];
for (int i = 0; i < fields.length; i++) { for (int i = 0; i < fields.length; i++)
{
String typeName = pg_stream.ReceiveString(connection.getEncoding()); String typeName = pg_stream.ReceiveString(connection.getEncoding());
int typeOid = pg_stream.ReceiveIntegerR(4); int typeOid = pg_stream.ReceiveIntegerR(4);
int typeLength = pg_stream.ReceiveIntegerR(2); int typeLength = pg_stream.ReceiveIntegerR(2);
......
...@@ -21,8 +21,9 @@ public class SimpleObjectPool implements ObjectPool ...@@ -21,8 +21,9 @@ public class SimpleObjectPool implements ObjectPool
*/ */
public void add(Object o) public void add(Object o)
{ {
if(cursize >= maxsize){ if (cursize >= maxsize)
Object newarr[] = new Object[maxsize*2]; {
Object newarr[] = new Object[maxsize * 2];
System.arraycopy(arr, 0, newarr, 0, maxsize); System.arraycopy(arr, 0, newarr, 0, maxsize);
maxsize = maxsize * 2; maxsize = maxsize * 2;
arr = newarr; arr = newarr;
...@@ -34,7 +35,8 @@ public class SimpleObjectPool implements ObjectPool ...@@ -34,7 +35,8 @@ public class SimpleObjectPool implements ObjectPool
* Removes the top object from the pool * Removes the top object from the pool
* @return Object from the top. * @return Object from the top.
*/ */
public Object remove(){ public Object remove()
{
return arr[--cursize]; return arr[--cursize];
} }
...@@ -42,13 +44,15 @@ public class SimpleObjectPool implements ObjectPool ...@@ -42,13 +44,15 @@ public class SimpleObjectPool implements ObjectPool
* Removes the given object from the pool * Removes the given object from the pool
* @param o Object to remove * @param o Object to remove
*/ */
public void remove(Object o) { public void remove(Object o)
int p=0; {
while(p<cursize && !arr[p].equals(o)) int p = 0;
while (p < cursize && !arr[p].equals(o))
p++; p++;
if(arr[p].equals(o)) { if (arr[p].equals(o))
{
// This should be ok as there should be no overlap conflict // This should be ok as there should be no overlap conflict
System.arraycopy(arr,p+1,arr,p,cursize-p); System.arraycopy(arr, p + 1, arr, p, cursize - p);
cursize--; cursize--;
} }
} }
...@@ -56,14 +60,16 @@ public class SimpleObjectPool implements ObjectPool ...@@ -56,14 +60,16 @@ public class SimpleObjectPool implements ObjectPool
/** /**
* @return true if the pool is empty * @return true if the pool is empty
*/ */
public boolean isEmpty(){ public boolean isEmpty()
{
return cursize == 0; return cursize == 0;
} }
/** /**
* @return the number of objects in the pool * @return the number of objects in the pool
*/ */
public int size(){ public int size()
{
return cursize; return cursize;
} }
...@@ -71,15 +77,17 @@ public class SimpleObjectPool implements ObjectPool ...@@ -71,15 +77,17 @@ public class SimpleObjectPool implements ObjectPool
* Adds all objects in one pool to this one * Adds all objects in one pool to this one
* @param pool The pool to take the objects from * @param pool The pool to take the objects from
*/ */
public void addAll(ObjectPool p){ public void addAll(ObjectPool p)
{
SimpleObjectPool pool = (SimpleObjectPool)p; SimpleObjectPool pool = (SimpleObjectPool)p;
int srcsize = pool.size(); int srcsize = pool.size();
if(srcsize == 0) if (srcsize == 0)
return; return ;
int totalsize = srcsize + cursize; int totalsize = srcsize + cursize;
if(totalsize > maxsize){ if (totalsize > maxsize)
Object newarr[] = new Object[totalsize*2]; {
Object newarr[] = new Object[totalsize * 2];
System.arraycopy(arr, 0, newarr, 0, cursize); System.arraycopy(arr, 0, newarr, 0, cursize);
maxsize = maxsize = totalsize * 2; maxsize = maxsize = totalsize * 2;
arr = newarr; arr = newarr;
...@@ -91,7 +99,8 @@ public class SimpleObjectPool implements ObjectPool ...@@ -91,7 +99,8 @@ public class SimpleObjectPool implements ObjectPool
/** /**
* Clears the pool of all objects * Clears the pool of all objects
*/ */
public void clear(){ public void clear()
{
cursize = 0; cursize = 0;
} }
} }
...@@ -40,10 +40,10 @@ public class Fastpath ...@@ -40,10 +40,10 @@ public class Fastpath
* @param conn org.postgresql.Connection to attach to * @param conn org.postgresql.Connection to attach to
* @param stream The network stream to the backend * @param stream The network stream to the backend
*/ */
public Fastpath(org.postgresql.Connection conn,org.postgresql.PG_Stream stream) public Fastpath(org.postgresql.Connection conn, org.postgresql.PG_Stream stream)
{ {
this.conn=conn; this.conn = conn;
this.stream=stream; this.stream = stream;
//DriverManager.println("Fastpath initialised"); //DriverManager.println("Fastpath initialised");
} }
...@@ -56,29 +56,33 @@ public class Fastpath ...@@ -56,29 +56,33 @@ public class Fastpath
* @return null if no data, Integer if an integer result, or byte[] otherwise * @return null if no data, Integer if an integer result, or byte[] otherwise
* @exception SQLException if a database-access error occurs. * @exception SQLException if a database-access error occurs.
*/ */
public Object fastpath(int fnid,boolean resulttype,FastpathArg[] args) throws SQLException public Object fastpath(int fnid, boolean resulttype, FastpathArg[] args) throws SQLException
{ {
// added Oct 7 1998 to give us thread safety // added Oct 7 1998 to give us thread safety
synchronized(stream) { synchronized (stream)
{
// send the function call // send the function call
try { try
{
// 70 is 'F' in ASCII. Note: don't use SendChar() here as it adds padding // 70 is 'F' in ASCII. Note: don't use SendChar() here as it adds padding
// that confuses the backend. The 0 terminates the command line. // that confuses the backend. The 0 terminates the command line.
stream.SendInteger(70,1); stream.SendInteger(70, 1);
stream.SendInteger(0,1); stream.SendInteger(0, 1);
stream.SendInteger(fnid,4); stream.SendInteger(fnid, 4);
stream.SendInteger(args.length,4); stream.SendInteger(args.length, 4);
for(int i=0;i<args.length;i++) for (int i = 0;i < args.length;i++)
args[i].send(stream); args[i].send(stream);
// This is needed, otherwise data can be lost // This is needed, otherwise data can be lost
stream.flush(); stream.flush();
} catch(IOException ioe) { }
throw new PSQLException("postgresql.fp.send",new Integer(fnid),ioe); catch (IOException ioe)
{
throw new PSQLException("postgresql.fp.send", new Integer(fnid), ioe);
} }
// Now handle the result // Now handle the result
...@@ -95,10 +99,11 @@ public class Fastpath ...@@ -95,10 +99,11 @@ public class Fastpath
// Now loop, reading the results // Now loop, reading the results
Object result = null; // our result Object result = null; // our result
while(true) { while (true)
{
int in = stream.ReceiveChar(); int in = stream.ReceiveChar();
//DriverManager.println("ReceiveChar() = "+in+" '"+((char)in)+"'"); //DriverManager.println("ReceiveChar() = "+in+" '"+((char)in)+"'");
switch(in) switch (in)
{ {
case 'V': case 'V':
break; break;
...@@ -111,11 +116,12 @@ public class Fastpath ...@@ -111,11 +116,12 @@ public class Fastpath
//DriverManager.println("G: size="+sz); //debug //DriverManager.println("G: size="+sz); //debug
// Return an Integer if // Return an Integer if
if(resulttype) if (resulttype)
result = new Integer(stream.ReceiveIntegerR(sz)); result = new Integer(stream.ReceiveIntegerR(sz));
else { else
{
byte buf[] = new byte[sz]; byte buf[] = new byte[sz];
stream.Receive(buf,0,sz); stream.Receive(buf, 0, sz);
result = buf; result = buf;
} }
break; break;
...@@ -123,7 +129,7 @@ public class Fastpath ...@@ -123,7 +129,7 @@ public class Fastpath
//------------------------------ //------------------------------
// Error message returned // Error message returned
case 'E': case 'E':
throw new PSQLException("postgresql.fp.error",stream.ReceiveString(conn.getEncoding())); throw new PSQLException("postgresql.fp.error", stream.ReceiveString(conn.getEncoding()));
//------------------------------ //------------------------------
// Notice from backend // Notice from backend
...@@ -144,7 +150,7 @@ public class Fastpath ...@@ -144,7 +150,7 @@ public class Fastpath
break; break;
default: default:
throw new PSQLException("postgresql.fp.protocol",new Character((char)in)); throw new PSQLException("postgresql.fp.protocol", new Character((char)in));
} }
} }
} }
...@@ -170,10 +176,10 @@ public class Fastpath ...@@ -170,10 +176,10 @@ public class Fastpath
* occurs. * occurs.
* @see org.postgresql.LargeObject * @see org.postgresql.LargeObject
*/ */
public Object fastpath(String name,boolean resulttype,FastpathArg[] args) throws SQLException public Object fastpath(String name, boolean resulttype, FastpathArg[] args) throws SQLException
{ {
//DriverManager.println("Fastpath: calling "+name); //DriverManager.println("Fastpath: calling "+name);
return fastpath(getID(name),resulttype,args); return fastpath(getID(name), resulttype, args);
} }
/** /**
...@@ -183,11 +189,11 @@ public class Fastpath ...@@ -183,11 +189,11 @@ public class Fastpath
* @return integer result * @return integer result
* @exception SQLException if a database-access error occurs or no result * @exception SQLException if a database-access error occurs or no result
*/ */
public int getInteger(String name,FastpathArg[] args) throws SQLException public int getInteger(String name, FastpathArg[] args) throws SQLException
{ {
Integer i = (Integer)fastpath(name,true,args); Integer i = (Integer)fastpath(name, true, args);
if(i==null) if (i == null)
throw new PSQLException("postgresql.fp.expint",name); throw new PSQLException("postgresql.fp.expint", name);
return i.intValue(); return i.intValue();
} }
...@@ -198,9 +204,9 @@ public class Fastpath ...@@ -198,9 +204,9 @@ public class Fastpath
* @return byte[] array containing result * @return byte[] array containing result
* @exception SQLException if a database-access error occurs or no result * @exception SQLException if a database-access error occurs or no result
*/ */
public byte[] getData(String name,FastpathArg[] args) throws SQLException public byte[] getData(String name, FastpathArg[] args) throws SQLException
{ {
return (byte[])fastpath(name,false,args); return (byte[])fastpath(name, false, args);
} }
/** /**
...@@ -214,9 +220,9 @@ public class Fastpath ...@@ -214,9 +220,9 @@ public class Fastpath
* @param name Function name * @param name Function name
* @param fnid Function id * @param fnid Function id
*/ */
public void addFunction(String name,int fnid) public void addFunction(String name, int fnid)
{ {
func.put(name,new Integer(fnid)); func.put(name, new Integer(fnid));
} }
/** /**
...@@ -253,8 +259,9 @@ public class Fastpath ...@@ -253,8 +259,9 @@ public class Fastpath
*/ */
public void addFunctions(ResultSet rs) throws SQLException public void addFunctions(ResultSet rs) throws SQLException
{ {
while(rs.next()) { while (rs.next())
func.put(rs.getString(1),new Integer(rs.getInt(2))); {
func.put(rs.getString(1), new Integer(rs.getInt(2)));
} }
} }
...@@ -279,8 +286,8 @@ public class Fastpath ...@@ -279,8 +286,8 @@ public class Fastpath
// //
// so, until we know we can do this (needs testing, on the TODO list) // so, until we know we can do this (needs testing, on the TODO list)
// for now, we throw the exception and do no lookups. // for now, we throw the exception and do no lookups.
if(id==null) if (id == null)
throw new PSQLException("postgresql.fp.unknown",name); throw new PSQLException("postgresql.fp.unknown", name);
return id.intValue(); return id.intValue();
} }
......
...@@ -43,8 +43,8 @@ public class FastpathArg ...@@ -43,8 +43,8 @@ public class FastpathArg
*/ */
public FastpathArg(int value) public FastpathArg(int value)
{ {
type=true; type = true;
this.value=value; this.value = value;
} }
/** /**
...@@ -53,8 +53,8 @@ public class FastpathArg ...@@ -53,8 +53,8 @@ public class FastpathArg
*/ */
public FastpathArg(byte bytes[]) public FastpathArg(byte bytes[])
{ {
type=false; type = false;
this.bytes=bytes; this.bytes = bytes;
} }
/** /**
...@@ -63,11 +63,11 @@ public class FastpathArg ...@@ -63,11 +63,11 @@ public class FastpathArg
* @param off offset within array * @param off offset within array
* @param len length of data to include * @param len length of data to include
*/ */
public FastpathArg(byte buf[],int off,int len) public FastpathArg(byte buf[], int off, int len)
{ {
type=false; type = false;
bytes = new byte[len]; bytes = new byte[len];
System.arraycopy(buf,off,bytes,0,len); System.arraycopy(buf, off, bytes, 0, len);
} }
/** /**
...@@ -92,13 +92,16 @@ public class FastpathArg ...@@ -92,13 +92,16 @@ public class FastpathArg
*/ */
protected void send(org.postgresql.PG_Stream s) throws IOException protected void send(org.postgresql.PG_Stream s) throws IOException
{ {
if(type) { if (type)
{
// argument is an integer // argument is an integer
s.SendInteger(4,4); // size of an integer s.SendInteger(4, 4); // size of an integer
s.SendInteger(value,4); // integer value of argument s.SendInteger(value, 4); // integer value of argument
} else { }
else
{
// argument is a byte array // argument is a byte array
s.SendInteger(bytes.length,4); // size of array s.SendInteger(bytes.length, 4); // size of array
s.Send(bytes); s.Send(bytes);
} }
} }
......
...@@ -124,8 +124,10 @@ public class Statement extends org.postgresql.Statement implements java.sql.Stat ...@@ -124,8 +124,10 @@ public class Statement extends org.postgresql.Statement implements java.sql.Stat
*/ */
public int getUpdateCount() throws SQLException public int getUpdateCount() throws SQLException
{ {
if (result == null) return -1; if (result == null)
if (((org.postgresql.ResultSet)result).reallyResultSet()) return -1; return -1;
if (((org.postgresql.ResultSet)result).reallyResultSet())
return -1;
return ((org.postgresql.ResultSet)result).getResultCount(); return ((org.postgresql.ResultSet)result).getResultCount();
} }
......
...@@ -7,23 +7,26 @@ import java.sql.*; ...@@ -7,23 +7,26 @@ import java.sql.*;
* This class extends java.sql.BatchUpdateException, and provides our * This class extends java.sql.BatchUpdateException, and provides our
* internationalisation handling. * internationalisation handling.
*/ */
class PBatchUpdateException extends java.sql.BatchUpdateException { class PBatchUpdateException extends java.sql.BatchUpdateException
{
private String message; private String message;
public PBatchUpdateException( public PBatchUpdateException(
String error, Object arg1, Object arg2, int[] updateCounts ) { String error, Object arg1, Object arg2, int[] updateCounts )
{
super(updateCounts); super(updateCounts);
Object[] argv = new Object[2]; Object[] argv = new Object[2];
argv[0] = arg1; argv[0] = arg1;
argv[1] = arg2; argv[1] = arg2;
translate(error,argv); translate(error, argv);
} }
private void translate(String error, Object[] args) { private void translate(String error, Object[] args)
message = MessageTranslator.translate(error,args); {
message = MessageTranslator.translate(error, args);
} }
// Overides Throwable // Overides Throwable
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment