Update on “Captcha” code

Kuldeep has been working on the captcha code making it a little more hard to guess. I will be updating on that here as soon as we come up with a final solution. For the moment I have the sample to show:

Captcha

Leave a Comment

The First “Servlet”

The first step towards the real world of programming was to write a servlet that runs on the IBM Websphere application server and communicates with the database server from within it’s code. The sample servlet I am going to discuss here does only one basic thing it communicates with the database server , executes a SELECT query on a particular table in the database and prints the results (all the rows fetched) onto the web-browser. I do all my management/coding from within the eclipse so I will be showing some nice screenshots of the environment (taken while I was working in it).

First of all I would like to remind myself that in order to communicate to the database I need to have the database pool setup in the Application server. That I did in the last post. Well some modifications need to be done to it now as my database server has been shifted from ‘localhost’ to a separate machine ‘192.168.1.4’. In order to do that just open up the administrative console of the IBM Websphere application server and from Servers -> Database Pool edit the pool ‘dwDatasource’. Two things needed to be changed in that:

1) Username: Administrator, Password: secret
2) JDBC URL: jdbc:db2://192.168.1.4:50000/SAMPLE

Then I saved the new settings and logged out of the administrative console. The logic (Step-by-step way) on how to connect to a database via a servlet (as explained here) is:

How stuff works

Note here that I can open/use the administrative console from within the eclipse IDE using the internal web browser provided by eclipse itself. So really no need to go and open FF (firefox). For the sake of convenience here I am pasting the database pool deployment plan (in xml):


<?xml version="1.0" encoding="UTF-8"?>
<connector xmlns="http://geronimo.apache.org/xml/ns/j2ee/connector-1.1"&gt;
<dep:environment xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.1"&gt;
<dep:moduleId>
<dep:groupId>console.dbpool</dep:groupId>
<dep:artifactId>test</dep:artifactId>
<dep:version>1.0</dep:version>
<dep:type>rar</dep:type>
</dep:moduleId>
<dep:dependencies>
<dep:dependency>
<dep:groupId>com.ibm.db2</dep:groupId>
<dep:artifactId>db2jcc</dep:artifactId>
<dep:version>9.1</dep:version>
<dep:type>jar</dep:type>
</dep:dependency>
<dep:dependency>
<dep:groupId>com.ibm.db2</dep:groupId>
<dep:artifactId>db2jcc_license_cu</dep:artifactId>
<dep:version>9.1</dep:version>
<dep:type>jar</dep:type>
</dep:dependency>
</dep:dependencies>
</dep:environment>
<resourceadapter>
<outbound-resourceadapter>
<connection-definition>
<connectionfactory-interface>javax.sql.DataSource</connectionfactory-interface>
<connectiondefinition-instance>
<name>test</name>
<config-property-setting name="Password">secret</config-property-setting>
<config-property-setting name="Driver">com.ibm.db2.jcc.DB2Driver</config-property-setting>
<config-property-setting name="UserName">Administrator</config-property-setting>
<config-property-setting name="ConnectionURL">jdbc:db2://192.168.1.4:50000/SAMPLE</config-property-setting>
<connectionmanager>
<local-transaction/>
<single-pool>
<max-size>10</max-size>
<min-size>0</min-size>
<match-one/>
</single-pool>
</connectionmanager>
</connectiondefinition-instance>
</connection-definition>
</outbound-resourceadapter>
</resourceadapter>
</connector>

After doing the above changes I also modified the database connection I had in the database explorer in eclipse. I selected the database connection right clicked on it and clicked on ‘Edit…’. Same stuff needs to be modified here too (see above).

Well Test connection worked for me and I finialized the settings. And re-connected to the database from within the database explorer. Now was the time to create a new table within the ‘DEEPENDRA’ schema (I have).

Database Explorer under Eclipse

In the above picture right clicking on Tables (selected) and selecting New -> With SQL Editor. Inside the SQL Editor writing the CREATE command:


CREATE TABLE EGUSERS (
NAME CHAR(30) NOT NULL,
AGE CHAR(2),
PRIMARY KEY(NAME)
);

After writing the above command right click anywhere on the text and select the option in the popup menu ‘Run SQL’. This will run the above SQL on the database server and will result in a new table EGUSERS within the DEEPENDRA schema. Finally it was time to insert some sample records into the table. Using the same SQL Editor (delete the CREATE SQL statement):


INSERT INTO DEEPENDRA.EGUSERS VALUES ('DEEPENDRA SINGH', '24');
INSERT INTO DEEPENDRA.EGUSERS VALUES ('KULDEEP SINGH SOLANKI' ,'23');
INSERT INTO DEEPENDRA.EGUSERS VALUES ('GAJE SINGH BHATI' , '22');
INSERT INTO DEEPENDRA.EGUSERS VALUES ('NISHANT CHOUHAN', '23');

After this right clicking again anywhere within the text and selecting ‘Run SQL’ this will insert 4 records into the DEEPENDRA.EGUSERS database table. Now was the time to create the servlet that will query this table. In order to do that I did the following from within the same eclipse environment (J2EE prespective was on):

File -> New -> Project -> Web -> Dynamic Web Project
Project Name: dwapp
Finish.

This created a ‘dwapp’ project for me. In order to get access to the database from within the servlet I had to modify the deployment plan for the Application server that existed in the WebContent/WEB-INF/ directory of my project. The files I modified were

web.xml
geronimo-web.xml

Note that it’s better to modify the xml source directly instead of using the gui to modify things for you as there are some problems with that at the moment (found this at the IBM forums). See the below picture on how to select the ‘Source’ when you open any of the deployment xml.

Selecting Source view

I am pasting my files here with the stuff highlighted which I modified/wrote. First in the row is ‘web.xml’


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" 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">
<display-name>
dwapp</display-name>
<servlet>
<description>
</description>
<display-name>
Testx</display-name>
<servlet-name>Testx</servlet-name>
<servlet-class>
Testx</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Testx</servlet-name>
<url-pattern>/Testx</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<resource-ref>
<res-ref-name>jdbc/DataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

</web-app>

Next is the geronimo-web.xml:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://geronimo.apache.org/xml/ns/j2ee/web-1.1" xmlns:nam="http://geronimo.apache.org/xml/ns/naming-1.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-1.1" xmlns:sys="http://geronimo.apache.org/xml/ns/deployment-1.1">
<sys:environment>
<sys:moduleId>
<sys:groupId>default</sys:groupId>
<sys:artifactId>dwapp</sys:artifactId>
<sys:version>1.0</sys:version>
<sys:type>car</sys:type>
</sys:moduleId>
<sys:dependencies>
<sys:dependency>
<sys:groupId>console.dbpool</sys:groupId>
<sys:artifactId>dwDatasource</sys:artifactId>
</sys:dependency>
</sys:dependencies>

</sys:environment>
<context-root>/dwapp</context-root>
<nam:resource-ref>
<nam:ref-name>jdbc/DataSource</nam:ref-name>
<nam:resource-link>dwDatasource</nam:resource-link>
</nam:resource-ref>

</web-app>

After modifying the above deployment plan it was time to write the real code that will communicate with the database. But before I tell you the code it’s a good time to explain a little about the above stuff we modified in the deployment plan.
Common Questions here are:

a) What is the deployment plan ?
b) Why do I need to modify it ?
c) What are the possible ways I can modify the above files (writing xml, using gui to write the xml for me) ?

It’s possible that you come up with some different set of questions, if so and you are not finding the solution to your question just drop me a comment line on this post and I will try to answer you. So coming to the answers of the above questions

http://cwiki.apache.org/GMOxDOC11/deployment-plans.html

Yes the simple answer I found to all of the questions regarding deployment plans in J2EE/geronimo was the above link. Please go through that link once and you will find answers to almost all of your questions regarding what exactly is web.xml and geronimo-web.xml and what meaning does those custom xml tags holds. I am still reading (haven’t finished yet) that topic.

So now comes the servlet code. Before writing the servlet class we need to import some classes which we will be utilizing. They are:


import java.io.PrintWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

If you want to know more about the above classes just hover the mouse over the class name or the package.classname and eclipse will show you the purpose of the class (press F2 to show the complete detail).

The class definition looks like this


public class Testx extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
public static final long serialVersionUID=0;
public Testx() {
super();
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

After the servlet comes into the memory (init() is called, not necessary to write if you extend javax.servlet.http.HttpServlet) controlled is transferred to service(). So our code will be written inside the service() method.

The first bits of the code will be some objects declaration.


DataSource dsource = null;
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
PrintWriter out = response.getWriter();

The important declaration here is the DataSource object creation. Most of the programs I have seen so far use DriverManager class to access the database but reading through the IBM website I found that it’s better to use DataSource objects if I need portability across databases.

The important declaration here is the DataSource object creation. Most of the programs I have seen so far use DriverManager class to access the database but reading through the IBM website I found that it’s better to use DataSource objects if I need portability across databases.

The next step was to get the connection and execute the query. That is done using the InitialContext.


InitialContext context = new InitialContext();
dsource = (DataSource) context.lookup("java:comp/env/jdbc/DataSource");
conn = dsource.getConnection();
stmt = conn.createStatement();
rset = stmt.executeQuery("SELECT * FROM DEEPENDRA.EGUSERS");

The result of the query (all rows of EGUSERS) will come into the ResultSet object ‘rset’. So now I looped across the rset as shown below to get the required data:


while(rset.next())
{
out.println("<TR>");
out.println("<TD>" + rset.getString("NAME") + "</TD>");
out.println("<TD>" + rset.getString("AGE") + "</TD>");
out.println("</TR>");
}

Finally all the objects are manually closed.


rset.close();
stmt.close();
conn.close();

Note that while executing the above code there can be errors that are handled via NamingException and SQLException catcher’s. Basically the above code is written in try { } block. For complete source code of the java file go here.

Output of the Servlet

Leave a Comment

Installation ‘wows’ in Linux

During the installation of the softwares I remember no difficulty that I faced off. The sequence of installation was simple. First I installed the IBM provided JAVA (was in a rpm). Then I installed the websphere community edition (simply executing the .bin file). And then I installed DB2 (extracting the archive and running exp/disk1/db2setup). During the DB2 setup I did created the sample database.

Finally it was time to install eclipse. Truely speaking it was not a installation just extracting the archive and running the eclipse from within the directory that got extracted. Note that (in Linux) DB2 installation created some special users for running the database related services. Most important of them was ‘db2inst1’. So I decided to use this user as the one from which I will do all the development. During the installation of DB2 in Windows I found that it provides option to select the local system account as the one from which it will run the DB2 service. So one can use that too (if using windows). I provided the necessary rights to ‘db2inst1’ so that it can do the Starting/Stoping/re-starting of the application server (which will be needed later).

Within eclipse I selected first of all the J2EE prespective. And went to Help->Software Update->Find and Install. From within the wizard in the first step I selected the option ‘Search for new feature to install’. Now in the second step I added a new Remote site with the following information:

Name: Eclipse WTP adapter

URL: http://download.boulder.ibm.com/ibmdl/pub/software/websphere/wasce/updates/

This is basically a plugin for eclipse that will be used to tell eclipse about our application server that is IBM Websphere community edition. So that we can manipulate the application server from within the eclipse environment and deploy/test our application from within eclipse itself. By default eclipse doesn’t have plugin for WASCE so this step is needed.

After this finally I clicked on Finish and it downloaded all the required plugin files and asked me to restart eclipse to load the new plugin settings. After doing so I added a new view to my existing prespective (J2EE prespective) that was the ‘Servers’. From within that view (by right clicking) I added a new Server. The whole thing was wizard based where I just needed to select the right version of the application server and doing nothing else (default settings were okay).

That added the application server (WASCE) into the Servers view. Right clicking the server and clicking on Start , started the server.¬† Now was the time to tell the application server something about the database we will be going to use (that is DB2). This is done by creating a database pool from within the administrative console of the application server. Administrative console can be started from within eclipse itself. Just right click on the server shown in the servers view and select ‘Launch Community edition console’. It will load the web console within eclipse itself. Otherwise just point your web-browser to the following URL:http://localhost:8080/console/portal/welcome

Providing username:system and password:manager (these are the default settings). Now from within this administrative console we go to Services -> Database Pools. And select Creation of a new database pool ‘Using Geronimo database pool wizard’. The following settings I gave (using the one given in a kickstart_java_apps tutorial).

Name of Database Pool: dwDatasource

Database Type: DB2

JDBC Driver Class: com.ibm.db2.jcc.DB2Driver

Driver JAR: com.ibm.db2/db2jcc/9.1/jar, com.ibm.db2/db2jcc_license_cu/9.1/jar (ctrl key for multiple select)

DB User name: db2inst1 (maybe different for your setup)

DB Password: secret (maybe different for your setup)

Port: 50000 (actually mapped in /etc/services)

Database: SAMPLE

Host: localhost (for the time being I have only one system)

JDBC Connect URL: jdbc:db2://localhost:50000/SAMPLE

We can use the default values for all the other settings now. So finally you can test the connection by click on the Test connection button and if the connection is sucessfull  you can just Deploy the pool. As soon as you deploy the pool the application server knows how to communicate to the database.  Now you can logout from the administrative console of WASCE.

Next I added the database to eclipse environment. So that I can manage the database from within the eclipse IDE. Just clicked on Window -> Show View -> Database Explorer. Right click on the connection and select New Connection. Within the wizard (during step 1) filled in the following settings:

Database Manager: DB2 UDB V9.1

JDBC Driver: Other

Database: SAMPLE

JDBC Driver Class: com.ibm.db2.jcc.DB2Driver

Class Location: /home/db2inst1/sqllib/java/db2jcc.jar:/home/db2inst1/sqllib/java/db2jcc_license_cu.jar (can be different for your setup)

Connection URL: jdbc:db2://localhost:50000/SAMPLE

UserID: db2inst1 (can be different for your setup)

Password: secret (can be different for your setup)

Click on Finish finally and the database connection shows up in the database explorer. Now I can connect to the database anytime from within the eclipse environment (the database service should be running ‘db2start’) and manipulate the database easily. I just played around with these stuff a little bit from within eclipse to get hold of the eclipse IDE.

This much for now I guess probably by today evening I will be writing how I wrote my first JAVA servlet that used all these stuff discussed in this article, together and did something useful.

Leave a Comment

The Start

Today I decided to download all the softwares by myself as the college authorities had older versions of the softwares. My first target were software packages for Linux platform.After alot of downloading/deleting/re-downloading I got the necessary packages. Here are the name of the files I downloaded:

db2exc_912_LNX_x86.tar.gz
wasce_ibm150sdk_setup-1.1.0.2-ia32linux.tar
wasce_samples-1.1.0.1.zip
wtp-all-in-one-sdk-R-1.5.4-linux-gtk.tar.gz

 

The first one is the IBM DB2 setup, second one is the IBM Websphere Community edition, third one contains some example J2EE codes (will be pretty helpful) and the last one is Eclipse IDE having all the required plugins needed for the project.

 

I found the last package after alot of headache. First I downloaded Eclipse from it’s own website. The version was 3.3 but when I used it I got alot of problems during downloading/installing of the WTP Connector for Websphere. After some research on IBM forums I found that I had to download this wtp-all-in-one-sdk (huge 200MB approx) which have all the required plugins I needed. After downloading this package I was able to install the Connector stuff from within Eclipse. So the version of Eclipse currently stands at 3.2.2.

 

The sample walk-through provided by IBM on how to install/configure all the required softwares was for windows so had to do little tweaks everywhere to get the things done on Linux. I am using Fedora 7 for this project and everything have been installed perfectly (afaik).

 

Now the other task was to get the same packages for windows which I did after some time (after testing things on Linux). The packages for windows are:

 

db2exc_912_WIN_x86.zip
wasce_ibm150sdk_setup-1.1.0.2-ia32win.zip
wasce_samples-1.1.0.1.zip
wtp-all-in-one-sdk-R-1.5.4-win32.zip

 

Haven’t yet tested the software and there configuration on Windows as I don’t have at the moment a Windows XP SP2 High end machine (having at-least 1 GB RAM). But hope that things will work out of box as there is a well described guide for the same platform provided by IBM.

 

Two nights we have spent so far discussing the various aspects of the projects specially the requirement analysis, services we are going to provide. Lot of ideas coming out of some great minds of CSE MBM.

 

So overall speaking it really doesn’t matter whether we could complete this project or not what really matters to us is how much we learn from this.

ScreenShot Files

 

 

Leave a Comment