RSS Feed Subscribe to RSS Feed

 

Setting up multiple instances of Tomcat

With multiple tomcat instances, each can run in its own JVM, have its own configuration and can be started/stopped independently.

One approach to doing this would be to have multiple, full tomcat installations. This article instead details how to install tomcat once (in CATALINA_HOME) but have multiple independent instances (by utilizing CATALINA_BASE). This is a more streamlined approach that makes creating multiple instances easier and also simplifies upgrades/rollbacks of tomcat.

Read more

Tags: , ,

EasyMock

EasyMock is an open source library for creating, and defining the behavior of, mock objects as part of your unit tests. This article describes how to use EasyMock (v3.0), including its record/playback approach, after setting the context with an brief introduction to unit testing in general and the associated need for mock objects.
Read more

Tags: , ,

Hamcrest Matcher

As a follow up to the Hamcrest post I made yesterday, I wanted to post an example of my own Hamcrest matcher implementation. This matcher tests if a string contains a specified number of substrings.
An example usage could be:


    String sql = "select a,b,c from tableA";
    assertThat(sql, hasNumberOfSubstrings(",", 2));

See the source code below. I have been reading up on OSS licenses recently and decided to release this using the same license as Hamcrest – the new BSD license.

I have also attached a jar which includes the associated unit tests, although you will need the hamcrest-unit-test project to compile, which can be downloaded as part of the hamcrest all-in-one jar.
Read more

Tags: , , ,

Hamcrest

Hamcrest is a framework for writing matcher objects. Matchers have a variety of uses, but are particularly useful when writing unit tests. Instead of using JUnit’s assertEquals methods, we use Hamcrest’s assertThat construct with one (or more) of the many Matchers available. For example

    assertTrue(a.equalTo(b));

becomes

    assertThat(a, equalTo(b));

A small change in this example, but Hamcrest’s benefits are many, enabling you to write much more flexible tests that are easier to read and have more meaningful failure messages.
Read more

Tags: , ,

Final day at JavaOne

I posted some notes about my final day at JavaOne to theServerSide. At the moment, currently on the front page. Cool 🙂
http://www.theserverside.com/news/thread.tss?thread_id=60987

Tags:

Singleton implementations

A singleton is a class that is instantiated exactly once (or at least, once per classloader). It is considered to be an anti-pattern by many (including me!) because it makes unit testing difficult. You can’t substitute a mock implementation for a singleton (unless it happens to implement an interface, which I haven’t seen too often). And singletons also make your APIs into liars.

However, if you do want/have to use singletons, this article discusses the best approach.

Read more

Tags:

HelloWorld: JSP -> Servlet

A while ago, I posted a simple HelloWorld Html->Servlet->JSP setup. Even though the html part is unnecessary (a JSP can obviously handle that alone), I deliberately included it as a template for Html/Servlet/JSP interaction. I have used it a bunch of times to get simple Proof of Concept projects up and running, or as a basis to create a simple browser interface to some server side process.

Most of the more recent projects I have used it on however have used straight JSP->Servlet, with no .html file involved. So I am now posting that setup, including some simple JSTL EL and conditional logic.

Read more

Tags: , ,

Selenium talk at SF JUG

I attended another great San Francisco JUG meeting tonight, this time on How to use Selenium with Maven/Ant to automate testing of web apps.

The talk was given by Chris Bedford, from Build Lackey Labs – “Automating the Monkey Work Out and the Quality In!”. Overall, I thought this was a great talk by Chris. He clearly has a huge amount of experience creating automated tests and integrating them with build tools and he gave a well structured, interesting, well delivered presentation. I have posted a copy of Chris’s slides and I think the video will be posted on the SF JUG site at some point, but I have also posted my notes from the presentation below…
Read more

Tags: , , , , ,

Java User Groups and cultivating your career

There is an interesting article here about the importance of User Groups, which links to this one about cultivating your career.
Both definitely worth a read.

Data binding in Spring MVC

Two of the most important tasks carried out by Spring MVC when you submit a form are Data binding and validation.
The following article discusses data binding, including the use of custom PropertyEditors, and some of the options available for registering such editors. Most of the information discussed applies to Spring in general, but its application in Spring MVC is my primary interest.

In a future article I would like to discuss validation including the use of custom error messages.

Note that these notes relate to version 2.5.6 of Spring, the latest production code at time of writing, and depend heavily on the corresponding Spring reference docs.

Read more

Tags: ,

HelloWorld: Html -> Servlet -> JSP

A couple of times recently I have had to setup up some very simple code to display on the client side (browser) some values created on the server side based on basic user input.

This has been part of some prototype/proof-of-concept work. I am posting my basic setup as an example in the form of the ubiquitous HelloWorld app. It uses a Html page to receive user input, which is submitted to a Servlet, processed, and the response displayed in a JSP using EL (Expression Language).

Obviously this could be done in various ways, including just JSPs, but this example acts as a template of Html/Servlet/JSP interaction.

1) Create a Html page called HelloWorld.html




Greeting Setup - Hello Who?



Enter greeting recipient:

2) Create a servlet to receive the user input
HelloWorldServlet.java


package com.helloworld;

import java.io.IOException;

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

public class HelloWorldServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		//get inputs		
		String msg = req.getParameter("msg");
		
		//any additional processing can be done here
		
		//set outputs
		req.setAttribute("msg", msg);
		
		//forward to jsp
		req.getRequestDispatcher("/HelloWorld.jsp").forward(req, res); 
	} 

}

3) Create a JSP to display the response
HelloWorld.jsp:


Hello ${msg}

4) Create the web application’s deployment descriptor file:
web.xml




	
		HelloWorld.html
	
	
	
		HelloWorldServlet
		com.helloworld.HelloWorldServlet
	
	
	
		HelloWorldServlet
		/HelloWorldServlet
	
	



That’s it.

The easiest way I have found for this kind of development is to create in Eclipse as a Dynamic Web Project (available via the Web Tools Platform that comes with the in the “Eclipse IDE for Java EE Developers” package). When you have carried out the above steps, just right click the project -> Run As -> Run on Server (assuming you have a server like Tomcat or GlassFish setup in Eclipse…).

I have attached the source in a war file.

Tags: , , ,

JUG Meetup: Joshua Bloch (Effective Java)

I had the chance tonight to see Joshua Bloch speak at the Silicon Valley Web JUG meetup down at the Googleplex in Mountain View. I have read and blogged about his great book “Effective Java” – probably the single best book I have read on Java – so it was great to hear him in person. The talk covered a couple of examples from his Java Puzzlers book as well as a discussion on some of the items from the Effective Java book. As expected, he was a great presenter, both insightful and funny.

Tags: , ,

JavaBeans vs Spring beans vs POJOs

The terms JavaBeans, “Spring beans” and POJOs are in widespread use and this article discusses each and the differences between them.

JavaBeans

At a basic level, JavaBeans are simply Java classes which adhere to certain coding conventions. For example, classes that

  1. Have a public default (no argument) constructor
  2. allows access to properties using accessor (getter and setter) methods
  3. Implement java.io.Serializable

More accurately, JavaBeans are classes that adhere to Sun’s JavaBeans spec, first published way back in 1996. A JavaBean was defined as a “software component model” for Java. The idea was that JavaBeans would be reusable software components that could be manipulated visually in a builder tool and that vendors would create and sell JavaBeans that could be composed together into applications by end users. The three most important features of a Java Bean are

  1. the set of properties (named attributes) it exposes
  2. the set of methods it allows other components to call
  3. the set of events it fires (to notify registered listeners of changes)

POJO

POJO is an acronym for Plain Old Java Object. The term was coined by Martin Fowler et. al., as a ‘fancy’ way to describe ordinary Java Objects that do not require a framework to use, nor need to be run in a application server environment. It is often used to distinguish simpler, lightweight Java objects from ‘heavyweight’ code like EJBs. The use of these kind of lightweight objects in programming is described in books such as “POJOs in Action” and advocated by frameworks like Spring.

Spring beans

A Spring bean is basically an object managed by Spring. More specifically, it is an object that is instantiated, configured and otherwise managed by a Spring Framework container. Spring beans are defined in a Spring configuration file (or, more recently, by using annotations), instantiated by the Spring container, and then injected into your application.

The reason Spring managed objects are referred to as beans is because in the very early versions, Spring was intended only for use with JavaBeans. That is no longer the case of course: Spring can manage just about any object, even if it doesn’t have JavaBean type characteristics such as default constructors or mutator methods (getters and setters). None the less, the term ‘Spring beans’ has stuck.

Can Spring beans be POJOs? Yes, and they usually are (although they don’t have to be – e.g. Spring can be used with ‘heavyweight’ Java objects, such as EJBs).
Can Spring beans be JavaBeans? As I have said, yes and again they often are but don’t have to be.

Summary

Although it have been well over 10 years since the JavaBeans spec was first published, it still carries weight and has influence the development of modern frameworks such as Spring. But while Java objects that have default constructor and use accessor methods for private fields may legitimately be called JavaBeans, the whole “reusable software component that can be manipulated visually in a builder tool” concept isn’t particularly popular anymore.

POJOs, however, are everywhere and the a backlash against the complexities for EJBs has resulted in widespread use of ‘lightweight’ Java programming.

Spring beans are objects created and managed by the Spring framework.

None of the 3 terms discussed are mutually exclusive. A Java object can be a JavaBean, a POJO and a Spring bean all at the same time.

Tags: , , ,

Groovy: Cool but slow

I have been learning Groovy recently (as part of Project Euler, a series of Maths programming problems). For the most part, I love it. I particularly like
the easy syntax. Java without the crud!
e.g.

  • System.out.println becomes simply println
  • for (int i-0; i<10; i++) becomes for ( i in 0..9 )
  • Accessor methods are autogenerated and used

Sure, the poor IDE support is a little annoying, especially the lack luster code completion and debugging capabilities, but I am sure it will improve soon (especially with SpringSource on the case).

But then I started to notice some slowness when using it. So, I performed a simple performance comparison and the results shocked me.
I wrote an identical loop in both Java and Groovy (see the code below) which simply loops a million times.

  • The Java version took ~5ms
  • The Groovy version took ~500ms

I was shocked! Could Groovy really be a 100 times slower? I had heard rumors about Groovy being a bit slower than Java, but I hadn't expected it to be this dramatic. Surely this is drastic enough to stop Groovy being used in serious, production quality projects?

I discussed this with a friend who is a Groovy advocate. He made the following points:

1. I was running with an older, slower version of Groovy

This is true. I ran the tests in Eclipse 3.5, with v1 of the Eclipse Groovy plugin, which uses v1.5.7 of the Groovy compiler.
However, when I downloaded the latest version of Groovy (Version: 1.6.3 with JVM: 1.6.0_13) and ran from the command line, it still took the Groovy code ~200 ms. A huge improvement, but still ~40 times slower than Java.

2. It is an artificial, unrealistic test, as these kind of huge loops are not normal in most programs

This is also true. But although artificial, it is still a straight comparison. Also, these kind of loops aren't so unusual in Project Euler type problems (at least in my crude brute force solutions!).

There are also some more detailed Java/Groovy performance test results here and here.

So, overall, I think the performance is a big issue. But not enough to stop me using it for pet projects. I am even going to keep trying to use it for Project Euler - it will be more motivation to avoid the brute force solutions. It is however, enough to stop me using it in any serious production apps.

For the record, here is the exact code I ran:
Java version


		long max = 1000000;		
		long start = Calendar.getInstance().getTimeInMillis();
		for(int i=0;i

Groovy version


		long max = 1000000;		
		long start = Calendar.getInstance().getTimeInMillis();		
		for(int i=0;i

It is also worth pointing out that when I changed the Groovy code to use proper Groovy syntax, as in for (i in 1..1000000) is was substantially faster (although still significantly slower than Java), but I have left it as is, for a apples vs apples comparison.

Tags:

Ant build file to redeploy to Tomcat

Here is an example of an ant file that redeploys a web project to tomat. The neat thing is that as well as creating the war file, it also stops and restarts tomcat, all from ant.
I have found myself rewriting variations of this on a couple of projects recently, so I thought it was worth posting…
(Note it doesn’t include a compile target as I am doing it from my IDE)



	

	
		
			
			
		
	
	
	
		
		
	

	
		
			
			
					
			
		
	 

	
		
			
		
	

	
		    


And here is an example of the associated build.properties file


	tomcat.home=C:/Program Files/Apache/tomcat
	project.name=SampleProjectName
	project.warfilename={project.name}.war
	project.deploywar=${tomcat.home}/webapps/${project.name}.war
	project.deploydir=${tomcat.home}/webapps/${project.name}

Tags: ,