Friday, 6 March 2009

Using TypeLoaders in Fuse to load Objects

The default loader supports String content.

If you want to load objects from the content it is necessary to create a custom TypeLoader.

For example, if we have the following resource file:

testfuse2.resources

TestFuse2.person=Jon,Doe


and a Person POJO defined as follows:

Person.java

public class Person
{
private String firstName;
private String lastName;

public Person(String firstName,String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}

public String toString()
{
return this.getClass().getName()+"[firstName="+firstName+", lastName="+lastName+"]";
}
}


Then we need to create our own typeloader to parse the Strign Jon,Doe to return a Person object.

Our TypeLoader looks like this:

PersonLoader.java

import java.util.Map;
import org.jdesktop.fuse.TypeLoader;

public class PersonLoader extends TypeLoader<Person>
{
@SuppressWarnings("unchecked")
public PersonLoader()
{
super(Person.class);
}

@Override
public Person loadType(String name, String value, Class resolver, Map map)
{
String[] parts = value.split(",");

return new Person(parts[0],parts[1]);
}
}



Now all we need to do, is modify our original code from my last post to register the new typeloader.

TestFuse2.java

import org.jdesktop.fuse.InjectedResource;
import org.jdesktop.fuse.ResourceInjector;
import org.jdesktop.fuse.TypeLoaderFactory;

public class TestFuse2
{
@InjectedResource
private Person person;

public String toString()
{
return person.toString();
}

public static void main(String[] args)
{
ResourceInjector.get().load(TestFuse2.class.getResource("testfuse2.resources"));
TypeLoaderFactory.addTypeLoader(new PersonLoader());

TestFuse2 testFuse2 = new TestFuse2();
ResourceInjector.get().inject(testFuse2);

System.out.println(testFuse2);
}
}

Using Fuse for Dependency Injection in Swing

The fuse project for dependency injection can be found at https://fuse.dev.java.net.

The overview is quite simple and can be found at https://fuse.dev.java.net/gettingstarted.html.

in short, Fuse uses a text file containing resources and values to be injected into the object at run time.

The following code shows a very simple example of how to use fuse:

1: Create the Resource File

create the package test and create the file testfuse.resources in that package.

add the following line to testfuse.resources

TestFuse.name=Jon Doe

When this resource file is applied by fuse, it will inject the value Jon Doe into the member name in the class TestFuse

2: Create the Java code to inject the resources

Create the class TestFuse.java to read the resource file and use fuse to inject the contents.

package test;
import org.jdesktop.fuse.InjectedResource;
import org.jdesktop.fuse.ResourceInjector;

public class TestFuse
{
@InjectedResource
private String name;

public String toString()
{
return this.getClass().getName()+"[name="+name+"]";
}

public static void main(String[] args)
{
ResourceInjector.get().load(TestFuse.class.getResource("testfuse.resources"));

TestFuse testFuse = new TestFuse();
ResourceInjector.get().inject(testFuse);

System.out.println(testFuse);
}
}

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