Thursday, December 20, 2007

Java Code For Reading and Writing a Properties File

// Read properties file.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("filename.properties"));
} catch (IOException e) {
}

// Write properties file.
try {
properties.store(new FileOutputStream("filename.properties"), null);
} catch (IOException e) {
}
Here is an example of the contents of a properties file: # a comment
! a comment

a = a string
b = a string with escape sequences \t \n \r \\ \" \' \ (space) \u0123
c = a string with a continuation line \
continuation line
d.e.f = another string

Friday, December 14, 2007

JAVA SECURITY

Security is, perhaps, the most important and necessary assurance requirement to consider when deploying a system. Because computing systems assume more and more widespread business and mission-critical functionality each day, the cost associated with a breach of security is also increasing. Furthermore, because security problems are human-induced problems, the range of possible problems is as limitless as the human mind. Security, thus, becomes a crucial problem to solve.

The Basic Security Model

Figure Security depicts the basic security model that results from security problems and assurance-provisioning mechanisms. At the top of the diagram, a resource provider is shown offering some security-critical data or application resources. Such resources are security-critical because a malicious being, such as the hacker depicted at the bottom of the diagram, can corrupt, reference (that is, access), replace, delay access to, or deny access to such resources.




Figure Security : The basic security model.

A security service provider depicted on the left side of the diagram attempts to protect such resources from attack by providing protection services such as integrity, confidentiality, authorization and access, identity, authenticity, availability, non repudiation, and auditing-protection services. Such services attempt to thwart the hacker's best efforts.
The right side of the diagram shows the beneficiary of the security services. These services include the following:

§ Integrity Verification: The beneficiary has some verification that the data or application is accurate.
§ Confidentiality Preservation: The beneficiary has some assurance that confidentiality of the data or application has been preserved.
§ Authorization/Access Permission: Properly authorized permission to access security-critical data, application, or other resource has been provided.
§ Identity Verification: The beneficiary has some verification that the identity associated with the data or application source is who they say they are.
§ Authenticity Permission: Properly authenticated permission to access some data, application, or other resource has been provided.
§ Availability of Service: The beneficiary has access to the data, application, or other resource when it expects to have access.
§ Nonrepudiation Evidence: The beneficiary has some evidence regarding from whom the data or application comes or has some evidence that an intended receiver actually received data sent to it.
§ Auditing Evidence: The beneficiary has some evidence of security-critical operations that take place in the system.

Java and Security

Java is a language for the Web and is used to design Web pages. The first Web pages created using Java contained just images and text. However, this was an advancement from the traditional way of presenting information. You had access to a large repository of data that could be accessed through the hyperlinks on a page. The only drawback was that for executable programs, you had to refer to the server. The Web interface was so designed that you filled up data in a page and the data was transmitted to the server where it was acted on by an executable program. There were animations or puzzles that made a Web page more exciting; however, they could not be successful if they were placed on the server for execution. Moreover, if the concerned program was placed on the server, there was a long time interval between the submission of a customer query and the result of the query being displayed on the Web page. Wouldn't it be much easier and require less overhead if executable programs could be placed on the Web page itself? However, here comes the security factor. If programs are placed on Web pages, there is a risk of viruses being downloaded when you load the specified Web page in the browser or execute the program on your computer. Second, if the program was created using a specific platform that is not supported by your system, the main benefit of the Web being platform-independent whereby you can run programs on any client is lost.

Thursday, December 13, 2007

AOP – Aspect Oriented Programming

AOP is a philosophy that is related to style of programming, first introduced by Gregor Kickzales in 1996. Like structured programming and Object-Oriented programming introduced a new approach for designing programs and a set of guidelines to make more readable and reusable code.

Aspect-oriented programming (AOP) better separates concerns than previous methodologies, thereby providing modularization of crosscutting concerns.

A concern is a particular goal, concept, or area of interest. In technology terms, a typical software system comprises several core and system-level concerns. For example, ATM processing system's core concern would process payments, while its system-level concerns would handle logging, transaction integrity, authentication, security, performance, and so on. To understand the spirit of AOP, you must understand the following issues:

Concerns Separation: referring the Law of Demeter, a project's efficiency increases if all the concerns are well modularized and if you only have to speak to your direct friends to make a modification of the program (this is a very old principle and the OOP gives some answers).

Crosscutting Concerns: in a complex system, there are always some concerns that are not easily modularized, especially common-interest concerns that, by essence, are used by several modules (i.e. several modules use/share a well-known service of a module -- such as a logging or a persistence service).

Dependencies inversion: the best way to avoid crosscutting is to NOT use the well-known services that crosscut. This is possible by reversing the dependencies (i.e. the well-known service shall use the other modules instead of the contrary). This dependency inversion is implemented by aspects.

Existing Frameworks
Probably the most mature and fully featured framework available today is AspectJ. While AspectJ sets the standard that most frameworks follow, the architects took the unusual step of adding new keywords to the Java language in their implementation. Though the new syntax isn't too difficult to learn, it does mean that you will have to change your compiler, and potentially reconfigure your editor, in order to use the new syntax. In a large team this may not be feasible, as the whole team could be affected. The modification to the language also increases the learning curve for teams looking to introduce AOP into existing projects.
What we need is a framework that can be easily introduced without severely impacting the existing development and build process. There are several frameworks that fit the bill, such as JBoss AOP, Nanning, and Aspectwerkz (AW). For this article, I've chosen Aspectwerkz because it is probably the easiest framework to learn and integrate into your existing projects.
Aspectwerkz, created by Jonas Boner and Alexandre Vasseur, remains one of the quickest and most fully featured AOP frameworks available. While it may not boast all of the features of AspectJ, it is sufficiently complete to be of great use to most developers in many situations.
One of the most interesting features of Aspectwerkz is its ability to run in two different modes: online and offline. In online mode, AW is hooked into the low-level classloading mechanism part of the JVM, allowing it to intercept all classloading calls and transform the bytecode on the fly. AW provides many options to hook in, and a wrapper script can be used as a replacement for the bin/java command to automatically detect and set a working configuration depending on the Java version and JVM capabilities. This mode holds many benefits to developers, as it can be hooked into any classloader and weave classes at classload time, which means that your class files are not modified manually, but deployed as usual. However, it does require additional configuration of your application server, which may not be possible in some situations.
In offline mode, two phases are required to generate your classes. The first phase is the standard compilation using the javac tool that we all know and love. (In fact, most of us love it so much that we replaced it with an Ant task years ago.) The second phase is where things get interesting, we run the AWcompiler in offline mode and point it to the newly created class files. The compiler will then modify the bytecode of the classes to include your advice at the correct point-cuts, as defined in an XML file. The benefit of using the offline mode is that the classes will run in any JVM from version 1.3 and up. This is the mode that I will use in this article, as it requires no modifications to Tomcat and could be applied to most existing projects with only slight modification to the build process.

Sunday, December 2, 2007

Connecting To Oracle using JDBC

--------------CODE Snippets For Connecting to Oracle Database-----------------------

Connecting to Oracle Using Thin Driver :

driverclassname = "oracle.jdbc.driver.OracleDriver";
dbprefix += "oracle:thin:";

System.out.println("Loading jdbc driver: " + driverclassname);

Class.forName(driverclassname);

DBURL = "jdbc:oracle:oci8:@::
or @::");

DBURL = dbprefix + DBURL;

After that get the useid and password from user :

con = DriverManager.getConnection(DBURL, userid, password);

---------------------------------Connection Successful-------------------------------

Connecting To DB2 using JDBC

------------------CODE Snippets For Connecting to DB2 Database-----------------------

Connecting to DB2 :

driverclassname = "COM.ibm.db2.jdbc.app.DB2Driver";
dbprefix += "db2:";

For DB2 Pure NetWork client:

driverclassname = "COM.ibm.db2.jdbc.net.DB2Driver";
dbprefix += "db2:";

System.out.println("Loading jdbc driver: " + driverclassname);

Class.forName(driverclassname);

DBURL = jdbc:db2:dbname;
DBURL = dbprefix + DBURL;

After that get the useid and password from user :

con = DriverManager.getConnection(DBURL, userid, password);

---------------------------------Connection Successful-------------------------------

Connect to Database like ( DB2 , Sybase ,Oracle,SQL server ) using JDBC

Complete Code Example : Connect to Database like ( DB2 , Sybase ,Oracle,SQL server ) using JDBC


//
// DISCLAIMER OF WARRANTIES.
// The following [enclosed] code is sample code
// This sample code is not part of any standard
// product and is provided to you solely for the purpose of assisting
// you in the development of your applications. The code is provided
// "AS IS". Authour MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE, REGARDING THE FUNCTION OR PERFORMANCE OF
// THIS CODE. THIS CODE MAY CONTAIN ERRORS. Author shall not be liable
// for any damages arising out of your use of the sample code, even
// if it has been advised of the possibility of such damages.
//


import java.sql.*;

import javax.sql.*;

import java.io.*;
import java.awt.*;
import java.awt.event.*;

public class jdbctest {

public String driverclassname;
public String DBURL;
public String dbprefix = "jdbc:";
public Connection con;
public Statement stmt;
public BufferedReader instream;
public long operationTimer;

public String response = "0";

public String globaluid = null;
public String globalpwd = null;

public String dbhostname;
public String dbport;
public String dbname;

public ClassLoader loader=null;
public Class dsClass=null;
ConnectionPoolDataSource ds=null;

public static final int DATASOURCECONNECTIONS=10;


// Capture window events...
static private class FrameCloser extends WindowAdapter {

public void windowClosing(WindowEvent we) {
System.out.println("windowClosing..." + we);
we.getWindow().dispose();
System.exit(0);
}
}

// Capture key events...
static private class KeyInterceptor implements KeyListener {
public void keyTyped(java.awt.event.KeyEvent ke) {
}
public void keyPressed(java.awt.event.KeyEvent ke) {
}
public void keyReleased(java.awt.event.KeyEvent ke) {
// System.out.println("keyReleased..." + ke);
if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
TextField tf = (TextField) ke.getComponent();
synchronized (tf) {
tf.notify();
}
} // if enter key is pressed
}
}

public static void main(String args[]) {
System.out.println("JDBC Test starting...");

jdbctest ct = new jdbctest();
ct.init(args); // Loads jdbc driver
ct.connect(); // sets connection
if (ct.con == null) {
System.out.println("Connection to " + ct.DBURL + " failed!");
System.exit(33);
}

System.out.println("Connection Successful: " + ct.con);
System.out.println(
"Connection took " + ct.operationTimer + " milliseconds to complete");
try {
System.out.println("AutoCommit is: " + ct.con.getAutoCommit());
} catch (SQLException s) {
s.printStackTrace();
System.out.println("Error code is: " + s.getErrorCode());
System.out.println("SQLState is: " + s.getSQLState());
System.exit(33);
}
do {
try {
if (!(ct.response.equals("11")) && !(ct.response.equals("10")))
{System.out.println("Create new statement...");
ct.stmt = ct.con.createStatement();}
} catch (SQLException se) {
se.printStackTrace();
System.out.println("Error code is: " + se.getErrorCode());
System.out.println("SQLState is: " + se.getSQLState());
System.exit(33);
}
} while (ct.process());
try {
if (ct.stmt != null) ct.stmt.close();
ct.con.close();
} catch (Exception e) {
e.printStackTrace();
}

// System.exit ???
System.exit(33);

}

public void init(String args[]) {
instream = new BufferedReader((new InputStreamReader(System.in)));

while (driverclassname == null) {
System.out.println(
"Please respond:\n\t1 - For DB2\n\t2 - For DB2/Pure Network Client\n\t3 - For Oracle (thin) \n\t4 -
For Oracle (oci8)\n\t5 - For Informix\n\t6 - For Sybase\n\t7 - For Cloudscape - (Local)\n\t8 - For Cloudscape - (RMI)\n\t9 -
For SQLServer (Microsoft Driver)\n\t10 - For SQLServer (SequeLink driver)\n\t11 - For SQLServer (WebSphere embedded Connect
JDBC driver)\n\t12 - For SQLServer(Data Direct Technologies Connect JDBC driver)");
response = readLine();
if (response.equals("1")) {
driverclassname = "COM.ibm.db2.jdbc.app.DB2Driver";
dbprefix += "db2:";
} else
if (response.equals("2")) {
driverclassname = "COM.ibm.db2.jdbc.net.DB2Driver";
dbprefix += "db2:";
} else
if (response.equals("3")) { //Thin Driver
driverclassname = "oracle.jdbc.driver.OracleDriver";
dbprefix += "oracle:thin:";
} else
if (response.equals("4")) { //Thick Driver
driverclassname = "oracle.jdbc.driver.OracleDriver";
dbprefix += "oracle:oci8:";
} else
if (response.equals("5")) {
driverclassname = "com.informix.jdbc.IfxDriver";
dbprefix += "informix-sqli:";
} else
if (response.equals("6")) {
driverclassname = "com.sybase.jdbc2.jdbc.SybDriver";
dbprefix += "sybase:";
} else
if (response.equals("7")) {
driverclassname = "COM.cloudscape.core.JDBCDriver";
dbprefix += "cloudscape:";
} else
if (response.equals("8")) {
driverclassname = "COM.cloudscape.core.RmiJdbcDriver";
dbprefix += "cloudscape:rmi:";
} else
if (response.equals("9")) {
driverclassname = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
dbprefix += "microsoft:sqlserver:";
} else
if (response.equals("10")) {
// driverclassname = "com.merant.sequelink.jdbcx.datasource.SequeLinkDataSource";
driverclassname = "com.ddtek.jdbcx.sequelink.SequeLinkDataSource";

dbprefix += "sequelink:";
} else
if (response.equals("11")) {
driverclassname = "com.ibm.websphere.jdbcx.sqlserver.SQLServerDataSource";
dbprefix += "sequelink:";
} else
if (response.equals("12")) {
driverclassname = "com.ddtek.jdbcx.sqlserver.SQLServerDataSource";
dbprefix += "sequelink:";
} else
System.out.println("Invalid selection: specify an option 1-12.");
}


System.out.println("Loading jdbc driver: " + driverclassname);
try {
if (Integer.parseInt(response) < DATASOURCECONNECTIONS)
{
Class.forName(driverclassname);
System.out.println(driverclassname + " was loaded successfully");
}
else
{loader = Thread.currentThread().getContextClassLoader();
if (loader == null)
loader = ClassLoader.getSystemClassLoader();

dsClass=loader.loadClass(driverclassname);
}

} catch (Exception e) {
e.printStackTrace();
System.out.println(
"Please modify you classpath to include the class: " + driverclassname);

System.out.println(
"To be sure that you have this class in your classpath, issue:\n javap "
+ driverclassname);
System.exit(33);
}

}

public void connect() {
while ((DBURL == null) && (Integer.parseInt(response) < DATASOURCECONNECTIONS)) {
System.out.println("Please enter connection URL info, e.g:");

if (driverclassname.endsWith(".app.DB2Driver")) {
System.out.println("jdbc:db2:dbname or dbname");
} else
if (driverclassname.endsWith(".net.DB2Driver")) {
System.out.println(
"jdbc:db2://:/ or //:/");
} else
if (driverclassname.endsWith(".OracleDriver")) {

if (response.equals("4")) {
System.out.println(
"jdbc:oracle:oci8:@:: or @::");
} else {
System.out.println(
"jdbc:oracle:thin:@:: or @::");
}

} else
if (driverclassname.endsWith(".IfxDriver"))
System.out.println(
"jdbc:informix-sqli://:/:INFORMIXSERVER=");
else
if (driverclassname.endsWith(".SybDriver"))
System.out.println("jdbc:sybase:::/");

else
if (driverclassname.endsWith(".SQLServerDriver"))
System.out.println("jdbc:microsoft:sqlserver://:;DatabaseName=");
else
if (driverclassname.endsWith(".JDBCDriver"))
System.out.println("jdbc:cloudscape:;create=");
else
if (driverclassname.endsWith(".RmiJdbcDriver"))
System.out.println("jdbc:cloudscape:rmi://:/ or //:
port>/
if (!(driverclassname.endsWith("SequeLinkDriver")))
DBURL = readLine();
else
DBURL = "";
}

if (DBURL==null) DBURL="";

if (!DBURL.startsWith(dbprefix))
DBURL = dbprefix + DBURL;


String userid = null;
{
if (Integer.parseInt(response) < 10)
System.out.println("Please enter userid for connection to " + DBURL);
else if (Integer.parseInt(response) < 13)
System.out.println("Please enter userid for connection to Microsoft SQL Server:");
userid = readLine();
System.out.println("userid is: '" + userid + "'");
}
String password = null;
if (userid != null && !userid.equals("")) {
System.out.println(
"Please enter password "
+ " =====> WARNING: PASSWORD NOT HIDDEN <====== ");
System.out.println(
"enter 'gui' instead of you password for a secure GUI prompt)");
password = readLine();
if (password.equalsIgnoreCase("gui"))
password = getPassword(userid);
}

globaluid = userid;
globalpwd = password;

try {

//per L3, DataSource approach is used with WS 4.x, so let's do it the same way
if (Integer.parseInt(response) >= DATASOURCECONNECTIONS) {
con = this.getDataSourceConnection(userid, password);
} else { //non-SQLServer

if (userid == null || userid.equals("")) {
long start = System.currentTimeMillis();
con = DriverManager.getConnection(DBURL);
operationTimer = System.currentTimeMillis() - start;
} else {
long start = System.currentTimeMillis();
con = DriverManager.getConnection(DBURL, userid, password);
operationTimer = System.currentTimeMillis() - start;
}

}
} catch (SQLException se) {
se.printStackTrace();
System.out.println("Error code is: " + se.getErrorCode());
System.out.println("SQLState is: " + se.getSQLState());
// See if we can help the user with diagnosing the problem:
boolean network_connect_problem = false;

if (driverclassname.equals("oracle.jdbc.driver.OracleDriver")) {
if ((se.getSQLState() == null) && (se.getErrorCode() == 17002)) {
System.out.println("Connection to the Oracle server failed.\n");
System.out.println(
"Unable to connect to @hostname:port specified in the DB URL.");
network_connect_problem = true;
}
}

if (driverclassname.equals("COM.ibm.db2.jdbc.net.DB2Driver")) {
if ((se.getSQLState() == "08S01") && (se.getErrorCode() == -99999)) {
System.out.println("Connection to the DB2 server failed.\n");
System.out.println(
"Unable to connect to //hostname:port specified in the DB URL.");
System.out.println(
"Verify that db2jstrt is running on the target host with the specified port as a
parameter...");
network_connect_problem = true;
}
}

if (network_connect_problem) {
System.out.println(
"Verify that the host and port that you are connecting to are correct.");
System.out.println(
"Also verify that the host you are connecting to is listening on the specified port.");
System.out.println("Hint: use telnet hostname port.");
System.out.println(
"\tIf you get connection refused then the host is not listening on the specified port.");
System.out.println(
"\tIf telnet simply hangs then the host is listening on the port.");
System.out.println();
}

} // End catch connect exception

}

private Connection getDataSourceConnection(String userid, String password) {
PooledConnection pooledConn = null;
Connection conn = null;


try {
/*loader = Thread.currentThread().getContextClassLoader();
if (loader == null)
loader = ClassLoader.getSystemClassLoader();

if (response.equals("10"))
dsClass =
loader.loadClass("com.merant.sequelink.jdbcx.datasource.SequeLinkDataSource");

else if (response.equals("11"))
dsClass =
loader.loadClass("com.ibm.websphere.jdbcx.sqlserver.SQLServerDataSource");

dsClass=loader.loadClass(driverclassname);

*/

ds = (ConnectionPoolDataSource) (dsClass.newInstance());

System.out.println("enter database name:");
dbname = readLine();

dsClass.getMethod("setDatabaseName", new Class[] { String.class }).invoke(
ds,
new Object[] { dbname });

System.out.println("enter port number:");
dbport = readLine();

dsClass.getMethod("setPortNumber", new Class[] { int.class }).invoke(
ds,
new Object[] { new Integer(dbport)});

System.out.println("enter server name:");
dbhostname = readLine();

dsClass.getMethod("setServerName", new Class[] { String.class }).invoke(
ds,
new Object[] { dbhostname });

dsClass.getMethod("setUser", new Class[] { String.class }).invoke(
ds,
new Object[] { userid });

dsClass.getMethod("setPassword", new Class[] { String.class }).invoke(
ds,
new Object[] { password });

long start = System.currentTimeMillis();
pooledConn = ds.getPooledConnection();
conn = pooledConn.getConnection();
operationTimer = System.currentTimeMillis() - start;

// Any use of the Connection must be done AFTER the unlock, or else it will fail
// with a license verification error.

} catch (SQLException se) {
se.printStackTrace();
System.out.println("Error code is: " + se.getErrorCode());
System.out.println("SQLState is: " + se.getSQLState());
// See if we can help the user with diagnosing the problem:

System.out.println(
"Verify that the host and port that you are connecting to are correct.");
System.out.println(
"Also verify that the host you are connecting to is listening on the specified port.");
System.out.println("Hint: use telnet hostname port.");
System.out.println(
"\tIf you get connection refused then the host is not listening on the specified port.");
System.out.println(
"\tIf telnet simply hangs then the host is listening on the port.");
// System.out.println();

return (null);

} // End catch connect exception

catch (Throwable th) {
th.printStackTrace();
return (null);
} finally {
// if (conn != null) try { conn.close(); } catch (Throwable th) {}
// if (pooledConn != null) try { pooledConn.close(); } catch (Throwable th) {}

}

return (conn);

}


private Connection getDataSourceConnection() {
PooledConnection pooledConn = null;
Connection conn = null;

System.out.println("getting data source connection...");


try {

long start = System.currentTimeMillis();
pooledConn = ds.getPooledConnection();
conn = pooledConn.getConnection();
operationTimer = System.currentTimeMillis() - start;

// Any use of the Connection must be done AFTER the unlock, or else it will fail
// with a license verification error.

} catch (SQLException se) {
se.printStackTrace();
System.out.println("Error code is: " + se.getErrorCode());
System.out.println("SQLState is: " + se.getSQLState());
// See if we can help the user with diagnosing the problem:

System.out.println(
"Verify that the host and port that you are connecting to are correct.");
System.out.println(
"Also verify that the host you are connecting to is listening on the specified port.");
System.out.println("Hint: use telnet hostname port.");
System.out.println(
"\tIf you get connection refused then the host is not listening on the specified port.");
System.out.println(
"\tIf telnet simply hangs then the host is listening on the port.");
// System.out.println();

return (null);

} // End catch connect exception

catch (Throwable th) {
th.printStackTrace();
return (null);
} finally {
// if (conn != null) try { conn.close(); } catch (Throwable th) {}
// if (pooledConn != null) try { pooledConn.close(); } catch (Throwable th) {}

}

return (conn);

}



public String readLine() {
String response = null;
try {
response = instream.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}

public boolean process() {

String instring = null;
if (!(response.equals("11")) && !(response.equals("10")))
{
while (instring == null) {
System.out.println(
"Please enter sql statement to execute...(q to quit)\n(or maxconn to test maximum connections
possible to this database)");
instring = readLine();
if (instring.equals("q")) {
System.out.println("Ok, quitting!");
return false;
} else
if (instring.equals("maxconn")) {
System.out.println("testing for maximum connections...");
maxconn();
return true;
}

}

}

else //special case with DataDirect driver, test connect only

{
while ((instring == null) || (!instring.equals("q")) && (!instring.equals("maxconn"))) {
System.out.println(
"Please enter q to quit\n(or maxconn to test maximum connections possible to this database)");
instring = readLine();

}

if (instring.equals("maxconn")) {
System.out.println("testing for maximum connections...");
maxconn();
return true;
}

else
if (instring.equals("q")) {
System.out.println("Ok, quitting!");
return false; }

else System.out.println("Jdbctest only supports connection testing for this driver.");


}

boolean rc = false;
try {
long start = System.currentTimeMillis();
rc = stmt.execute(instring);
operationTimer = System.currentTimeMillis() - start;
} catch (Exception e) {
e.printStackTrace();
}

System.out.println(
"Operation took " + operationTimer + " milliseconds to complete");
ResultSet rs = null;

System.out.println(
"Just tried " + rc + " = stmt.execute(\"" + instring + "\");");

if (rc) {
try {
System.out.println("Getting result set...");
rs = stmt.getResultSet();
ResultSetMetaData rsm = rs.getMetaData();
// Display names of columns fetched
int colcount = rsm.getColumnCount();
System.out.println(colcount + " column(s) in result");
int[] coltype = new int[colcount + 1]; // Do not slot 0
for (int i = 1; i < colcount + 1; i++) {
System.out.print(rsm.getColumnName(i) + " ");
coltype[i] = rsm.getColumnType(i);
}

System.out.println();
System.out.println("-----------------------------------");

while (rs.next()) {
for (int j = 1; j < colcount + 1; j++) {
if (j != 1)
System.out.print(",");
switch (coltype[j]) {
case Types.TINYINT :
System.out.print("" + rs.getShort(j));
break;

case Types.SMALLINT :
System.out.print("" + rs.getShort(j));
break;

case Types.INTEGER :
System.out.print("" + rs.getInt(j));
break;

case Types.BIGINT :
System.out.print("" + rs.getLong(j));
break;

case Types.FLOAT :
System.out.print("" + rs.getFloat(j));
break;

case Types.REAL :
System.out.print("" + rs.getDouble(j));
break;

case Types.DOUBLE :
System.out.print("" + rs.getDouble(j));
break;

case Types.NUMERIC :
System.out.print("" + rs.getInt(j));
break;

case Types.DECIMAL :
System.out.print("" + rs.getInt(j));
break;

case Types.CHAR :
// System.out.print(""+rs.getByte(j));
System.out.print("" + rs.getString(j));
break;

case Types.VARCHAR :
System.out.print("" + rs.getString(j));
break;

case Types.LONGVARCHAR :
System.out.print("" + rs.getString(j));
break;

case Types.DATE :
System.out.print("" + rs.getDate(j));
break;

case Types.TIME :
System.out.print("" + rs.getTime(j));
break;

case Types.TIMESTAMP :
System.out.print("" + rs.getTimestamp(j));
break;

case Types.BINARY :
case Types.BIT :
case Types.VARBINARY :
case Types.LONGVARBINARY :
byte b[] = rs.getBytes(j);
for (int n = 0; n < b.length; n++)
System.out.print("" + b[n] + "|");
break;

case Types.NULL :
System.out.print("-");
break;

case Types.OTHER :
System.out.print("OTHER");
break;

default :
System.out.print("UNKNOWN-TYPE");
}
}
System.out.println();

}
System.out.println();

rs.close();
} catch (SQLException se) {
se.printStackTrace();
System.out.println("Error code is: " + se.getErrorCode());
System.out.println("SQLState is: " + se.getSQLState());
}
}

return true;

}

String getPassword(String userid) {
Frame f;
Panel p;
Label l;
TextField tf;

// Create the frame
f = new Frame("Password Prompt for JDBC tester");
f.setLocation(400, 400);
f.setSize(350, 100);
// Reister ourselves for 'Close' events
f.addWindowListener(new FrameCloser());

// Create the panel
p = new Panel();
f.add(p, "Center");
l = new Label("Please enter password for Data Base user: " + userid);
tf = new TextField(20);
tf.setEchoChar('*');
p.add(l, "Center");
p.add(tf, "Center");
try {
f.show();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(
"Your ===> DISPLAY <=== Environment Variable is not exported properly. Please correct and retry.");
}

try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
f.show();
tf.requestFocus();
tf.addKeyListener(new KeyInterceptor());

// System.out.println("Waiting for password to be entered...");

synchronized (tf) {
try {
tf.wait();
} catch (InterruptedException e) {
}
}
String password = tf.getText();
f.transferFocus();
f.dispose();
return password;
}

public void maxconn() {

Connection c[] = new Connection[125];

System.out.println("1 connection assumed...looping...");

int i;

for (i = 0; i < 125; i++)
try {
if (globaluid == null || globaluid.equals("")) {

if (Integer.parseInt(response) < DATASOURCECONNECTIONS)
{
long start = System.currentTimeMillis();
c[i] = DriverManager.getConnection(DBURL);
operationTimer = System.currentTimeMillis() - start;
}
else c[i]= getDataSourceConnection();
} else {
if (Integer.parseInt(response) < DATASOURCECONNECTIONS)
{

long start = System.currentTimeMillis();
c[i] = DriverManager.getConnection(DBURL, globaluid, globalpwd);
operationTimer = System.currentTimeMillis() - start;
}

else c[i]= getDataSourceConnection();

}

System.out.println("Connection Successful: " + c[i]);
System.out.println(
"Connection "
+ (i + 2)
+ " took "
+ operationTimer
+ " milliseconds to complete");
} catch (SQLException se) {
se.printStackTrace();
System.out.println("Error code is: " + se.getErrorCode());
System.out.println("SQLState is: " + se.getSQLState());
i--;
break;
}

catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
i--;
break;
}

System.out.println(
"Maximum connections to DB:" + DBURL + " is " + (i + 2) + ".");
System.out.println("closing all connections except initial connection...");

for (i = 0; i < 125; i++)
if (c[i] != null)
try {
c[i].close();
System.out.print(".");
} catch (SQLException se2) {
se2.printStackTrace();
System.out.println("Error code is: " + se2.getErrorCode());
System.out.println("SQLState is: " + se2.getSQLState());
}
System.out.println("Done!");

}

}

Java Programming Style Guidelines

Java Programming Style Guidelines:

  • Files
    Java source files should have the extension .java.
    Point.java
    Enforced by the Java tools.
  • File content must be kept within 80 columns.
  • Special characters like TAB and page break must be avoided.
  • The package statement must be the first statement of the file. All files should belong to a specific package.

  • Imported classes should always be listed explicitly.
    import java.util.List; // NOT: import java.util.*; import java.util.ArrayList; import java.util.HashSet;
  • Class and Interface declarations should be organized in the following manner:
    Class/Interface documentation.
    class or interface statement.
    Class (static) variables in the order public, protected, package (no access modifier), private.
    Instance variables in the order public, protected, package (no access modifier), private.
    Constructors.
    Methods (no specific order).
  • Class variables should never be declared public.
  • Variables must never have dual meaning.
  • Arrays should be declared with their brackets next to the type
  • Variables should be kept alive for as short a time as possible.
  • Only loop control statements must be included in the for() construction

  • Loop variables should be initialized immediately before the loop.
    isDone = false; // NOT: bool isDone = false; while (!isDone) { // : : // while (!isDone) { } // : // }
  • The use of do-while loops can be avoided.
  • The use of break and continue in loops should be avoided.