A Java Bean based on Commons DbUtils
Written by coregps on Saturday, July 30th, 2005 in Java.
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!
Written by coregps on Saturday, July 30th, 2005 in Java.
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!
Written by coregps on Saturday, July 30th, 2005 in Web Design.
Many times we want to restrict user input to numbers only. The following function can be used to validate both integer and decimal values:
function numeralsOnly(currv, evt, decimal) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
((evt.which) ? evt.which : 0));
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) {
return false;
}
if (charCode == 46) {
if (decimal == 0) {
return false;
} else {
if (currv.indexOf(”.”) != -1) {
return false;
}
}
} else if (currv.indexOf(”.”) != -1) {
var s = currv.substring(currv.indexOf(”.”));
if (s.length > decimal) {
return false;
}
}
return true;
}
For ease of reuse, I save the code into a separate file named common.js. The use of the function is very easy:
First, include the common.js file by adding the following code into <head> tag:
And then use it:
// integer only
<input type=”text” name=”amount” size=”30″ maxlength=”15″ onkeypress=”return numeralsOnly(this.value, event, 0)” />
// numbers with two decimal
<input type=”text” name=”price” size=”30″ maxlength=”15″ onkeypress=”return numeralsOnly(this.value, event, 2)” />
Written by coregps on Friday, July 29th, 2005 in Web Services.
WS-Security in the Enterprise, Part 1: Problem Introduction by Denis Pilipchuk — WS-Security doesn’t exist in a vacuum–in an enterprise, it must work with many other systems, which means dealing with other access control systems and potential incompatibilities. Denis Pilupchuk begins his series on integrating WS-Security and enterprise systems by spelling out where the problem lies and what pieces need to be created to resolve it.
WS-Security in the Enterprise, Part 2: The Framework by Denis Pilipchuk — Denis Pilupchuk continues his series on developing a WS-Security toolkit by developing a general framework to match the needs identified in part one and by starting to map WSSE features to Java objects.
Written by coregps on Friday, July 29th, 2005 in General.
Today I found this words in a SQL Server forum, I found it thought-provoking. So, I decided to share it with all of you.
As is well known, the Internet gives us more and better ways to get information and learn new technologies. However, This ease of networking also makes me lazier and lazier in some extent. Many times, when I encounter some problem, I always search the answer on the net directly without thinking. Although the problem is solved I still don’t really understand. So, When I meet the same problem the next time, I can’t solve it either and just search it on the net again.
When I found this words, I’m aware that I was wrong. From now on, I decide to make good use of the internet. Thinking instead of Searching!
Written by coregps on Friday, July 29th, 2005 in Java.
Create Desktop Applications with Java-Based Web Technologies by Will Iverson — Will Iverson provides detailed, step-by-step instructions for building a simple, point-and-shoot installer for a basic web application using Apache Jakarta Tomcat and a combination of free tools and various Apache-license projects. Will is the author of Mac OS X for Java Geeks.
Written by coregps on Friday, July 29th, 2005 in General.
I’m very excited to find FreeWebs.com, which offers free web hosting services. It provides 40Mb space and offers services for both beginners and professionals. For beginners without prior expreience in web publishing, FreeWebs provides a simple but powerful online web page builder. For advanced users, you can upload you site, and then edit your pages in a flash with the WebzEdit RealTime WYSIWYG page editing. Most excited of all is speed. I’ve tested some example sites hosted on it. Very fast!
I can’t enumerate all of its top-notch services here. For more information of FreeWebs.com or sign up, please visit http://www.freewebs.com/. BTW, If you are looking for a Free Web Hosting now. Select FreeWebs.com! I’m sure that you must be very satisfied with it.
Written by coregps on Friday, July 29th, 2005 in Web Design.
I have a jsp page which contains a form and some text fields. The number of text fields and the name of these text fields are indeterminate. Because they are created dynamically according to the request parameters. BTW, there are no other types of elements. I want the user to begin typing into the first text box of the form without having to physically bring focus to the box.
This can be achieved by using the elements collection which contains all objects in a given form, and the onload event handler within the body tag to invoke the focus( ) method of the first text box, like following:
Written by coregps on Friday, July 29th, 2005 in Web Design.
When using Cascading Style Sheets or CSS as it is refered to, it is extremely important to check your document for any browser issues. I found an excellent CSS Validator. You can validate CSS by URI, or by uploading the css file, or validate CSS directly.
You can find it at http://www.searchengineforums.com/tools/validate-css/.
Written by coregps on Friday, July 29th, 2005 in General.
Most of us today have to keep track of dozens of passwords, such as for email, Yahoo Messenger, FTP, forms etc. Can you remember all of them? No matter what your answer is, I want to say I can’t. So, I often write my passwords in my note book, or use the same password over and over again for different applications or web sites for easy to remember. I know it is a bad habit.
Today, I found a free open source windows utility - Password Safe, which can be used to keep passwords securely encrypted on computers. It protects passwords with the Blowfish encryption algorithm, a fast, free alternative to DES. The program’s security has been thoroughly verified by Counterpane Labs under the supervision of Bruce Schneier, author of Applied Cryptography and creator of the Blowfish algorithm. Password Safe allows us to manage our old passwords and to easily and quickly generate, store, organize, retrieve, and use complex new passwords, using password policies that you control. Once stored, our user names and passwords are just a few clicks away. Furthermore, we can organize our passwords using our own customizable references-for example, by user ID, category, web site, or location. We can choose to store all our passwords in a single encrypted master password list (an encrypted password database), or use multiple databases to further organize our passwords (work and home, for example).
BTW, It is just 641k after setup! The latest version of Password Safe is 2.09. Download it at here.
Written by coregps on Friday, July 29th, 2005 in General.
Problem
I’m working with a file containing lines that have id, village name, water depth separated by tabs, which is exported from MapInfo Tab file. Like this:
id Village Name Depth
1 ’Zhou Zhuang’ 0.0
2 ’He Zhuang’ 4.0
3 ’Su Cun’ 4.0
4 ’Xi Ying Zhen’ 4.0
5 ’Xie Xhuang’ 4.0
6 ’Ying Zhen’ 4.0
… … …
I want to convert these lines to INSERT SQL statements by following steps:
1. Replace tabs with commas.
2. Insert the following string at the start of each line:
3. And then add the following string at the end of each line:
Here I want to add a new field named ‘areaid’.
So, The result should be something like this:
INSERT INTO village(id, name, depth, areaid) VALUES (1,’Zhou Zhuang’,0.0,2)
INSERT INTO village(id, name, depth, areaid) VALUES (2,’He Zhuang’,4.0,2)
INSERT INTO village(id, name, depth, areaid) VALUES (3,’Su Cun’,4.0,2)
INSERT INTO village(id, name, depth, areaid) VALUES (4,’Xi Ying Zhen’,4.0,2)
INSERT INTO village(id, name, depth, areaid) VALUES (5,’Xie Xhuang’,4.0,2)
INSERT INTO village(id, name, depth, areaid) VALUES (6,’Ying Zhen’,4.0,2)
However, this file contains thousands of lines!!! I do not want to press Ctrl + C and Ctrl + V thousands of times!
Solution
This can be achieved by using regular expression in UltraEdit.
1. Make sure that Unix mode is active. This can set at “Advanced” > “Configuration” > “Find” Tab.
2. Click “Search” > “Replace“, make sure that both “Regular expresssions” option and “Replace all from top of file” option are checked.
3. Do a search and replace using regular expression like this:
Search for: ^(.+)$
Replace with: INSERT INTO village(id, name, depth, areaid) VALUES (\1,2)
Written by coregps on Friday, July 29th, 2005 in Database.
HSQLDB is an open source SQL relational database engine written in Java. It has a JDBC driver and supports a rich subset of ANSI-92 SQL (BNF tree format) plus SQL 99 and 2003 enhancements. It offers a small (less than 100k in one version), fast database engine which offers both in-memory and disk-based tables. Embedded and server modes are available. Additionally, it includes tools such as a minimal web server, in-memory query and management tools (can be run as applets) and a number of demonstration examples.
Yup! This Mini and Powerful baby!! I first encountered HSQLDB is in Twister (an open source workflow engine written in Java). Now, many people on the internet are talking about it. I can’t wait any more! Download it and test it in practice!
1. Download HSQLDB at here, and unzip the file downloaded to the directory c:\hsqldb. And then add the file c:\hsqldb\lib\hsqldb.jar into CLASSPATH.
2. Create a new directory c:\databases used to save databases. Now, execute the runManager.bat file in the c:\hsqldb\demo folder. A Java applet with two windows will pop up. In the ‘Type:’ dropdown list, select ‘HSQL Database Engine Standalone’, and enter ‘jdbc:hsqldb:file:c:\databases\miniDB’ in the textbox named ‘URL’. Then press OK.
Now, create my first table.
Press Ctrl+R (or View->Refresh Tree), The new created table will appear in the “DB tree” (yellow box with a + sign in it). Insert some data:
Browse data in table:
Now create a new account for database user and drop the default user ’sa’.
Close HSQL Database Manager, and look in the c:\databases folder, the following files are created:
miniDB.lck
miniDB.log
miniDB.properties
3. Run the HSQL Database Server
Note that when using HSQLDB, the database connection <url> must start with ‘jdbc:hsqldb:’. The forms of the 1.7.2 Server database connection <url> is as this:
The following explanation of database.i and dbname.i options is extracted from HSQL documentation:
* Multiple databases can be served by each instance of the Server. The value of i is currently limited to the range 0..9, allowing up to 10 different databases. Any number is this range can be used.
* The value assigned to database.i is interpreted using the format ‘[type]spec’, where the optional type component is one of ‘file:’, ‘res:’ or ‘mem:’ and the spec component is interpreted in the context of the type component. If omitted, the type component is taken to be ‘file:’.
* The value assigned to dbname.i is taken to be the key used to look up the desired database instance and thus corresponds to the <alias> component of the HSQLDB HSQL protocol database connection url: ‘jdbc:hsqldb:hsql[s]://host[port][/<alias>]’.
* The value of database.0 is special. If dbname.0 is not specified, then this defaults to an empty string and a connection is made to database.0 path when the <alias> component of an HSQLDB HSQL protocol database connection url is omitted. If a database key/value pair is found in the properties when the main method is called, this pair is supersedes the database.0 setting
4. Test HSQLDB in JSP page.
<%@page language=”java” import=”java.sql.*”%>
<%!
Driver driver = null;
String dbURL = null;
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
Object rsValue = null;
int counter;
%>
<%
try {
driver = (Driver) Class.forName(”org.hsqldb.jdbcDriver”).newInstance();
dbURL = “jdbc:hsqldb:hsql://localhost/miniDB”;
conn = DriverManager.getConnection(dbURL, “dbuser”, “secret”);
stat = conn.createStatement();
rs = stat.executeQuery(”SELECT * FROM test”);
} catch (Exception e) {
out.print(”Unable do make connection to database”);
}
%>
<html>
<head>
<title>HSQLDB Test</title>
</head>
<body bgcolor=”#FFFFFF” text=”#000000″>
<%
if (rs.next()) {
out.println(rs.getString(1));
}
%>
</body>
</html>
<%
rs.close();
stat.close();
conn.close();
%>
Visit http://hsqldb.sourceforge.net/ for more information about HSQLDB.
Written by coregps on Friday, July 29th, 2005 in Web Design.
We often need a modal dialog box to capture user-entered values. Internet Explorer provide a window object method that creates a modal dialog box. That is window.showModalDialog(). The syntax of it is:
Where
sURL specifies the URL of the document to load and display, this parameter is required;
vArguments specifies the arguments to use when displaying the document. Use this parameter to pass a value of any type, including an array of values. The dialog box can extract the values passed by the caller from the dialogArguments property of the window object. This parameter is optional.
sFeatures specifies the window ornaments for the dialog box, using one or more of the following semicolon-delimited values:
This parameter is optional.
Scripts in the document loaded into the dialog window can access the passed arguments by reading the window.dialogArguments property. To get values back to the main window’s script from a modal dialog, assign those values to the window.returnValue property of the dialog window’s document. When the user closes the dialog window, the returned value is assigned to the variable at the left side of the expression.
The following example uses the showModalDialog method to open a modal dialog box and pass back two parameters.
testDialog.html
<html>
<head>
<title>Launch a Modal Dialog</title>
<script type=”text/javascript”>
function openDialog() {
var result = window.showModalDialog(”dialog.html”, “”,
“dialogWidth:300px; dialogHeight:201px; center:yes”);
if (result != null) {
var restoredArray = result.split(”,”);
alert(”Param1=” + restoredArray[0] + “\n” + “Param2=” + restoredArray[1]);
}
}
</script>
</head>
<body>
<input type=”button” value=”Open Dialog” onclick=”openDialog()” />
</body>
</html>
dialog.html
<html>
<head>
<title>Modal Dialog</title>
<script type=”text/javascript”>
function setParam() {
window.returnValue = param1.value + “,” + p2.value;
window.close();
}
</script>
</head>
<body>
<center>
Param1:
<select name=”param1″>
<option value=”Hello”>Hello</option>
<option value=”World”>World</option>
</select><br />
Param2:
<input type=”text” name=”p2″ value=”Hello World!”/><br />
<input type=”button” value=”OK” onclick=”setParam()”/>
</center>
</body>
</html>
Written by coregps on Friday, July 29th, 2005 in General.
My Tomcat server is usually under a large load, and goes down periodically with some error message like java.net.BindException. When I run netstat on it, I got many TCP ports in the TIME_WAIT state. After reading the articles Hurry up and TIME_WAIT and The TIME_WAIT State’s Effect on IIS Performance, I know that the server port will go into a TIME_WAIT state when the client sends the server a FIN packet. However, the server will keep the connection alive for 4 minutes. This happens to be a rather long time. As long as the server port is in TIME_WAIT state, no other connections can be made to the port. This problem can be solved by shortening the TIME_WAIT interval. Open the registry and create the following key:
Find: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
Create: TcpTimedWaitDelay
Type: REG_DWORD (DWORD Value)
Value: 30 seconds (decimal)
However, I’ve read another article which also discusses this problem, it said that if pooling is enabled, it is not necessary to adjust the TcpTimedWaitDelay setting. I do configure the connection pool on Tomcat. I have no idea if I have to adjust this setting.
Written by coregps on Friday, July 29th, 2005 in General.
Everyday, from morning to night, I put my hands on the keyboard and type and type and type and type endlessly. I’m so sick of this life without passion. I feel as if I were not a man at all, but a code machine.
I want to say: “I’m not a machine, I want freedom!”
Written by coregps on Friday, July 29th, 2005 in Java.
I’ve configured connection pool on Tomcat 5.5.7 lately. However, when I run a load test, I encountered the following error message:
After configuring the following two JVM heap size options, it works fine.
-Xms, Setting minimum heap size of the memory allocation pool. Set this value to a muliple of 1024 that is greater than 1MB. As a general rule, set minimum heap size equal to the maximum heap size to minimum garbage collections.
-Xmx, Setting maximum heap size. Set this value to a multiple of 1024 that is greater than 1MB.
My configuration is:
The default JVM heap size is 64MB.
Written by coregps on Friday, July 29th, 2005 in Java.
I’ve installed Tomcat 5.5.7, J2SE 5.0, MySQL 4.1.10 on Windows 2000. When I configured Tomcat Connection pool according to the steps described in my another entry, which is already tested on Tomcat 5.0.27, I got the following error message:
Finally, I found the solution at TheServerSide.com. It is very simple, just put all connection data inside the Resource element, instead of a ResourceParams element. Like this:
One more thing to watch out is Tomcat 5.5.7 uses
“org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory“,
instead of
“org.apache.commons.dbcp.BasicDataSourceFactory“.
For a more detail discussion of this topic, see http://www.theserverside.com/discussions/thread.tss?thread_id=25459.
Written by coregps on Friday, July 29th, 2005 in Java.
What is Connection Pooling?
Connection pooling is a technique of creating and managing a pool of connections that are ready for use by any thread that needs them.
This technique of “pooling” connections is based on the fact that most applications only need a thread to have access to a JDBC connection when they are actively processing a transaction, which usually take only milliseconds to complete. When not processing a transaction, the connection would otherwise sit idle. Instead, connection pooling allows the idle connection to be used by some other thread to do useful work.
In practice, when a thread needs to do work against a MySQL or other database with JDBC, it requests a connection from the pool. When the thread is finished using the connection, it returns it to the pool, so that it may be used by any other threads that want to use it.
When the connection is “loaned out” from the pool, it is used exclusively by the thread that requested it. From a programming point of view, it is the same as if your thread called DriverManager.getConnection() every time it needed a JDBC connection, however with connection pooling, your thread may end up using either a new, or already-existing connection.
Tomcat Connection Pooling Configuration
Tomcat provides a JNDI (Java Naming Directory Inteface, Which is a directory-like listing of resources maintained by a provider and available for lookup and access by a client) Context for each application, this allows an application to ‘lookup’ values and resources which have been configured within the server.xml and/or the web.xml file. This is how the connection pooling works, the steps taken to configure and use it are:
1. Define the resource inside the server.xml
Configure the JNDI DataSource in Tomcat by adding a declaration for your resource to $CATALINA_HOME/conf/server.xml. Like this:
<Context path=”" docBase=”" debug=”0″ reloadable=”true”>
<Logger className=”org.apache.catalina.logger.FileLogger”
prefix=”localhost_DBTest_log.” suffix=”.txt”
timestamp=”true”/>
<Resource name=”jdbc/TestDB”
auth=”Container”
type=”javax.sql.DataSource”/>
<ResourceParams name=”jdbc/TestDB”>
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!– Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to 0 for no limit.
–>
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
<!– Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
–>
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>
<!– Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
–>
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>
<!– MySQL dB username and password for dB connections –>
<parameter>
<name>username</name>
<value>dbuser</value>
</parameter>
<parameter>
<name>password</name>
<value>secret</value>
</parameter>
<!– Class name for the official MySQL Connector/J driver –>
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<!– The JDBC connection url for connecting to your MySQL dB.
The autoReconnect=true argument to the url makes sure that the
mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
connection. mysqld by default closes idle connections after 8 hours.
–>
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/demodb?autoReconnect=true&useUnicode=true&characterEncoding=gb2312</value>
</parameter>
</ResourceParams>
</Context>
2. Declare the resource inside the application’s web.xml. Like this:
<web-app xmlns=”http://java.sun.com/xml/ns/j2ee“
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance“
xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd“
version=”2.4″>
<web-app>
<description>MySQL Connection Pooling Test</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
3. Using the connection pool.
Now, Create a simple jsp page to test the connection pool.
<%@ page contentType=”text/html;charset=GBK”%>
<%@ page import= “java.sql.* “%>
<%@ page import= “javax.sql.* “%>
<%@ page import= “javax.naming.* “%>
<%
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try{
Context initCtx = new InitialContext();
DataSource ds = (DataSource)initCtx.lookup(”java:comp/env/jdbc/TestDB”);
conn = ds.getConnection();
stmt = conn.createStatement();
String sql = “select userid, username from userinfo”;
rs = stmt.executeQuery(sql);
while (rs.next()) {
out.println(rs.getString(1) + “<br />”);
out.println(rs.getString(2) + “<br />”);
}
rs.close();
rs = null;
stmt.close();
stmt = null;
conn.close();
conn = null;
} catch (Exception ex) {
out.println(”Cannot get Connection pool. Error:” + ex);
ex.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
out.println(”Cannot close ResultSet” + e);
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
out.println(”Cannot close Statement” + e);
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
out.println(”Cannot close Connection” + e);
}
conn = null;
}
}
%>
And the following is a Java class which is used to obtain a Connection from Connection pool.
package com.esurfer.common;
import java.sql.Connection;
import java.sql.SQLException;
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/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;
}
}
References:
Connection pooling with MySQL Connector/J
http://dev.mysql.com/tech-resources/articles/connection_pooling_with_connectorj.html
JNDI Datasource HOW-TO of Tomcat Documentation
http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html
Written by coregps on Friday, July 29th, 2005 in Java.
JavaCoding.net provides Java certification mock exams for SCJP and SCEA. The mock exams for each certification can be accessed via 1 application, which can be launched via Java Web Start. You can take the tests as many times as you want. Questions are randomly taken from repository each time. At the end of the series of questions, you’ll get your score and a detailed report of your mistakes.
Take the test now at http://www.javacoding.net/mocks/mocks.php
Written by coregps on Friday, July 29th, 2005 in Web Design.
| 000000 | 000033 | 000066 | 000099 | 0000CC | 0000FF |
| 003300 | 003333 | 003366 | 003399 | 0033CC | 0033FF |
| 006600 | 006633 | 006666 | 006699 | 0066CC | 0066FF |
| 009900 | 009933 | 009966 | 009999 | 0099CC | 0099FF |
| 00CC00 | 00CC33 | 00CC66 | 00CC99 | 00CCCC | 00CCFF |
| 00FF00 | 00FF33 | 00FF66 | 00FF99 | 00FFCC | 00FFFF |
| 330000 | 330033 | 330066 | 330099 | 3300CC | 3300FF |
| 333300 | 333333 | 333366 | 333399 | 3333CC | 3333FF |
| 336600 | 336633 | 336666 | 336699 | 3366CC | 3366FF |
| 339900 | 339933 | 339966 | 339999 | 3399CC | 3399FF |
| 33CC00 | 33CC33 | 33CC66 | 33CC99 | 33CCCC | 33CCFF |
| 33FF00 | 33FF33 | 33FF66 | 33FF99 | 33FFCC | 33FFFF |
| 660000 | 660033 | 660066 | 660099 | 6600CC | 6600FF |
| 663300 | 663333 | 663366 | 663399 | 6633CC | 6633FF |
| 666600 | 666633 | 666666 | 666699 | 6666CC | 6666FF |
| 669900 | 669933 | 669966 | 669999 | 6699CC | 6699FF |
| 66CC00 | 66CC33 | 66CC66 | 66CC99 | 66CCCC | 66CCFF |
| 66FF00 | 66FF33 | 66FF66 | 66FF99 | 66FFCC | 66FFFF |
| 990000 | 990033 | 990066 | 990099 | 9900CC | 9900FF |
| 993300 | 993333 | 993366 | 993399 | 9933CC | 9933FF |
| 996600 | 996633 | 996666 | 996699 | 9966CC | 9966FF |
| 999900 | 999933 | 999966 | 999999 | 9999CC | 9999FF |
| 99CC00 | 99CC33 | 99CC66 | 99CC99 | 99CCCC | 99CCFF |
| 99FF00 | 99FF33 | 99FF66 | 99FF99 | 99FFCC | 99FFFF |
| CC0000 | CC0033 | CC0066 | CC0099 | CC00CC | CC00FF |
| CC3300 | CC3333 | CC3366 | CC3399 | CC33CC | CC33FF |
| CC6600 | CC6633 | CC6666 | CC6699 | CC66CC | CC66FF |
| CC9900 | CC9933 | CC9966 | CC9999 | CC99CC | CC99FF |
| CCCC00 | CCCC33 | CCCC66 | CCCC99 | CCCCCC | CCCCFF |
| CCFF00 | CCFF33 | CCFF66 | CCFF99 | CCFFCC | CCFFFF |
| FF0000 | FF0033 | FF0066 | FF0099 | FF00CC | FF00FF |
| FF3300 | FF3333 | FF3366 | FF3399 | FF33CC | FF33FF |
| FF6600 | FF6633 | FF6666 | FF6699 | FF66CC | FF66FF |
| FF9900 | FF9933 | FF9966 | FF9999 | FF99CC | FF99FF |
| FFCC00 | FFCC33 | FFCC66 | FFCC99 | FFCCCC | FFCCFF |
| FFFF00 | FFFF33 | FFFF66 | FFFF99 | FFFFCC | FFFFFF |
Written by coregps on Friday, July 29th, 2005 in Java.
KickJava.com puts all the Java APIs from J2SE, J2EE, J2ME, Java TV, Java Phone, and Java Card under one roof, you can browse all of them in one place by API, class, and package. You can add your code snippet to these Java APIs and view the examples. It also provides many links to free ebooks. For more information, visit http://www.kickjava.com/.
Written by coregps on Friday, July 29th, 2005 in Java.
Javascript to Java applet
Javascript can access public methods and variables exposed by a Java applet. An applet within a document is referred to either using it’s id / name or using an index into the applets collection(starting from zero).
Considering the following applet:
<applet code=”HelloWorld.class” name=”HelloApplet” width=”400″ height=”100″>
</applet>
We can refer to this applet using any of the following methods in JavaScript:
document.HelloApplet
// or
document.applets[”HelloApplet”]
// or
document.applets[0]
Where applets array is used to reference all of the applets on a page. The length property of applets returns how many applets are in the document (document.applets.length).
The following is an simple Hello World applet:
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
private String msg = “Hello World!”;
public void paint(Graphics g) {
g.drawString(msg, 20, 20);
}
public void setMessage(String msg) {
this.msg = msg;
repaint();
}
}
The following is the html page which runs and displays the applet:
<html>
<head>
<title>Communication between Javascript and Applet</title>
<script type=”text/javascript”>
function setMessage(s) {
document.HelloApplet.setMessage(s);
// alternative way to reference the applet
// document.applets[’HelloApplet’].setMessage(s);
// or
// document.applets[0].setMessage(s);
}
</script>
</head>
<body bgcolor=”#FFFFFF”>
<applet code=”HelloWorld.class” name=”HelloApplet” width=”400″ height=”100″>
</applet>
<br />
<input type=”button” value=”Set Message” onclick=”setMessage(’Hello Message From Javascript!’);”/>
</body>
</html>
Java applet to Javascript
To access JavaScript methods, properties, and data structures from Java applet, we need to import the Netscape javascript package:
The package netscape.javascript defines the JSObject class and the JSException exception object. Java Class JSObject represents JavaScript Objects and JSException represents JavaScript exceptions. You can find these .class files in a .zip file located in the <Windows Installation Directory>\Java\Packages directory or download here: netscape.jar.
In addition, we need to specify the MAYSCRIPT attribute of the <APPLET> tag which permit an applet to access JavaScript. Attempting to access JavaScript from an applet that does not have the MAYSCRIPT attribute generates an exception. The MAYSCRIPT tag is needed only for Java applet to access JavaScript; it is not needed for JavaScript to access Java applet.
<applet code=”HelloWorld.class” name=”HelloApplet” width=”400″ height=”100″ MAYSCRIPT=”MAYSCRIPT”>
</applet>
The following is a brief description of the JSObject class’ member functions:
public static JSObject getWindow (Applet applet )
This static method returns a JSObject for the window containing the given applet. For example,
JSObject MainWindow = JSObject.getWindow ( this );
public Object call ( String methodName, Object args[ ] )
This invokes a JavaScript method from within a Java applet. For example,
JSObject MainWindow = JSObject.getWindow ( this );
String message[ ] = {”Hello!”};
MainWindow.call ( “showAlert”, message );
public Object eval ( String s )
This method evaluates a JavaScript expression. The expression is a string of JavaScript source code, which will be evalauted in the context given by this. For example,
JSObject win = JSObject.getWindow ( this );
JSObject msg = win.eval ( “document.testForm.message” );
public Object getMember ( String name )
This method retrieves an indexed member of a JavaScript object. Equivalent to this.name in JavaScript. For example,
JSObject MainWindow = JSObject.getWindow ( this );
JSObject DocumentPage = (JSObject)MainWindow.getMember ( “document” );
JSObject TestForm = (JSObject) DocumentPage.getMember ( “TestForm” );
JSObject Message = (JSObject) TestForm.getMember ( “message” );
public Object getSlot ( int index)
This method retrieves an indexed member of a JavaScript object. Equivalent to this [index] in JavaScript. For example,
JSObject MainWindow = JSObject.getWindow ( this );
JSObject DocumentPage = (JSObject)MainWindow.getMember ( “document” );
JSObject Applets = (JSObject) DocumentPage.getMember ( “applets” );
Object theApplet = Applets.getSlot ( index );
public void removeMember ( String name )
This method removes a named member of a JavaScript object.
public void setMember ( String name, Object value )
This method sets a named member of a JavaScript object. It is equivalent to this.name = value in JavaScript. For example,
JSObject MainWin = JSObject.getWindow ( this );
JSObject DocumentPage = (JSObject) MainWin.getMember ( “document” );
JSObject TestForm = (JSObject) DocumentPage.getMember ( “testForm” );
JSObject Message = (JSObject) TestForm.getMember ( “message” );
Message.setMember ( “value”, “Congratulations!” );
public void setSlot ( int index, Object value )
This method sets an indexed member of a JavaScript object. It is equivalent to this[index] = value in JavaScript.
public String toString ()
This method converts a JSObject to a string.
The following is an example:
import java.applet.Applet;
import java.awt.Event;
import java.awt.Graphics;
import netscape.javascript.*;
public class HelloWorld extends Applet {
private String msg = “Hello World!”;
public void init() {
try {
JSObject win = JSObject.getWindow(this);
try {
msg = (String)win.eval(”document.testForm.message.value”);
} catch (Exception e1) {
showStatus( “Error call javascript err=” + e1 );
}
} catch (JSException e) {
showStatus( “Error call javascript err=” + e );
}
}
public void paint(Graphics g) {
g.drawString(msg, 20, 20);
try {
JSObject.getWindow(this).call(”showAlert”, new Object[]{”Hello Message From Applet”});
} catch (JSException e) {
showStatus( “Error call javascript err=” + e );
}
}
public void setMessage(String msg) {
this.msg = msg;
repaint();
}
public boolean mouseMove(Event e, int x, int y) {
try {
JSObject.getWindow (this).eval (”javascript:window.status=’x:” + x + “, y:” + y + “‘”) ;
} catch (Exception ex) {
showStatus( “Error call javascript err=” + ex );
}
return true ;
}
}
The html page looks like this:
<html>
<head>
<title>Communication between Javascript and Applet</title>
<script type=”text/javascript”>
function setMessage(s) {
document.HelloApplet.setMessage(s);
}
function showAlert(s) {
alert(s);
}
</script>
</head>
<body bgcolor=”#FFFFFF”>
<applet code=”HelloWorld.class” name=”HelloApplet” width=”400″ height=”100″ MAYSCRIPT=”MAYSCRIPT”>
</applet>
<br />
<input type=”button” value=”Change Message” onclick=”setMessage(’Hello Message From Javascript!’);”/>
<form name=”testForm”>
<input type=”text” name=”message” size=”20″ value=”Congratulations!”/>
</form>
</body>
</html>
References:
http://www.netspade.com/articles/java/javascript.xml
http://www.javaside.com/asp/mus.asp?page=/us/tips/j_2.shtml
http://www.csse.monash.edu.au/~lloyd/tildeProgLang/Java/JavaScript/
http://www.codeproject.com/jscript/javatojs.asp?df=100&forumid=736&exp=0&select=40180
http://docs.rinet.ru/WebPub/ch38.htm
http://members.ozemail.com.au/~phoenix1/html/livecon.htm
http://members.ozemail.com.au/~phoenix1/html/packages.htm#1003191
Written by coregps on Friday, July 29th, 2005 in General.
Chinese New Year, Spring Festival is coming on 9th February, it is the time for family reunion. I’m so excited that I can not get down to my work. It has been one year since I left home. Now, I will go back to home. Therefore, there will be no updates here until my return.
Written by coregps on Friday, July 29th, 2005 in Java.
For fresh Tomcat installations, directory listing is enabled by default. We will see the entire directory listing when no index file is present. For production deployments, it is encouraged to turn it off. There are basically 2 methods to achieve this:
1. Create an index.html file and place it in the web application’s directory where there is no index file in it. Like following:
<html>
<head>
<meta http-equiv=”refresh” content=”3; url=http://www.demo.com/”>
</head>
<body>
<center>
<p>
The requested page was not found on this server. <br />
You will be redirected to home page in 3 seconds.
</p>
<center>
</body>
</html>
2. Edit the global web.xml file to turn off the option.
Open the file web.xml which is located inside $CATALINA_HOME/conf/. Locate the following section:
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>
org.apache.catalina.servlets.DefaultServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Change <param-value> (highlignted above) of listings parameter to false. Save this file, and restart Tomcat.
Written by coregps on Friday, July 29th, 2005 in General.
I’m often confused by the difference between the words “property” and “attribute“. Today I found an article which explains the difference between the two words in detail. Below are some portions of that article.
Property: The word property comes from Latin properius, which means “own”. A property is what the thing has on its own (pertaining to itself). That means, a property denotes a objective physical aspect, which is independent of our knowledge or opinion .
Attribute: The word attribute comes from the latin verb “tribuere”, which means to give. For instance, a tribute is a gift, to retribute is to give back, to attribute is to give at. An attribute is literally “given at”. So, by definition, an attribute is a given fact, which has been attributed, ascribed, imputed, assigned or otherwise given. That means, by definition, an attribute is subjective; it’s a virtual quality.
The words property and attribute are meant to be pointers that direct the attention to the difference. The word “property” pointing to the real aspects and “attribute” pointing to the virtual aspects of things. These pointers are very useful because they enable us to decide what is real or virtual. They are a great help in switching mentally between a realistic and a virtualistic mode of perception. Most things have both properties and attributes, which means there are always real and virtual aspects about almost anything. This applies not only to people but also to animals and objects. E.g. A person may have certain physical properties, such as blue or brown eyes, or a white or black skin, but the nationality or citizenship of that person is always a virtual attribute.
The properties are intrinsic physical qualities of the object itself: They can, in principle, be perceived through the senses or measured objectively by instruments. For instance, the height, the shape, the substance or the weight of an object are its properties. The attributes, on the other hand, are “virtues” supplied by the mind. For instance, a house may have many properties, which make it real but the value of it is an attribute. So, the value of a house is virtual. Another example is the sex of a person: Being a man or a woman is a property but being someone’s husband or a wife is an attribute.
Read the full article at http://www.muc.de/~heuvel/papers/virtual/properties_and_attributes.html.
Written by coregps on Friday, July 29th, 2005 in AJAX, Web Design.
“Please Wait” messages are an excellent way to let the user know that your web based application is performing some action, such as loading a page or processing data. Without such a notification, users may begin clicking other controls on the web page, or close the browser due to the excessive delays.
The following “Please Wait” function is done using DIV layers. While the web application performs a long time process, a “Please Wait” message will be displayed. When process is finished, the “Please Wait” message will be hidden.
<head>
<style type=”text/css”>
.bgcolor1{
background-color:#B5CBE7;
}
.bgcolor2{
background-color:#F7F7F7; font-size: 10pt;
}
</style>
<script type=”text/javascript”>
function showWait(optype) {
if(optype == “show” ) {
waiting.style.visibility = “visible”;
} else {
waiting.style.visibility = “hidden”;
}
}
</script>
</head>
<body>
<div id=”waiting” class=”bgcolor1″ style=”position:absolute; top:130; left:35%; z-index:10; visibility:hidden; padding:1px;”>
<div class=”bgcolor2″ style=”width:280px; text-align:center; padding:10px;” id=”waiting_sub”>
<img src=”/image/wait.gif” align=absmiddle> Processing… Please Wait
</div>
</div>
</body>
<script type=”text/javascript”>showWait(’show’);</script>
<!– long-time operations here –>
<script type=”text/javascript”>showWait(’hide’);</script>
Written by coregps on Friday, July 29th, 2005 in Java.
In my recent project, I have a jsp page that creates files and directories on the Tomcat web server. These files and directories are owned by user “Tomcat”. However, When I deleted these useless files and directories using FTP, I failed. Even though I set the permissions of those files and directories to 777. So, I wrote the following code to accomplish this.
<%@ page pageEncoding=”GBK”%>
<%@ page contentType=”text/html;charset=GBK”%>
<%@ page import=”java.io.*”%>
<%@ page isELIgnored=”false” %>
<%!
private void clearFiles(File file, JspWriter os) throws IOException{
if (file.isDirectory()) {
os.println(”<font color=’blue’>Processing Directory: ” + file.getName() + “</font><br/>”);
os.flush();
File[] allfile = file.listFiles();
for (int i = 0; i < allfile.length; i++) {
clearFiles(allfile[i], os);
}
os.println(”<font color=’teal’><b>Deleting</b> Directory: ” + file.getName() + “</font><br/>”);
os.flush();
if ( file.delete() ) {
os.println(” <b>Success</b>”);
os.flush();
} else {
os.println(” <b>Failed</b>”);
os.flush();
}
} else if (file.isFile()) {
os.println(”<font color=’red’><b>Deleting</b> File: ” + file.getName() + “</font><br/>”);
os.flush();
if ( file.delete() ) {
os.println(” <b>Success</b>”);
os.flush();
} else {
os.println(” <b>Failed</b>”);
os.flush();
}
}
}
%>
<c:if test=”${param.start == ‘true’}”>
<%
File file = new File((getServletContext().getRealPath(”/”) + “www”).replace(’\\’, ‘/’));
clearFiles(file, out);
%>
</c:if>
<c:if test=”${param.start != ‘true’}”>
<form>
<input type=”hidden” name=”start” value=”true”/>
<input type=”submit” value=”Start Delete”/>
</form>
</c:if>
Written by coregps on Friday, July 29th, 2005 in Java, AJAX.
As is well known, Forms are the way to “call” server side scripts in HTML, the page will be reloaded each time the forms are posted, this is often not very user friendly. Using the HTTP Request, we can call the server side script without refreshing the page. I’ve used this technology in my current web project. However, I encountered some trouble with it, which took almost my whole night.
This is an online exam system that enables students to take online test through browser. It provides a feature that is enable students to mark doubtable questions which can be reviewed again. To prevent reloading pages, I use the HTTP Request to post requests to a server side script which deals with the answers of students, also the doubtable questions. The following is the main idea of this system:
First, Save all the questions selected randomly to a session with the doubtable flag set to the default value false.
And then, Display all the questions and their selectable answers, each with a button used to mark doubtable questions. The default value of the button is empty, when students click it, it will display a question mark. At the same time, set the doubtable field of the question to true in the session.
Now, the trouble comes. The first time students mark a doubtable question and cancel mark of the same question works well. From the second time on, It can not work correctly. I tried my best to find the root cause of it almost a whole night
The following is my initial code snippet:
<script type=”text/javascript”>
function markDoubt(questionid, doubtFlag) {
// 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 = “dealAnswer.jsp?questionid=” + questionid + “&flag=” + doubtFlag;
xmlHttp.open( “POST”, sURL, false );
// Execute the request
xmlHttp.send(null);
alert(xmlHttp.responseText);
}
</script>
In order to find out the reason, I add the following line to the server side script (dealAnswer.jsp):
And use the responseText property of HTTP Request Object to show the response. I imagine that when making a new request, the response should show a different time. Most curious of all, I found that this can work only the first time. From the second time on, it returned the same response as the time making the same request the first time. For example,
The First time students mark a doubtable question, the time of the response is:
Wed Jan 26 15:35:29 CST 2005
And then cancel the question mark of the same question, the time of the response is:
Wed Jan 26 15:36:52 CST 2005
From the second time on, when students mark the same doubtable question, the time of the response is still:
Wed Jan 26 15:35:29 CST 2005
And cancel the same question is still:
Wed Jan 26 15:36:52 CST 2005
It seems that the response has been cached. So, I added the following lines:
response.setHeader(”Cache-Control”,”no-cache”); //HTTP 1.1
response.setHeader(”Pragma”,”no-cache”); //HTTP 1.0
response.setDateHeader (”Expires”, 0); //prevents caching at the proxy server
However, NO EFFECT!!!!
Finally, I add an additonal request parameter named currTime to the Query String and delete the XML HTTP Request object after making the post so that there always be a different URL each time. As following:
<script type=”text/javascript”>
function markDoubt(questionid, doubtFlag) {
// 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 = “dealAnswer.jsp?questionid=” + questionid + “&flag=” + doubtFlag + “&currTime=<%=new java.util.Date()%>”;
xmlHttp.open( “POST”, sURL, false );
// Execute the request
xmlHttp.send(null);
delete xmlHttp;
}
</script>
Wow!!! It works!!!! I’m very excited.
Although it can work now, I don’t understand why. Any comments will be appreciated.
Written by coregps on Friday, July 29th, 2005 in SQL Server.
I’m working on an online exam project in jsp using SQL Server 2000 database. In which I need some way to quickly pull out a certain number of random records (questions) for each subject and the type of the question from database and generate the exam paper. I used the following solution, it is very simple.
Where N is the number of records that you want, the NewID() function returns a new Unique Identifier(GUID). When the query runs, a column with GUIDs is created and the results are sorted before the N records are retrieved.
The following T-SQL is my code snippet used to select random questions from database.
Written by coregps on Friday, July 29th, 2005 in Workflow, Web Services.
BPEL4WS stands for Business Process Execution Language for Web Services.
Business Process can be described in two ways:
- Executable business processes, which model actual behavior of a participant in a business interaction.
- Business protocols(abstract processes), which use process descriptions that specify the mutually visible message exchange behavior of each of the parties involved in the protocol, without revealing their internal behavior.
BEPL4WS provides a language for the formal specification of business processes and business interaction protocols.
BPEL4WS extends the Web Services interaction model and enables it to support business transactions.
BPEL4WS defines an interoperable integration model that should facilitate the expansion of automated process integration in both the intra-corporate and the business-to-business spaces.
BPEL4WS uses a notion of message properties to identify protocol-relevant data embedded in messages which can be viewed as “transparent” data relevant to public aspects as oppsed to the “opaque” data that internal/private functions use.
- Transparent data affects the public business protocol in a direct way
- Opaque data affects the business protocol only by creating nondeterminism.
Any data that is used to affect the behavior of a business protocol must be transparent and hence viewed as a property.
BPEL4WS defines a model and a grammar for describing the behavior of a business process based on interactions between the process and its partners. The interaction with each partner occurs through Web Service interfaces, and the structure of the relationship at the interface level is encapsulated in what we call a partner link.
The BEEP4WS process defines how multiple service interactions with these partners are coordinated to achieve a business goal, as well as the state and the logic necessary for this coordination.
BPEL4WS also introduces systematic mechanisms for dealing with business exceptions and processing faults.
Finally, BPEL4WS introduces a mechanism to define how individual or composite activities within a process are to be compensated in cases where exceptions occur or a partner requests reversal.
BPEL4WS is layered on top of several XML specifications: WSDL1.1, XML Schema 1.0, and XPath1.0.
- WSDL messages and XML Schema type definitions provide the data model used by BPEL4WS processes.
- XPath provides support for data manipulation.
- All external resources and partners are represented as WSDL services.
Written by coregps on Friday, July 29th, 2005 in Java.
MyJavaServer provides an open, freely accessible development and deployment environment for us to expand our knowledge towards new, innovative and industry-relevant web and enterprise application frameworks and platforms. The following are what MyJavaServer offers to us:
Connection
14 Gbps (14,336 Mbps) aggregated bandwidth to the internet via 6 independent network backbones
Java services
J2SE 1.5 based application server
Servlet 2.3
Java Server Pages (JSP) 1.2
Pre-installed third-party libraries
RDBMS services
Embedded: HSQLDB, InstantDB
Miscellaneous
SMTP service
Unfiltered HTTP responses (no ad placement)
WAP/WML, Java WebStart MIME extensions
Storage
5 MB initial filesystem quota
Full native filesystem read/write access
File Transfer Protocol (FTP) file management
Don’t wait any more, join it quickly!!! You can sign up for it here: http://www.myjavaserver.com/
Written by coregps on Friday, July 29th, 2005 in Linux.
Red Hat offers a worldwide Red Hat Academy program for high schools and higher education to teach students the most practical and relevant Linux and open source skill sets. Red Hat Academy assures students truly understand the content by deploying the only 100% web-delivered Linux curriculum with hands-on assignments and performance-based assessments.
Written by coregps on Friday, July 29th, 2005 in General.
Today, When I surf on the web I found an online typing test website. I took a test there and got a bad socre
, even though I spend a lot of time indoors working on a computer. So I decide to set aside some time every day to improve my typing skills.
How fast can you type? Take a typing test here.
Written by coregps on Friday, July 29th, 2005 in Java.
The Servlet API provides a method to turn a URL path, relative to the current JSP or Servlet, into an absolute filesystem path. The method ServletContext.getRealPath(String) does the trick. Every JSP has a ServletContext object called application.
To get absolute root path of web application, using something like this:
or
To get absolute path of current jsp page, using something like this:
String jspFilePath = getServletContext().getRealPath(request.getRequestURI()).replace(’\\’, ‘/’);
String absPath = jspFilePath.substring(0, jspFilePath.lastIndexOf(”/”));
or
X-Smiles is a Java based XML browser. It is intended for both desktop use and embedded network devices and to support multimedia services.
The main advantage of the X-Smiles browser is that it supports several XML related specifications and is still suitable for embedded devices supporting the Java environment.
The main objective of X-Smiles project is to deliver a pure Java XML browser, capable of displaying documents written in various XML languages. The X-Smiles browser should support at least:
I was so excited when I found this baby. Don’t wait any more! I’m sure that you will be excited by this soooooooooooooooooo coooooooooooooooool browser too!
To take a look at screen shots of X-Smiles at http://www.xsmiles.org/screenshots.html
Download X-Smiles at http://www.xsmiles.org/download.html