Archive for May, 2005

MySQL tinyint coverted to Java boolean

Written by coregps on Wednesday, May 25th, 2005 in MySQL.

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

I have a MySQL table with a field named “finish”, the column type is tinyint(1). When I retrieve the value of the field in my jsp page like following:

int iFinish = ((Integer)map.get(”finish”)).intValue();

I get a java.lang.ClassCastException. From the JDBC API Tutorial and Reference of Sun, I know that The JDBC type “TINYINT” is mapped to the Java type “byte”, and The JDBC type “TINYINT” is mapped to the Java Object type “Integer”.

So, I try the following code. However, I get the same exception.

byte iFinish = ((Integer)map.get(”finish”)).byteValue();

Finally, I find the root cause of the problem from MySQL Reference Manual:

TINYINT[(M)] [UNSIGNED] [ZEROFILL]

A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.

BOOL , BOOLEAN

These are synonyms for TINYINT(1). The BOOLEAN synonym was added in MySQL 4.1.0. A value of zero is considered false. Non-zero values are considered true.

In the future, full boolean type handling will be introduced in accordance with standard SQL.

When I change my code like following,

boolean bFinish = ((Boolean)map.get(”finish”)).booleanValue();

Or change the field width to 2 (greater than 1), and use the code below:

byte iFinish = ((Integer)map.get(”finish”)).byteValue();

My jsp page works fine.

Changing select Element Content using XMLHTTP object

Written by coregps on Tuesday, May 24th, 2005 in AJAX.

In my recent project, I want to change the options in a select element in response to other form control settings. Data for the option elements is retrieved from database. Originally, I want to implement this using javascript dynamic array. However, there too many records will be retrieved. To reduce the number of records retrieved, I use XMLHTTP object to retrive data from database dynamically. The following is the code:



<script type=”text/javascript”>
function getCities() {
    var countryid = thisForm.countryid.value;
   
    // Create an instance of the XML HTTP Request object
    var xmlHttp = new ActiveXObject( “Microsoft.XMLHTTP” );
 
    // Prepare the XMLHTTP object for a HTTP POST
    var sURL = “search.jsp?countryid=” + countryid;
    xmlHttp.open( “POST”, sURL, false );


    // Execute the request
    xmlHttp.send(null);
   
    // responseText contains HTML code of select element
    cityContainer.innerHTML = xmlHttp.responseText;
   
    // delete XML HTTP Request object
    delete xmlHttp;
}
</script>



<select name=”countryid” style=”width:20%” onchange=”getCities()”>
    <option value=”1″>America</option>
    <option value=”2″>England</option>
    …
</select>


<div id=”cityContainer”">
   <select name=”cityid” style=”width: 20%”></select>
</div>


In my jsp page, I construct the HTML source code of the city select element using results retrieved from database.



<%@ page import=”java.util.*”%>
<jsp:useBean id=”city” class=”com.esurfer.DemoApp.City”/>
<select name=”cityid” style=”width: 20%”>
<%
int countryid = 0;
String sCountryId = request.getParameter(”countryid”);
if (sCountryId != null) {
    countryid = Integer.parseInt(sCountryId);
}
city.setCountryid(countryid);
Iterator iterCities = city.getCities().iterator();
while (iterCities.hasNext()) {
    Map map = (Map)iterCities.next();%>
    <option value=”<%=map.get(”cityid”)%>”><%=map.get(”cityname”)%></option><%
}
%>
</select>

Java Plug-in Fatal Error

Written by coregps on Sunday, May 22nd, 2005 in Java.

Today, When I visited a java applet in IE, I got the following error:

Java Plug-in Fatal Error:

The Java Runtime Environment cannot be loaded from <\bin\server\jvm.dll>

I visited the applet in FireFox, the same error. I tried to reinstall JDK and JRE many times, but has no effect. Finally, I found the solution from a Japanese friend’s blog. Just delete the following directory:

C:\Documents and Settings\<user name>\Application Data\Sun

After deleting the directory, the Java Plug-in works again.

WYSIWYG HTML Editors

Written by coregps on Friday, May 20th, 2005 in Web Design.

TinyMCE

TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor control released as Open Source under LGPL by Moxiecode Systems AB. It has the ability to convert HTML TEXTAREA fields or other HTML elements to editor instances. TinyMCE is very easy to integrate into other CMS systems.

FCKeditor

This HTML text editor brings to the web many of the powerful functionalities of known desktop editors like Word. It’s really lightweight and doesn’t require any kind of installation on the client computer. As it is Open Source, you are allowed to use it for free wherever you want.

XStandard

XStandard is the leading standards-compliant plug-in WYSIWYG editor for Windows desktop applications and browser-based content management systems (IE/Mozilla/Firefox). The editor generates clean XHTML Strict or 1.1, uses CSS for formatting, and ensures the clean separation of content from presentation.
Markup generated by XStandard meets the most demanding accessibility requirements.
XStandard Lite is free for use in commercial applications.

Developing with Maven

Written by coregps on Wednesday, May 18th, 2005 in Java.

 Developing with Maven by Rob Herbst — By knowing what developers want in a build tool, Maven hopes to unseat Ant as the favorite build tool of Java developers. Rob Herbst looks at Maven’s most compelling features.

Color, Contrast & Dimension in News Design

Written by coregps on Wednesday, May 18th, 2005 in General.

Color, Contrast & Dimension in News Design by Pegie Stark Adam — An online guide that explains color theory and shows how to use it in design through examples and exercises.

Best Practices for Exception Handling

Written by coregps on Wednesday, May 18th, 2005 in Java.

 Best Practices for Exception Handling by Gunjan Doshi — Java’s concept of exceptions and how they’re used has led to controversy and, in some cases, bad programming practices. Gunjan Doshi seeks to lay down some best practices for using exceptions in Java.

Top 15 Ant Best Practices

Written by coregps on Wednesday, May 18th, 2005 in Java.

 Top 15 Ant Best Practices by Eric M. Burke — Nearly every open source Java project now uses Ant. The widespread use of Ant in these projects has naturally led to an increased need for a set of well-established best practices. Eric M. Burke, coauthor of Java Extreme Programming Cookbook and Ant: The Definitive Guide, offers his 15 best practices for using Ant and for writing well-crafted Ant buildfiles. These tips were inspired by his own mistakes on previous projects, or from horror stories relayed to him from other developers.

Eclipse Plugins Exposed, Part 2: Simple GUI Elements

Written by coregps on Wednesday, May 18th, 2005 in Java.

Eclipse Plugins Exposed, Part 2: Simple GUI Elements by Emmanuel Proulx — Eclipse is largely composed of plugins, but you can’t just write any arbitrary code and have Eclipse magically incorporate it. In part two of his series on Eclipse, Emmanuel Proulx introduces Eclipse’s “extension points” by showing how to create toolbar buttons, menu items, and dialogs.

Too many connections

Written by coregps on Wednesday, May 18th, 2005 in Java, MySQL.

This problem drives me mad. MySQL gives me “Too many connections” error again :(

At the very start, I use connection pool with MySQL in my web project. And the environment of web server is configured by myself. I can configure Tomcat connection pool and set the maximum number connections of MySQL. The following is the code used to fetch a connection from connection pool:

public class DBConn {
    public static Connection getConnection() {
     Connection conn = null;
     try {
            Context initCtx = new InitialContext();
            DataSource ds =(DataSource)initCtx.lookup(”java:comp/env/jdbc/TestDB”);
            // or
            // Context envContext = (Context)initCtx.lookup(”java:comp/env”);
            // DataSource ds = (DataSource) envContext.lookup(”jdbc/TestDB”);
            try {
                conn = ds.getConnection();
            } catch (SQLException e1) {
                System.out.println(”Get Connection Failed!”);
            }
        } catch (NamingException e) {
            System.out.println(”Get Connection Failed!”);
        }
     return conn;
 }
}

It works fine. However, our customer changed a new ISP. The web server can not be configured and does not support connection pool. So, I have to change the code used to get a connection like this:

public class DBConn {
    private static String dbUserName = “root”;
 private static String dbPassword = “secret”;
 private static String connectionURL = “jdbc:mysql://localhost:3306/demodb?autoReconnect=true”;
 private static String driverName = “com.mysql.jdbc.Driver”;
    public static Connection getConnection() {
     Connection conn = null;
     try {
         Class.forName(driverName).newInstance(); //Load Database Driver
         conn = DriverManager.getConnection(connectionURL, dbUserName, dbPassword);
        } catch (Exception e) {
            System.out.println(”Get Connection Failed!”);
        }
     return conn;
 }
}

And the following code is used to retrieve data from MySQL database and put them into Vector.

public Vector getUserInfo() {
    Vector vector = new Vector();
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
 String sql = “SELECT userid, username FROM userinfo;
 try {
        conn = DBConn.getConnection();
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            UserInfo user = new UserInfo();
            user.setUserId(rs.getInt(1));
            user.setUserName(rs.getString(2));
            vector.add(user);
        }
       
        rs.close();
        rs = null;
       
        stmt.close();
        stmt = null;
       
        conn.close();
        conn = null;
    } catch (Exception e) {
        System.out.println(”Fetch Record(s) Error!”);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                System.out.println(”Cannot close ResultSet” + e);
            }
            rs = null;
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                System.out.println(”Cannot close Statement” + e);
            }
            stmt = null;
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println(”Cannot close Connection” + e);
            }
            conn = null;
        }
    }
 return vector;
}

As you can see, I do close all the resources. But I get the “Too many connections” error message again. Even I can not connect to MySQL using phpMyAdmin. I want to implement my own connection pool. Any suggestions will be appreciated.

FREE book on Struts Best Practices

Written by coregps on Wednesday, May 18th, 2005 in Java.

Today I found an entry about this book on JavaLobby. In this book, you will learn

  • The basics and strengths of Struts
  • How to fill the gaps in Struts
  • Which features are important for J2EE projects.
  • Develop professional Struts code by adopting proven strategies
  • How to handle exceptions in production Struts applications in the BEST way
  • Real practical benefits of customizing Struts
  • Best Practices and Strategies in Struts

Download this free book, example source code and slides from Struts Training at here.

Wirting Your Web Application with Open Source Java

Written by coregps on Wednesday, May 18th, 2005 in Java.

Wiring Your Web Application with Open Source Java by Mark Eagle — Building a web application with Java can be a complex process when architecting a combination of UI, business logic, and persistence. This article introduces a way to leverage open source software to lessen the burden.

Get absolute path to “WEB-INF/classes”

Written by coregps on Wednesday, May 18th, 2005 in Java.

The following function can be used to find the absolute path to a file in the WEB-INF/classes directory:

public static File getFileFromInputStream(String fileName) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL url = cl.getResource(fileName);
if (url != null) {
File file = new File(url.getFile());
return file;
} else {
return null;
}
}

You can use it just pass over the name of the file.

Proxool in practice

Written by coregps on Wednesday, May 18th, 2005 in Java.

What is Proxool?

Proxool is an open source Java connection pool, which can add connection pooling to your existing JDBC driver transparently. It is very easy to configure, and you can migrate your code in a walk.

Download

For the most up-to-date version, go to the Proxool download site. As of this date, the current version is Proxool 0.8.3. Download the Proxool zip file to your local machine.

Install

Unzip the proxool-0.8.3.zip file to a directory, You will find proxool-0.8.3.jar in the lib directory. Copy it to your web application’s WEB-INF/lib directory.

Configuration

For ease of changing the database parameters, I will configure the pools by using an XML file or a properties file.

First, I will explain the solution using an XML file. This can be achieved by the following steps:

1. Create an XML file named proxool.xml (you can name it whatever you like), like following:

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<proxool>
    <alias>myPool</alias>
    <driver-url>jdbc:mysql://localhost:3306/demodb</driver-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <driver-properties>
      <property name=”user” value=”root”/>
      <property name=”password” value=”secret”/>
    </driver-properties>
    <test-before-use>true</test-before-use>
    <maximum-connection-lifetime>60000</maximum-connection-lifetime>
    <prototype-count>5</prototype-count> 
    <maximum-connection-count>50</maximum-connection-count>
    <house-keeping-test-sql>select CURRENT_DATE</house-keeping-test-sql>
</proxool>

2. Configure the pools at startup by adding the following lines in web.xml:

<servlet>
  <servlet-name>ServletConfigurator</servlet-name>
  <servlet-class>org.logicalcobwebs.proxool.configuration.ServletConfigurator</servlet-class>
  <init-param>
    <param-name>xmlFile</param-name>
    <param-value>WEB-INF/proxool.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>

Note that when using this solution, you must download a JAXP compliant XML parser. Here I will use Xerces, download the zip file, unzip it and put all jar files into your web application’s WEB-INF/lib directory.

Another solution I will explain is using a properties file. This can be done also in two steps:

1. Create a propreties file named proxool.properties (you can name it whatever you like), like following:

jdbc-0.proxool.alias=myPool
jdbc-0.proxool.driver-class=com.mysql.jdbc.Driver
jdbc-0.proxool.driver-url=jdbc:mysql://localhost:3306/demodb
jdbc-0.user=root
jdbc-0.password=secret

jdbc-0.proxool.maximum-connection-count=40
jdbc-0.proxool.prototype-count=4

jdbc-0.proxool.house-keeping-test-sql=select CURRENT_DATE
jdbc-0.proxool.verbose=true
jdbc-0.proxool.statistics=10s,1m,1d
jdbc-0.proxool.statistics-log-level=DEBUG

2. Configure the pools at startup by adding the following lines in web.xml:

<servlet>
  <servlet-name>ServletConfigurator</servlet-name>
  <servlet-class>org.logicalcobwebs.proxool.configuration.ServletConfigurator</servlet-class>
  <init-param>
    <param-name>propertyFile</param-name>
    <param-value>WEB-INF/proxool.properties</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet> 

Using

Once you’ve done the steps above, restart Tomcat. And now we can pick up a connection by using the alias configured above. The following is a Java Bean used to retrieve a connection from the connection pool.

package com.esurfer.common;

import java.sql.*;

public class DBConn {
    public static Connection getConnection() {
       Connection conn = null;
       try {
            conn = DriverManager.getConnection(”proxool.myPool”);
       } catch (Exception e) {
            System.out.println(”Get Connection Failed!” + e);
       }
      return conn;
    }
}

We can use the connection object retrieved to create statements, like following:

Connection conn = DBConn.getConnection();
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

Lesson

Be sure not to lost the the following line when you configure your servlet.

<load-on-startup>1</load-on-startup>

If you lost it, you will get error message something like java.sql.SQLException: No suitable driver. It seems that Proxool itself can’t find the driver.

For the full list of all the properties, visit http://proxool.sourceforge.net/properties.html.
For more information about Proxool, visit http://proxool.sourceforge.net/index.html.

Scroll table with the header and the left most column fixed

Written by coregps on Wednesday, May 18th, 2005 in Web Design.

I came across some trouble recently when using table to display data retrieved from database. I would like to be able to make the header and the left most column of my table fixed when doing vertical scrolling and horizontal scrolling. I’ve found an excellent solution to this problem. If you meet the same trouble, you can visit http://web.tampabay.rr.com/bmerkey/examples/locked-column-csv.html.


BTW, It works only in IE.

Store ResultSet in ArrayList or Vector

Written by coregps on Wednesday, May 18th, 2005 in Java.

Recently, I am hesitant about using Vector or Arraylist to store ResultSet. Which one is better, I have no idea. Today, I found an article  Vector or ArrayList — which is better? on javaworld.com. Here is some snippet of it:

Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It’s always best to set the object’s initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don’t know how much data you’ll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.

After reading this article, I made a test. And the following is my environment:

  • Windows 2000 Server
  • Tomcat 5.5.7 with connection pool configured
  • SQL Server 2000
  • JDK 5.0

In my SQL Server database, there is a table named “z_pz01″, It contains 497 records. To make this test, I created a Java Bean which contains four methods used to retrieve data from database. Like this:

package com.esurfer.common;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;

import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class DBConn {
    public static Connection getConnection() {
        Connection conn = null;
        try {
               Context initCtx = new InitialContext();
               DataSource ds =(DataSource)initCtx.lookup(”java:comp/env/jdbc/myDB”);
               try {
                   conn = ds.getConnection();
               } catch (SQLException e1) {
                   System.out.println(”Get Connection Failed!” + e1);
               }
           } catch (NamingException e) {
               System.out.println(”Get Connection Failed!” + e);
           }
        return conn;
    }
   
    public static ArrayList searchA(String sql) {
        ArrayList result = null;
        Connection conn  = null;
        Statement stmt   = null;
        ResultSet rs     = null;
        try {
            // Fetch a connection from pool
            conn = getConnection();
           
            // Create a scrollable result set
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            rs = stmt.executeQuery(sql);
           
            // Move to the end of the result set
            rs.last();
           
            // Get the row number of the last row which is also the row count
            int rowCount = rs.getRow();
           
            rs.beforeFirst();
            if (rowCount != 0) {
                result = new ArrayList(rowCount);
                ResultSetMetaData rsmd = rs.getMetaData();
                int cols = rsmd.getColumnCount();
                int iIndex = 0;
                while (rs.next()) {
                    Hashtable ht = new Hashtable();
                 for (int i = 1; i <= cols; i++) {
                     String sTemp = rs.getString(i);
                     if (sTemp == null) sTemp = “”;
                     sTemp = sTemp.trim();
                     ht.put(rsmd.getColumnName(i), sTemp);
                 }
                 result.add(iIndex, ht);
                 iIndex++;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                stmt = null;
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                conn = null;
            }
        }
        return result;
    }
   
    public static ArrayList searchA1(String sql) {
        ArrayList result = new ArrayList();
        Connection conn  = null;
        Statement stmt   = null;
        ResultSet rs     = null;
        try {
            // Fetch a connection from pool
            conn = getConnection();
           
            // Create a scrollable result set
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            rs = stmt.executeQuery(sql);
           
            ResultSetMetaData rsmd = rs.getMetaData();
            int cols = rsmd.getColumnCount();
            //int iIndex = 0;
            while (rs.next()) {
                Hashtable ht = new Hashtable();
                for (int i = 1; i <= cols; i++) {
                    String sTemp = rs.getString(i);
                    if (sTemp == null) sTemp = “”;
                    sTemp = sTemp.trim();
                    ht.put(rsmd.getColumnName(i), sTemp);
                }
                result.add(ht);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                stmt = null;
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                conn = null;
            }
        }
        return result;
    }
   
    public static Vector searchV(String sql) {
        Vector result = null;
        Connection conn  = null;
        Statement stmt   = null;
        ResultSet rs     = null;
        try {
            // Fetch a connection from pool
            conn = getConnection();
           
            // Create a scrollable result set
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            rs = stmt.executeQuery(sql);
           
            // Move to the end of the result set
            rs.last();
           
            // Get the row number of the last row which is also the row count
            int rowCount = rs.getRow();
           
            rs.beforeFirst();
            if (rowCount != 0) {
                result = new Vector(rowCount);
                ResultSetMetaData rsmd = rs.getMetaData();
                int cols = rsmd.getColumnCount();
                int iIndex = 0;
                while (rs.next()) {
                    Hashtable ht = new Hashtable();
                 for (int i = 1; i <= cols; i++) {
                     String sTemp = rs.getString(i);
                     if (sTemp == null) sTemp = “”;
                     sTemp = sTemp.trim();
                     ht.put(rsmd.getColumnName(i), sTemp);
                 }
                 result.add(iIndex, ht);
                 iIndex++;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                stmt = null;
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                conn = null;
            }
        }
        return result;
    }
   
    public static Vector searchV1(String sql) {
        Vector result = new Vector();
        Connection conn  = null;
        Statement stmt   = null;
        ResultSet rs     = null;
        try {
            // Fetch a connection from pool
            conn = getConnection();
           
            // Create a scrollable result set
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            rs = stmt.executeQuery(sql);
           
            ResultSetMetaData rsmd = rs.getMetaData();
            int cols = rsmd.getColumnCount();
            //int iIndex = 0;
            while (rs.next()) {
                Hashtable ht = new Hashtable();
                for (int i = 1; i <= cols; i++) {
                    String sTemp = rs.getString(i);
                    if (sTemp == null) sTemp = “”;
                    sTemp = sTemp.trim();
                    ht.put(rsmd.getColumnName(i), sTemp);
                }
                result.add(ht);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                stmt = null;
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                conn = null;
            }
        }
        return result;
    }
}

In my jsp pages, I executed each method 100 times and recorded the execution time.

<%@ page contentType=”text/html;charset=GBK”%>
<%@ page import= “java.util.*, com.esurfer.common.DBConn”%>
<%
System.out.println(”ArrayList with initial capacity set:”);
for (int i = 0; i < 100; i++) {
    long lBegin = System.currentTimeMillis();
    ArrayList result = DBConn.searchA(”SELECT * FROM z_pz01″);
    System.out.println(System.currentTimeMillis() - lBegin);
}
%>

<%@ page contentType=”text/html;charset=GBK”%>
<%@ page import= “java.util.*, com.esurfer.common.DBConn”%>
<%
System.out.println(”ArrayList without setting initial capacity:”);
for (int i = 0; i < 100; i++) {
    long lBegin1 = System.currentTimeMillis();
    ArrayList result1 = DBConn.searchA1(”SELECT * FROM z_pz01″);
    System.out.println(System.currentTimeMillis() - lBegin1);
}
%>

<%@ page contentType=”text/html;charset=GBK”%>
<%@ page import= “java.util.*, com.esurfer.common.DBConn”%>
<%
System.out.println(”Vector with initial capacity set:”);
for (int i = 0; i < 100; i++) {
    long lBegin = System.currentTimeMillis();
    Vector vector = DBConn.searchV(”SELECT * FROM z_pz01″);
    System.out.println(System.currentTimeMillis() - lBegin);
}
%>

<%@ page contentType=”text/html;charset=GBK”%>
<%@ page import= “java.util.*, com.esurfer.common.DBConn”%>
<%
System.out.println(”Vector without setting initial capacity:”);
for (int i = 0; i < 100; i++) {
    long lBegin = System.currentTimeMillis();
    Vector vector = DBConn.searchV1(”SELECT * FROM z_pz01″);
    System.out.println(System.currentTimeMillis() - lBegin);
}
%>

The statistic result is shown here(execution time in milliseconds):

  Set initial capacity Not Set initial capacity
ArrayList 482.4643 504.86735
Vector 493.699 481.82655

It seems that the one using Vector without setting initial capacity is the best solution. I don’t know if I’m right. Any ideas or test results will be appriciated.

How can I make such a stupid mistake!

Written by coregps on Wednesday, May 18th, 2005 in General, SQL Server.

I have a web application which works fine originally. However, today, after I modified some code, it can’t work any more. I’ve been getting the following error message:

[Microsoft][SQLServer 2000 Driver for JDBC] Error establishing socket.

I’ve tried to reinstall sql server, patch SQL server with service pack 3, even copy all databases to another sql server, but still the same. Finally, I found out the root cause of this problem. It only because my carelessness. What I’ve modified is a comment line, not the working line. Like this:

String sDBServer = “ibmserver”;
// String sDBServer = “server”;    <– I’ve modified this line, you know, it will not work for ever!

I’m going mad! It took me almost a whole day :(

FacesIDE

Written by coregps on Wednesday, May 18th, 2005 in Java.

FacesIDE is an Eclipse plugin for web application development that used JSF It requires Eclipse 3.0 (or higher), JDT, GEF and EclipseHTMLEditor. And, it recommends Sysdeo Tomcat Plugin. But it is not indispensable.

FacesIDE has the following features.

  • Add JSF supports to existing Java project.
  • Visual editing of navigation and managed-beans
  • Validate faces-config (It’s based on DTD, and also checks that JSPs and classes exist)
  • Wizards for creating JSP files
  • Preview of JSF’s JSP files
  • Code completion and validation for managed-bean names, properties and methods
  • Code completion and validation for JSF’s taglibs (It’s a function of EclipseHTMLEditor)
  • Add taglib to JSP using EclipseHTMLEditor’s tag palette

url: http://amateras.sourceforge.jp/cgi-bin/fswiki_en/wiki.cgi?page=FacesIDE

Faces Console

Written by coregps on Wednesday, May 18th, 2005 in Java.

The Faces Console is a FREE standalone Java Swing application for developing and managing JavaServer Faces-based applications. With the Faces Console you can visually edit JavaServer Faces configuration files as well as JSP Tag Library files.

native2ascii - Native-to-ASCII Converter

Written by coregps on Wednesday, May 18th, 2005 in Java.

 native2ascii - Native-to-ASCII Converter

Converts a file with native-encoded characters (characters which are non-Latin 1 and non-Unicode) to one with Unicode-encoded characters.

SYNOPSIS

native2ascii [options] [inputfile [outputfile]]

DESCRIPTION

The Java compiler and other Java tools can only process files which contain Latin-1 and/or Unicode-encoded (\udddd notation) characters. native2ascii converts files which contain other character encodings into files containing Latin-1 and/or Unicode-encoded charaters.

If outputfile is omitted, standard output is used for output. If, in addition, inputfile is omitted, standard input is used for input.

OPTIONS

-reverse

Perform the reverse operation: convert a file with Latin-1 and/or Unicode encoded characters to one with native-encoded characters.

-encoding encoding_name

Specify the encoding name which is used by the conversion procedure. The default encoding is taken from System property file.encoding. The encoding_name string must be taken from the first column of the table of supported encodings in the Supported Encodings document.

-Joption

Pass option to the Java virtual machine, where option is one of the options described on the reference page for the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes.

Example

native2ascii -encoding gb2312 messages_zh.properties messages_zh_CN.properties

Free HTML Table Generator with CSS Style Sheet

Written by coregps on Wednesday, May 18th, 2005 in Web Design.

The HTML Table CSS Style Generator allows you to tinker with different settings and allows you to see the results immediately. Using the table generator can be helpful if you know your stuff, or you are just learning about html tables, and how to use cascading style sheets to get the right look for your web pages.

For more information, see http://www.spectrum-research.com/V2/projects_table_generator.asp.

JSP Tabs Taglib

Written by coregps on Wednesday, May 18th, 2005 in Java.

The Ditchnet JSP Tabs Taglib provides an incredibly simple toolkit for adding rich, sophisticated tabbed-pane GUI components to web-based user interfaces. The Tabs Taglib combines the powerful features of DHTML, Java, and JSP to allow you to create web-based tabbed interfaces that behave in a manner remarkably similar to what you would expect from a rich client toolkit like Java Swing.

It is very easy to this Tablib. First,  Make sure that the JSTL is in your web app’s classpath. This means having jstl.jar and standard.jar on your web app’s classpath. And then download the Ditchnet JSP Tabs Taglib JAR file and put the JAR file into the WEB-INF/lib directory of your web application. Now we can use it like following:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
        “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<%@ page contentType=”text/html” %>
<%@ taglib prefix=”tab” uri=”http://ditchnet.org/jsp-tabs-taglib” %>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>

 
<head>
    <tab:tabConfig />
</head>
 
<body>
 
 
<tab:tabContainer id=”data-collect-container”>

 <tab:tabPane id=”computer” tabTitle=”Computer”>
      // some form fields here for computer
 </tab:tabPane>

 <tab:tabPane id=”software” tabTitle=”Software”>
      // some form fields here for software
 </tab:tabPane>

</tab:tabContainer>
 
</body> 
 
</html>

I decide to switch to Netbeans

Written by coregps on Wednesday, May 18th, 2005 in Java.

Eclipse becomes more and more slow. When I’m doing java development using eclipse, it always slows down the enrire machine. So, I decide to switch to Netbeans. And I find some resources about Netbeans 4.1.

The J2EE 1.4 Tutorial for NetBeans IDE 4.1:
http://www.netbeans.org/download/docs/41/j2ee-tutorial/index.html

An excellent blog about Netbeans 4.1:
http://blogs.sun.com/geertjan

The 8th J2EE programming with Passion course has already started

Written by coregps on Wednesday, May 18th, 2005 in Java.

The 8th session of the free online “J2EE programming with Passion!” course has already started from May 16th, 2005. This course will cover Web-tier programming topics, which includes MVC design pattern, Struts, and JavaServer Faces. I’ve ever participated in the 6th session of this course, but did not finish it. This time, I must catch the opportunity. I will set aside enough time to finish this course.

Check the following website for more information about the course:

http://www.javapassion.com/j2ee/



Site Navigation