Wednesday, 10 December 2008

A Dynamic Web Project (Part III)

The object of this exercise is to create a Dynamic Web Project in Eclipse and deploy it to your local Apache Tomcat server and then to an Apache Tomcat server running in a VirtualBox Ubuntu guest.

The application will contain a simple index.html file, a simple index.jsp file and two servlets DBConnect and JNDIConnectDB. The first servlet will create and connect to a database directly using sql commands. The second servlet will connect to a database using a configured JNDI entry in Apache Tomcat.

Create a simple servlet


Right click on the source folder in the project and create a new servlet as follows:

Java Resources: src (right-click)
new -> other -> web -> servlet
next

set the following in the Create Servlet window:

java package: servlets
class name: JNDIConnectDB

and click next to navigate to the next screen in the wizard.
In the URL Mappings window, click on /JNDIConnectDB and click the edit button

URL Mappings
/JNDIConnectDB
Edit

change the pattern from /JNDIConnectDB to /servlet/JNDIConnectDB

/JNDIConnectDB (change to) /servlet/JNDIConnectDB

click ok and then click finish

ok
finish

Enter the following code into JNDIConnectDB.java

package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
* Servlet implementation class DBConnect
*/
public class JNDIConnectDB extends HttpServlet
{
private static final long serialVersionUID = 1L;

private static String driver = "org.apache.derby.jdbc.ClientDriver";
private static String protocol = "jdbc:derby://localhost:1527/";
private static String dbName = "mydb";

private Statement s;

/**
* @see HttpServlet#HttpServlet()
*/
public JNDIConnectDB()
{
super();
// TODO Auto-generated constructor stub
}

private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
PrintWriter out = response.getWriter();

Context ctx = new InitialContext( );
DataSource ds = (DataSource)
ctx.lookup("java:comp/env/jdbc/myDB");
Connection conn = ds.getConnection( );


Properties props = new Properties();

String create = request.getParameter("create");

s = conn.createStatement();

if(create!=null && create.equals("true"))
{
execute("DROP TABLE test");
execute("CREATE TABLE test (id INTEGER NOT NULL,name VARCHAR(32) NOT NULL)");
execute("ALTER TABLE test ADD PRIMARY KEY (id)");
execute("INSERT INTO test(id,name) VALUES(1,'john')");
execute("INSERT INTO test(id,name) VALUES(2,'richard')");
}

ResultSet rs = s.executeQuery("select * from test");

out.println("<staff>");

while(rs.next())
{
ResultSetMetaData rsmd = rs.getMetaData();

out.println("<employee>");

for(int i=1;i<=rsmd.getColumnCount();i++)
{
String colName = rsmd.getColumnName(i);

out.println("<"+colName+">");
out.println(rs.getObject(i));
out.println("</"+colName+">");
}

out.println("</employee>");
}

out.println("</staff>");

conn.close( );
}
catch (SQLException e)
{
throw new ServletException(e);
}
catch (NamingException e)
{
throw new ServletException(e);
}
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
process(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
process(request, response);
}

private void execute(String query)
{
try
{
s.execute(query);
System.out.println("executed: "+query);
}
catch(SQLException e)
{
System.err.println(query);
System.err.println(e.getMessage());
}
}

}

Create a context.xml file in your WebContent/META-INF folder by right-clicking on META-INF and selecting new xml file as follows:

WebContent/META-INF (right-click on META-INF)
new -> other -> xml -> xml
File name: context.xml
finish

click finish to close the popup window and then enter the following into the context.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource
name="jdbc/myDB"
type="javax.sql.DataSource"
auth="Container"
username="john"
password="password"
driverClassName="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/mydb"
maxActive="8"
/>
</Context>

Start the Server and Test the Servlet


First of all make certain that your Derby database is running (see earlier blog entries).

Right click on the project (Tomcat1) and click run on server

project (Tomcat1) - (right click)
run on server

The server will start.

Now open your browser and navigate to the servlet by entering the following url into your browser:

http://localhost:8080/Tomcat1/servlet/JNDIConnectDB

The output you should see in your browser window is below:

<staff>
<employee>
<ID>
1
</ID>
<NAME>
john
</NAME>
</employee>
<employee>
<ID>
2
</ID>
<NAME>
richard
</NAME>
</employee>
</staff>

A Dynamic Web Project (part II)

The object of this exercise is to create a Dynamic Web Project in Eclipse and deploy it to your local Apache Tomcat server and then to an Apache Tomcat server running in a VirtualBox Ubuntu guest.

The application will contain a simple index.html file, a simple index.jsp file and two servlets DBConnect and JNDIConnectDB. The first servlet will create and connect to a database directly using sql commands. The second servlet will connect to a database using a configured JNDI entry in Apache Tomcat.

Create a simple servlet


Right click on the source folder in the project and create a new servlet as follows:

Java Resources: src (right-click)
new -> other -> web -> servlet
next

set the following in the Create Servlet window:

java package: servlets
class name: DBConnect

and click next to navigate to the next screen in the wizard.
In the URL Mappings window, click on /DBConnect and click the edit button

URL Mappings
/DBConnect
Edit

change the pattern from /DBConnect to /servlet/DBConnect

/DBConnect (change to) /servlet/DBConnect

click ok and then click finish

ok
finish

Enter the following code into DBConnect.java

package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class DBConnect
*/
public class DBConnect extends HttpServlet
{
private static final long serialVersionUID = 1L;

private static String driver = "org.apache.derby.jdbc.ClientDriver";
private static String protocol = "jdbc:derby://localhost:1527/";
private static String dbName = "mydb";

private Statement s;

private static boolean driverloaded = false;

/**
* @see HttpServlet#HttpServlet()
*/
public DBConnect()
{
super();
// TODO Auto-generated constructor stub
}

private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
PrintWriter out = response.getWriter();

if(!driverloaded)
{
Class.forName(driver);
driverloaded=true;
}

Properties props = new Properties();

String user = request.getParameter("user");
String password = request.getParameter("password");
String create = request.getParameter("create");

if(user==null) user = "john";
if(password==null) password = "password";

props.put("user", user);
props.put("password", password);

Connection conn = DriverManager.getConnection(protocol + dbName + ";create=true", props);
System.out.println("Connected to and created database " + dbName);

s = conn.createStatement();

if(create!=null && create.equals("true"))
{
execute("DROP TABLE test");
execute("CREATE TABLE test (id INTEGER NOT NULL,name VARCHAR(32) NOT NULL)");
execute("ALTER TABLE test ADD PRIMARY KEY (id)");
execute("INSERT INTO test(id,name) VALUES(1,'john')");
execute("INSERT INTO test(id,name) VALUES(2,'richard')");
}

ResultSet rs = s.executeQuery("select * from test");

out.println("<staff>");

while(rs.next())
{
ResultSetMetaData rsmd = rs.getMetaData();

out.println("<employee>");

for(int i=1;i<=rsmd.getColumnCount();i++)
{
String colName = rsmd.getColumnName(i);

out.println("<"+colName+">");
out.println(rs.getObject(i));
out.println("</"+colName+">");
}

out.println("</employee>");
}

out.println("</staff>");
}
catch (SQLException e)
{
throw new ServletException(e);
}
catch (ClassNotFoundException e)
{
throw new ServletException(e);
}
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
process(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
process(request, response);
}

private void execute(String query)
{
try
{
s.execute(query);
System.out.println("executed: "+query);
}
catch(SQLException e)
{
System.err.println(query);
System.err.println(e.getMessage());
}
}

}


Start the Server and Test the Servlet


First of all make certain that your Derby database is running (see earlier blog entries).

Right click on the project (Tomcat1) and click run on server

project (Tomcat1) - (right click)
run on server

The server will start.

Now open your browser and navigate to the servlet by entering the following url into your browser:

http://localhost:8080/Tomcat1/servlet/DBConnect

The output you should see in your browser window is below:

<staff>
<employee>
<ID>
1
</ID>
<NAME>
john
</NAME>
</employee>
<employee>
<ID>
2
</ID>
<NAME>
richard
</NAME>
</employee>
</staff>

A Dynamic Web Project (part I)

The object of this exercise is to create a Dynamic Web Project in Eclipse and deploy it to your local Apache Tomcat server and then to an Apache Tomcat server running in a VirtualBox Ubuntu guest.

The application will contain a simple index.html file, a simple index.jsp file and two servlets DBConnect and JNDIConnectDB. The first servlet will create and connect to a database directly using sql commands. The second servlet will connect to a database using a configured JNDI entry in Apache Tomcat.

Step 1 - Create the Dynamic Web Project


Open Eclipse and create a new Dynamic Web Project

From the toolbar: new Project -> Web -> Dynamic Web Project

Enter a name for your project:

Tomcat1

select your locally installed Apache Tomcat server

apache-tomcat-6.0.18

as your Target Runtime and click

finish

Create index.html


Navigate to your project in the project explorer panel - panel to the left - or from the menu select:

window -> show view -> navigator

Right-click on your WebContent folder and select:

WebContent (right click)
new -> other -> web -> html
click next

Type index as the filename. The suffix of .html will be added automatically. click the finish button

index
finish

Enter the following into the main panel:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>index.html</h1>
</body>
</html>

save the file.

Create index.jsp


Navigate to your project in the project explorer panel - panel to the left - or from the menu select:

window -> show view -> navigator

Right-click on your WebContent folder and select:

WebContent (right click)
new -> other -> web -> jsp
click next

Type index as the filename. The suffix of .jsp will be added automatically. click the finish button

index
finish

Enter the following into the main panel:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>index.jsp</h1>
</body>
</html>

save the file.

Launch the Server


Right-click on index.html and select and launch the page on the server as follows:

index.html (right click)
run as -> run on server

Select your tomcat server and click finish

apache-tomcat-6.0.18
finish

Your web page will launch in your browser.

To view your jsp file, change index.html in the browser to index.jsp

Install PostgreSQL in Ubuntu (VirtualBox)

Download and Install PostgresSQL


Open your browser and navigate to http://postgresql.org. Here you can download the latest .bin file (e.g. postgresql-8.3.5.1-linux.bin)

Now install the image by opening a Terminal session and entering the following:

cd Desktop
chmod 755 postgresql-8.3.5.1-linux.bin
sudo ./postgresql-8.3.5.1-linux.bin

run with the defaults - so leave the installation directory as the default /opt/PostgreSQL/8.3 and the port as the default port 5432.
When prompted, agree to launch stackbuilder and from the popup window
select PostgresSQL on default port 5432 as the instance to work with.

Now select JDBC database drivers and click next. Leave the temporary folder as the default of /tmp folder.

The jdbc drivers will be installed into /opt/PostgresSQL/pgJDBC

Install Apache HTTPD in Ubuntu (VirtualBox)

In your Ubuntu virtual server, open your web browser and download the latest source (tar.gz) image from http.apache.org.

Open a terminal session and install apache as follows:

sudo cp httpd*gz /opt
cd /opt
sudo bash
gunzip httpd*
tar xvf httpd*.tar
rm -f httpd*.tar

cd httpd*
./configure --prefix=/opt/apache2
make
make install

Now you can start the server with

sudo /opt/apache2/bin/apachectl -k start

and stop the server with

sudo /usr/apache2/bin/apachectl -k stop

Check the server is running by opening your browser and navigating to:

http://localhost

For further information, have a look at

http:/httpd.apache.org/docs/2.2/install.html

Install Ant in Ubuntu (VirtualBox)

In a terminal session enter the following:

sudo apt-get install ant

Install Apache Tomcat in Ubuntu (VirtualBox)

Start your Ubuntu virtualBox server and using firefox download the latest tomcat image from http://tomcat.apache.org and install it as follows:

Install and Configure Tomcat



  • open firefox and navigate to tomcat.apache.org

  • From the Download menu, select Tomcat 6.x

  • From Binary Distributions (Core) select the tar.gz image

  • This will download the file apache-tomcat-6.0.18.tar.gz onto your Desktop

  • Open a Terminal window (Applications->Accessories->Terminal) and perform the following:

    cd Desktop
    sudo mv apache-tomcat-6.0.18.tar.gz /opt
    cd /opt
    sudo gunzip apache-tomcat-6.0.1.18.tar
    sudo tar xvf apache-tomcat-6.0.18.tar
    sudo rm -f apache-tomcat-6.0.18.tar


  • Create a tomcat user and change the owner of all the extracted files to tomcat as follows:

    sudo useradd -g 46 -s /sbin/nologin -d /opt/tomcat/temp tomcat
    sudo chown -R tomcat apache-tomcat-6.0.1.18


  • Edit the /etc/profile to set the CATALINA_HOME environment variable as follows:

    sudo vi /etc/profile
    add export CATALINA_HOME=/opt/apache-tomcat-6.0.18


  • create/edit the setenv.sh tomcat file as follows:

    vi /opt/apache-tomcat-6.0.18/bin/setenv.sh


  • add the following lines to the setenv.sh file

    export CATALINA_HOME=/opt/apache-tomcat-6.0.18
    export JAVA_HOME=/usr/jdk1.6.0_10


  • reboot your server


Create scripts to start and stop the Server


Create a bin sub-directory in your home directory and add the scripts startServer and stopServer as follows:

cd
mkdir bin
cd bin

create the startServer script as follows:

vi startServer

add the following line to startServer

sudo -u tomcat /opt/apache-tomcat-6.0.18/bin/startup.sh

Now create the stopServer script as follows:

vi stopServer

add the following line to stopServer

sudo -u tomcat /opt/apache-tomcat-6.0.18/bin/shutdown.sh

Now set the scripts to executables as follows:

chmod 755 startServer stopServer

Start and Verify that the Tomcat Server is running


In your terminal session enter the following:

startServer

Open firefox and navigate to the following url

http://localhost:8080

Install Java in Ubuntu (VirtualBox)

Start your VirtualBox Ubuntu guest and log in. Open firefox and download the latest JavaSE JDK from http://java.sun.com and install as follows:

  • From http://java.sun.com click on downloads->JavaSE and select the latest jdk (JDK6-update10)

  • Select the linux -> multi-language and download the .bin file

  • The file will download onto your desktop

  • Open a terminal session (Applications->Accessories->Terminal) and enter cd Desktop

  • move the downloaded file to your destination directory (e.g /opt)
    sudo mv jdk-6u10-linux-i586.bin /opt

  • cd /opt

  • sudo chmod 700 jdk-6u10-linux-i586.bin

  • sudo ./jdk-6u10-linux-i586.bin

  • type yes to accept the license agreement and install java with all the defaults.

Now we need to modify our system variables to know where Java is. There are a number of ways to do this - one option is as follows:

  • sudo vi /etc/profile

  • add the following entries to the end of the /etc/profile file:

    export JAVA_HOME=/usr/jdk1.6.0_10
    export PATH=$JAVA_HOME/bin:$PATH



Now reboot your server.

Create Ubuntu Shared Folder in Virtual Box

This article assumes that your are running VirtualBox on a Mac and are running Ubuntu as the guest in VirtualBox (the instructions are similar for VirtualBox running on Windows).

  • Shutdown your VirtualBox Ubuntu session if it is running

  • In your host operating create the folder you want to share - e.g. ubuntuShared

  • From the VirtualBox control panel, click on your Ubuntu Virtual Machine

  • In the right hand panel, click shared folders

  • A window will open to manage shared folders. Click the add folder icon on the right hand side

  • navigate to the folder you created in your host operating system and click choose

  • click ok to close the navigator window

  • ensure that your selected folder is highlighted in the shared folder panel and click ok

  • Start your Ubuntu session and log in

  • Open a Terminal session (Applications->Accessories->Terminal)

  • Create a mount-point directory for your Shared Folder - e.g. sudo mkdir /media/windows-shared

  • Mount your shared folder over your newly created directory - e.g. sudo mount.vboxsf ubuntuShared /media/windows-share


Now your shared folder is mounted and you can access it. Note that by doing this manually, you will need to manually mount your shared folder every time the server restarts.


Install VirtualBox Guest Additions for Ubuntu

This article assumes you already have Ubuntu already installed and running in VirtualBox and have logged into your Ubuntu session.

  • From the Devices menu of your running VirtualBox session select Install Guest Additions...

  • Open a new Terminal window in Ubuntu (Applications->Accessories->Terminal)

  • in the Terminal window type cd /media/cdrom

  • type sudo ./VBoxLinuxAdditions-x86.run

  • enter your password

  • restart Ubuntu by selecting System->Quit->Restart

Install Ubuntu as VirtualBox Guest on a Mac

This note assumes you have already installed the latest version of VirtualBox from http://virtualbox.org/.

Either use an Ubuntu installation CD, or download the latest Ubuntu iso image from http://www.ubuntu.com/.

The steps are as follows:

Create a Virtual Hard-Drive for Ubuntu



  • start VirtualBox

  • Select New from the toolbar

  • Enter a name for your session in the Name field - e.g. Ubuntu

  • select Ubuntu from the drop-down list as the OS Type

  • set the Base Memory Size to a realistic figure - I set it to just 1GB (1000 MB) and that works fine

  • For the Virtual Hard Disk, click on New

  • Select Fixed-size image

  • Select the folder you want to store your disk image in by clicking on the yellow folder

  • select a name for the Virtual Disk - e.g. UbuntuDisk

  • set the image size to something realistic - e.g. 12.00GB

  • click Finish to create the fixed-size hard disk



Boot the Virtual Hard-Drive


Once the drive has been created, install Ubuntu

  • Ensure that your new drive image is selected at he Primary Master and click Next

  • Click finish



Install Ubuntu


Ubuntu will now appear as a powered-off image in the main VirtualBox console.

  • Click on the Ubuntu (powered off) image

  • Click on CD/DVD-ROM in the right panel


A new window will open allowing you to Mount a CD/DVD Drive.

  • Check the Mount CD/DVD Drive check-box

  • If you are installing from a CD/DVD click the Host CD/DVD Drive radio button and select you drive from the drop-down list

  • If you are installing from an ISO image, click the ISO Image File radio button and navigate to your downloaded ISO Image File

Starting Derby Using Java Code


package net.tplusplus.repository.derby.sql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class StartServer
{
public static final String DERBY_PATH = "/Applications/db-derby-10.4.2.0-bin";

public static void main(String[] args) throws IOException
{
String startupPath = DERBY_PATH + "/bin/startNetworkServer";

String[] envp = new String[]
{
"DERBY_HOME=/Applications/db-derby-10.4.2.0-bin"
};

//System.setProperties(props);

Process p = Runtime.getRuntime().exec(startupPath,envp);

BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

// read the output from the command

String line;

System.out.println("Here is the standard output of the command:\n");

while ((line = stdInput.readLine()) != null)
{
System.out.println(line);
}

// read any errors from the attempted command

System.out.println("Here is the standard error of the command (if any):\n");
while ((line = stdError.readLine()) != null)
{
System.out.println(line);
}

System.exit(0);

}
}

Starting Derby

To create a double-clickable script to start Derby

open the command shell

cd /Applications

edit a script called startDERBY

enter the following


startNetworkServer


chmod +x startDERBY

Installing Derby on a Mac

Download the Derby bin distribution from http://db.apache.org/derby/derby_downloads.html

Extract the archive by double clicking on it.

Move the folder to wherever you want the derby installation to be housed.

Open a command shell and edit .profile

(if the .profile does not exist, create one - this will be picked up next time you log in)

set DERBY_HOME and PATH as follows


export DERBY_HOME=/Applications/db-derby-10.4.2.0-bin
export PATH=$PATH:$DERBY_HOME/bin


note, DERBY_HOME points to wherever you moved the DERBY installation