Monday, March 29, 2010

Simple Captcha with Struts

In this post we will learn how to use simple Captcha with Struts to create Captcha for confirming that the interacting user is a person not a computer..

Here is a 5-steps implementation:

1.Download the Simple Captcha jar:

Here is the link:

2.Add the jar to your web project classpath:

Typically inside web-inf/lib folder

3.Add new servlet to your web project:
Name: CaptchaServlet

*Implement doGet method:

try {
Captcha captcha = new Captcha.Builder(200, 50).addText(new DefaultTextProducer(6)).gimp(new DropShadowGimpyRenderer()).build();
//200, 50 is the size, 6 is the number of letters to use, we choose the shadow renderer.
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
// don't cache it , don't store it, expire after 0 second, so with refresh new image loaded
//image type
CaptchaServletUtil.writeImage(response, captcha.getImage());
//write the image
//store the answer for this in session
} catch (Exception e) {

4.In Your action class: (where the html form that include Captcha is submitted) add the following code:

//registerFormBean is the form bean of the current action and captcha response is the field of user input

String answer =
if (answer == null || registerFormBean.getCaptchaResponse()==null || !answer.equals(registerFormBean.getCaptchaResponse())){
ActionErrors errors = new ActionErrors();
errors.add("error1", new ActionMessage("error.captcha"));

error.captcha contain the following value in resource bundle:
error.captcha=Invalid value of shown text!

//so we check either pass successfully or add to errors error regarding captcha.

5.In the JSP file , add the following:

<img id="captchaImg" src="/...context..../CaptchaServlet" alt="Captcha Image" height="45">
<img src="/...context..../images/reload.jpg" alt="Reload" onclick="document.forms[0].captchaImg.src='/...context..../CaptchaServlet?id='+Math.random();" style="cursor:pointer"/>
<br><font color=red>*</font>Enter Value Shown:
<br><html:errors property="error1"/><br>
<html:text property="captchaResponse" maxlength="6" style="width:100pt"/>

-This will construct the Captcha and the text field to enter the value and struts error message to show errors in captcha response, plus the refresh icon.

NOTE: a good trick we used here is the java script Math.random() function , this way prevent certain browsers like Firefox 3.0 to cache the URL and keep posting the same Captcha image , this enforce it to get the new value without doing any more effort.

Here is how it will looks like:

Invalid content Error Message shown here:

For more details refer to the web site :

Sunday, March 28, 2010

RESTful WS & ROA in JDC 2010 (My Presentation)

In Java Developer Conference 2010 , i have spoken about the RESTful Web Serivces and Resource Oriented Architecture.

I gave overview over the basic web concepts , REST concepts , how to implement RESTful WS using Jersey implementation of the Java specification JAX-RS (JSR-311), using Ajax with RESTful WS and finally what is known as ROA (Resource Oriented Architecture)

The term REST comes from Roy Fielding's PhD dissertation, published in 2000, and it stands for REpresentational State Transfer. REST by itself is not architecture.

REST is a set of constraints that, when applied to the design of a system, creates a software architectural style.

Fielding ends with the following constraints that define a RESTful system:
• It must be a client-server system
• It has to be stateless—there should be no need for the service to keep users’ sessions; in other words, each request should be independent of others
• It has to support a caching system—the network infrastructure should support cache at different levels
• It has to be uniformly accessible—each resource must have a unique address and a valid point of access
• It has to be layered—it must support scalability
• And others.

These constraints don't dictate what kind of technology to use; they only define how data is transferred between components and what are the benefits of following the guidelines.

Therefore, a RESTful system can be implemented in any networking architecture available.

More important, there is no need for us to invent new technologies or networking protocols: we can use existing networking infrastructures such as the Web to create RESTful architectures.

Consequently, a RESTful architecture is one that is maintainable, extendable, and distributed.

In September, 2009, the final release of Sun JAX-RS (JSR-311) provides a high level declarative programming model; with the ability to create Restful Web Services by using this implementation we can achieve Resource Oriented Architecture (ROA).

You can find the presentation at:

Using Ajax with Struts

In this post we will go through the easiest way to add Ajax support in struts application, this means using the Action class not Servlet in the Ajax URL..

We will go through adding Ajax support to check on the uniqueness of login-name (i.e. availability for the user to register using the name) , we will do the following simple steps to achieve this:

1. Create the Java Script method that call our action class:
//this is the request object
var request= null ;
//this is the function that will be called to submit our request, it is generic function that accept URL and value and param so it can be used by different components:

function isUniqueName(url,value,param){
if(value==null || value==""){
alert("Please Enter Valid "+param+"!");
return false;
request.onreadystatechange = handleRequest;"POST",url+value,true);
request.send("<?XML version=\"1.0\" encoding=\"UTF-8\"?>");
//This function to create our request object for different browsers
function createXmlHttpRequest(){
request = new ActiveXObject("Microsoft.XMLHTTP");
else if(window.XMLHttpRequest){
request = new XMLHttpRequest();
//this is the function that handle the response and update the UI, it assume there will be div named "Output" to recieve the outcome of the http request made:
function handleRequest(){
if(request.readyState == 4 && request.status == 200){
if(value == null){
value = request.responseXML;
document.getElementById("output").innerHTML = value;

2.Import Java script file in the html page:

<script language="JavaScript" src="/..../ajax_check_name.js">

-This is the name of our java script file.

3.Add html components that will use these functions:

//login field:

Login Name <html:text property="loginName" maxlength="16" style="width:250pt" onblur="isUniqueName('/..../',this.value,'loginName');"/>

//check button
<img src="/..../images/question.jpg" alt="Check Availability?" onclick="isUniqueName('/.../',document.forms[0].loginName.value,'loginName');" style="cursor:pointer">

//output div
<div id="output"></div>

- As you can see we call the Ajax function 2 times one on leave the text field and another one when click on check ourselves.

4.In Action Class:

String stepId=request.getParameter(IActions.STEP_ID);

String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.write("< src='/.../images/not_available.jpg' />");return null;
out.write("< src='/..../images/available.jpg' />");return null;

- Of course the logic here , if login name already exist , show not available image to the user, otherwise it is available to use it.

- You should notice the null return here , is to by-pass struts forwards return from the mapping files, this behave as if you are using Servlet directly.

* The Output will looks like :
Name already exist.
Name available for use.

Saturday, March 27, 2010

Draw ECG Using Java Script Draw Functions

In this post we will draw ECG using Java script draw library functions, the output will looks like the above image.

To draw ECG we need to identify few things 1st :
1.ECG baseline used.
2.Sampling rate : no of readings per seconds.

1. We will have 1 html div component to draw the ECG inside:

<div id="Canvas" style="background-image: url(ecg_back.png); position: relative; height: 250px; width: 1000px;"></div>

This is the div background image, its 250x50, this will typically fit for 1 Second (so you need to draw samples in this box according to your sampling rate, in our example we have 500/seconds so we draw 500 per this 250 pixel , so we will increment the draw by 0.5 for each sample).

2. Import the graphics library: (in the header)

<script type="text/javascript" src="wz_jsgraphics.js"></script>

You can download this library from the URL:

3. Initialize the Java Script ECG variables: (in the header)

y=new Array(....,.....,.... ); //this contain the y values (readings) we will post the example values at the end of the article.
currentPart=0; //current page is 1st page in the ECG
baseline=201; //the is the ECG recording baseline
total=0; //total number of pages
temp=y.length; //calculate the total number of pages
temp=temp-2000; //as shown in the 1st image , we will draw 4 seconds in each page (each second represented by 500 sample =2000 total sample)
//initiliazie the graphics object to draw in our Div (i.e. Canvas)
jg = new jsGraphics("Canvas");
//set this true if we need to allow the user to print it, it will impact performance a little.

4. Draw the initial ECG page by calling draw() method on html body onload:

<body onload="draw();">

5. Draw function code:

function draw(){
jg.drawString("Lead II",40,5); //this should be adjusted according to the lead number
jg.drawString("HR 80 per min",40,25); //this should be adjusted according to HR value
jg.drawString("Page "+(currentPart+1)+"/"+total,40,220); //this is the current page number
var x=0;
var x=0;
if(x==1000) { break;} //break once reach to end of the div of 4 seconds.

6. Next and Previous page buttons:

<img src="prev.gif" onclick="drawPrev();"/>
<img src="next.gif" onclick="drawNext();"/>

7. drawPrev() and drawNext() functions:

function drawNext(){
jg.clear(); //clear all drawings
start=currentPart*2000; //this is the total samples per page (4 seconds)
var x=0;
jg.drawString("Lead II",40,5);
jg.drawString("HR 80 per min",40,25);
jg.drawString("Page "+(currentPart+1)+"/"+total,40,220);
if(x==1000) { break;}

function drawPrev(){
jg.clear(); //to clear all drawings
var x=0;
jg.drawString("Lead II",40,5);
jg.drawString("HR 80 per min",40,25);
jg.drawString("Page "+(currentPart+1)+"/"+total,40,220);
if(x==1000) { break;}

8. Y array example values:

y=new Array(12,13,18,27,38,44,44,43,46,52,57,57,53,49,48,49,50,51,54,57,59,59,57,56,55,55,55,56,57,59,59,59,59,59,59,59,58,59,59,59,60,60

Note: For more details about Graphics drawing library , check the URL:

You can find a working example at the URL:

Friday, March 26, 2010

Free Secure Wallet

Free Secure Wallet is a free mobile application build by J2ME

Used for storing sensitive data on mobiles (secure notepad) like Credit card, password and all sensitive data that should be kept secure.

The application provide a lot of security measures like log in password, encode stored data for more security , expire session after 30 min. (since version 1.2 this is configurable feature)

It is working on all J2ME platforms with MIDP 2.0 and CLDC 1.0. It support Arabic/English languages for the interface, But stored data should be English.

*Since version 1.1 a newly added feature which is "Forced Password Set" this allow you to set a password that can be used to open the application in case you are forced for that, it open the application with no entries displayed.

*Since version 1.2 , you have the option to list the items sorted or not sorted.

*Now in version 2.0, you have the ability to export the data into the device memory than re-import them on another device but after providing the same password used in export them, so you can change your device and keep your data move easily.

The Application Version 2.0 can be downloaded from the URL :

Any suggested features will be considered in subsequent releases.

Tuesday, March 23, 2010

Ajax Simplified Steps

Ajax Simplified Steps

This is my 1st post in my technical blog , i will show here different technical topics, i will try to simplify the steps needed to implement different technologies and post some tutorials to show the basic concepts behind them.

In this post i am showing how to use the Ajax technology in few simple steps describing the technology basics, the 2nd post will show a real project that uses Ajax.

Let's begin with the steps that we need to implement Ajax in our web projects:

1.Create Request Object:

request = new XMLHttpRequest();

-This is the object that we will use to open the connection.

2.Call Open method:[HTTP method], [URI], Async, [Basic auth username], [Basic auth password]);

-Here we open the connection using the required http method (Post, Put, Get, ...),URI is the requested URI , aynch = true/false for asynchronous or not.

3.Setup Handler method:

request.onReadyStateChange = [Name of handler function];

-The handler method is the method that will receive the response of our request, so it can process it.

4.Send header information:(if needed)

request.setRequestHeader([Header name], [Header value]);

-If we need to send specific header attribute , like needed response type ,..etc., we use this method to set this header parameter.

5.Send the request:

request.send([Entity-body]); //null if not PUT or POST

-This method submit the request.

6.Handler method called with status:

- The handler method usually check if the response is return or not and the response status code for example readyState=4 means the response is ready now , e.g.

If(request.readyState==4 [&& request.status == 200]) {
//do UI changes

The possible Ready Status values are:
0 = Unsent
1 = Opened
2 = Header Received
3 = Loading
4 = Done

So Done here doesn't mean success , so you need to check on the response status is 200 which means OK.

* 2 Response Types available:

* responseXML: DOM object representing the response document—assuming it was served as XML and the browser can parse it
* responseText: response document as a raw string—useful when it’s JSON or some other non-XML format

7.Get Response Header Info:
(if needed)


-In case you expected certain header attributes in the response, you can use this method to retrieve it.

**Cross Platform Issue

To enable it to work in all browsers you need to get the request object correctly,so replace this method :

request = new XMLHttpRequest();

request = createXMLHttpRequest();

function createXMLHttpRequest() {
if (typeof XMLHttpRequest != "undefined") {
return new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined") {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("XMLHttpRequest not supported");

Parsing the Response:

To Parse the response you can have it as XML or non-XML (mostly JSON):

Parsing XML Response

function myHandler() {
if (request.readyState == 4) {
var root = request.responseXML;
var addrsElem = root.getElementsByTagName('addresses')[0];
var firstAddr = addrsElem.getElementsByTagName('address')[0];
var addrText = fistAddr.firstChild;
var addrValue = addrText.nodeValue;

Parsing JSON Response

function myHandler() {
if (request.readyState == 4) {
var card = eval('(' + request.responseText + ')');
addrField.value = card.addresses[0].value;

JSON Security Vulnerability:

a) If the data and the entire JavaScript environment is not within the control of a single trusted source.
b) If the data is itself not trusted, for example, it may be subject to malicious JavaScript code injection attacks; unless some additional means is used to validate the data first.

How to avoid this ?

By using 1 of the 3 options listed here:

1) The RFC that defines JSON (RFC 4627) suggests using the following code to validate JSON before using “eval”:

var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test( text.replace(/"(\\.|[^"\\])*"/g, ''))) && eval('(' + text + ')');

2) A new function, parseJSON(), has been proposed
-Safer alternative to eval, as it is specifically intended to process JSON data and not JavaScript.

3)Native JSON encoding/decoding
-Faster compared to the JavaScript libraries
-Supported in IE8, FF3.5, Chrome,….etc.