Tuesday, August 14, 2007

Build a JAR of JARs with Maven2

If you want to create a ZIP or JAR made up of other artifacts, one option is using the maven-dependency-plugin. Here's a quick how-to:

1. Explicitly list the artifacts you want included.


<dependencies>
...
<dependency>
<groupId>javax.sip</groupId>
<artifactId>jain-sip-ri</artifactId>
<version>1.2-2007-07-25</version>
</dependency>
...
</dependencies>


2. Configure the plugin as needed

<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>${project.artifactId}-fetch-deps</id>
<phase>generate-sources</phase>
<goals><goal>copy-dependencies</goal></goals>
<configuration>
<outputDirectory>${project.build.outputDirectory}</outputDirectory>
<stripVersion>true</stripVersion>
<excludeTransitive>true</excludeTransitive>
<excludeArtifactIds>junit</excludeArtifactIds>
</configuration>
</execution>
</executions>
</plugin>
</plugins>

Service Locator an alternative to Dependency Injection?

In my unending quest for knowledge, I read an article explaining Dependency Injection as well as discussing Service Locator as an alternative.

After taking some time to talk about each pattern individually (DI & SL), it's finally time address the real question. Is Service Locator an alternative to Dependency Injection?

The most important aspect of DI is IoC (Inversion of Control). Through DI, you pass control to the consumer of the class. For the sake of argument, let's say you decide to implement Service Locator instead of DI. Now a class gets its resources from the ServiceLocator class and is no longer coupled directly to the resource itself. Assuming your primary goal was IoC, who now controls the resource? Well, the SeriveLocator class. So you've passed control from one class to another. Does that accomplish IoC? No. A consumer of your class still has no control. So what do you do? You implement DI to inject the resource into the ServiceLocator; and what were we trying to accomplish by using Service Locator instead of DI in the first place?

When it comes down to it, they only share one thing in common: the ability to decouple a class from its dependencies. While technology independence is a noble cause, these two patterns offer much more.

Look at it this way. Would you ever tell someone that's looking to buy a corvette that a mini van is an alternative? No. Now, if you're only concerned with getting from point A to point B, the mini van would be a viable alternative. But, who buys a corvette just to get from point A to point B ?

Conclusion
DI offers decoupling with the benefit of IoC. Service Locator should be used to manage services for multiple consumers and abstract away the pain of accessing that service.

Monday, August 13, 2007

Inject a String with Spring 2.0.6 and Maven2

Here's a real quick how-to for injecting a simple String value with Spring 2.0.6.

Configuration File


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="proxyHost" class="java.lang.String">
<constructor-arg>
<value>10.9.5.120</value>
</constructor-arg>
</bean>
</beans>


Java Code

public class stringInjectionExample {
private static final String SPRING_FILE = "sip.xml";
private static final String PROXY_HOST_BEAN_NAME = "proxyHost";

public void init() {
Resource resource = new ClassPathResource(SPRING_FILE);
BeanFactory factory = new XmlBeanFactory(resource);
String proxyHost = (String) factory.getBean(PROXY_HOST_BEAN_NAME);

System.out.println("Using ProxyHost: " + proxyHost);
}
}


Output

Using ProxyHost: 10.9.5.120


pom.xml

...

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>2.0.6</version>
</dependency>
</dependencies>

<repositories>
<repository>
<id>Ibiblio</id>
<name>Maven2 Ibiblio Repository</name>
<url>http://mirrors.ibiblio.org/pub/mirrors/maven2</url>
<layout>default</layout>
</repository>
</repositories>

...

Thursday, August 9, 2007

Service Locator

I mentioned in my last blog entry that I want to discuss the idea of the Service Locator pattern as an alternative to Dependency Injection. However, I first wanted to discuss each pattern individually. So here's what I have to say about Service Locator.

At the root of the Service Locator pattern, the idea is that a single object has access to all the services that your system/component needs. It will handle acquiring, creating, or connecting to those services. In a simpler environment, it may simply be holding references to objects (as compared to performing complex lookups for services in an enterprise environment). With that in mind, how could the Service Locator pattern help us?

Benefit #1
First, let's look at a very simple example. Consider the following:


class SimpleExample {
private MessageGenerator generator;

public simpleExample() {
this.generator = new MessageGeneratorImpl();
}

public void initiateSession() {
Message message = this.generator.createInvite();
this.generator.sendMessage(message);
}
}

What benefit would we see from changing it to user a Service Locator like this?

class ServiceLocator {
private static Map services = new HashMap();

public static void addService(String name, Object service) {
map.put(name, service);
}

public static Object getService(String name) {
return services.get(name);
}
}


class SimpleExample {
public simpleExample() { }

public void initiateSession() {
MessageGenerator generator = ServiceLocator.getService("MessageGenerator");
Message message = generator.createInvite();
generator.sendMessage(message);
}
}

The primary benefit here is that the SimpleExample class is no longer coupled to the implementation of MessageGenerator. The SimpleExample class relies on the ServiceLocator to provide the correct implementation. So, removing a direct dependency between a class and its needed service is one thing the ServiceLocator can accomplish.

Benefit #2
Now, let's think bigger. Consider having 10 classes, each needing to use several of 8 different services in your application. Imagine how messy (and tightly coupled) things would be with each class having a direct dependency on each service it needed.

What would happen if instead we used ServiceLocator to manage access to those 8 services. Well, none of the classes would require direct knowledge of any service. They could simply use a public method on the Service Locator to acquire a service when necessary. So, we've gone from 10 classes having 3,4,5, or more direct couplings to services; to simply interfacing through public methods on the Service Locator.

How much cleaner and readable would the code become? So, organization and readability can be improved in this scenario by implementing Service Locator.

Conclusion
There is a whole lot more to talk about when discussing the Service Locator pattern. However, I think the two benefits I've show here are enough to discuss this pattern being an alternative to Dependency Injection. So, I'm going to stop here for now. Maybe I'll put up a more detailed discussion of Service Locator in the future.

Some Service Locator links:
Martin Fowler
Core J2EE Pattern Catalog on java.sun.com
Another description on java.sun.com

Monday, August 6, 2007

Dependency Injection

I read an article focused mainly on Dependency Injection. However, what interested me even more was it's discussion around Service Locator as an alternative to DI. In my opinion, Service Locator should only be considered as an alternative in some scenarios. However, before I blog my opinions about Service Locator and Dependency Injection, I'm going to start by talking about each one individually. I don't want to assume everyone reading this knows what both patterns are and really don't want to write one giant post. So, read below for a summary of dependency injection or visit the article mentioned above for more detail.

Quick Explanation
First of all, you may have been doing DI without knowing what it was. But, to explain, Dependency Injection is exactly what it sounds like. A class's dependencies are injected into the class rather than created inside it. Probably best explained with an example.

Instead of:


class RequestHandler {
private ResponseGenerator responseGenerator;

public RequestHandler() {
this.responseGenerator = new ResponseGeneratorImpl();
}
}

Do this:

class RequestHandler {
private ResponseGenerator responseGenerator;

public RequestHandler(ResponseGenerator responseGenerator) {
this.responseGenerator = responseGenerator;
}
}

So, what does this do? We've accomplished two things. First we've created loose coupling between RequestHandler and ResponseGenerator. The first method uses a specific implementation while the second doesn't. Second, we've given control to the entity instantiating RequestHandler. This says, "I don't want to limit you to a specific implementation of ResponseGenerator, so i'll give you control and allow you to provide me with the ResponseGenerator you'd like me to use."

Types
There are three (3) types of Dependency Injection: Constructor Injection, Setter Injection, and Interface Injection. You've just seen an example of Constructor Injection. I'm not going to talk about or show Interface Injection for several reasons. (I've never used it and the other two are much more common.) Setter Injection I'm sure you can picture, but just in case, see the example below.

public class RequestHandler {
private ResponseGenerator responseGenerator;

public void setResponseGenerator(ResponseGenerator responseGenerator) {
this.responseGenerator = responseGenerator;
}
}

Constructor vs Setter Injection
The primary distinction is that Constructor Injection provides a usable object (presumably) immediately after construction. This means no worries of running into exceptions because you instantiated an object but forgot to set one of its dependencies. So what about when you're dealing with quite a few dependencies? Either your constructor gets long, or you're forcing many setter method calls to create a usable object. Unless you have a good reason to use Setter Injection, I'd stick to Constructor Injection as a rule of thumb. (And stay away from using a combination if at all possible !!! My pet peeve.)

Pros
Other than enabling loose coupling and increasing usability through inversion of control, the remaining major benefit is ease of testing. DI allows you to simply inject mock objects to unit test the class under test.

Cons
When your class has lots of dependencies, it can get messy. Even though this could be an indication your class should be separated out into multiple classes (cohesion), it doesn't necessarily. So, from time to time, you will run into this.

More to Come
There are more DI pros and cons, but nothing really worth talking about unless you're comparing against an alternative. Stay tuned and I'll be doing just that when I look at the idea of Service Locator as an alternative to Dependency Injection.

Other DI Links:
Wikipedia
James Lorenzen's Blog

Sunday, August 5, 2007

SCWCD: The Beginning

About a month ago, I got started studying for my WCD certification by reading the first two chapters of this book. I haven't had a chance to touch it since, so I just started from the beginning again and decided to talk a little about what I'm learning.

In the very beginning there are a lot of web development basics discussed. This includes an intro to HTML and HTTP, what a web server does, the basic life cycle of an HTTP request/response pair, how to go about creating a simple servlet. So, here's a quick summary:

HTTP & HTML
-- Most common HTTP requests are GET and POST
-- GET request has a limited (character) length
-- data sent with a GET is appended to the URL
-- data sent with a POST is contained inside the reques

Web Server
-- a Web Server (by itself) can only serve static pages
-- a 'helper application' is needed to serve dynamic content or save data

URL
-- By default, port 80 is used(port of the web server application)

Servlets
-- a simple servlet class extends HttpServlet and implements doGet() and doPost()
-- a Deployment Descriptor maps a servlet class to a url pattern


Simple Servlet


import javax.servlet.*;
import javax.servlet.http.*;

public class ChadServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
// IMPLEMENT ME
}
}



Simple Deployment Descriptor


<web-app ...>
<servlet>
<servlet-name>SimpleServlet</servlet-name>
<servlet-class>ChadServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SimpleServlet</servlet-name>
<url-pattern>/myservlet</url-pattern>
</servlet-mapping>
</web-app>