Friday, December 7, 2007

Use Google Reader to Find Number of Subscribers to a Feed

In Google Reader, click on "Add Subscription". Type in the name of the blog or part of the blog url and hit Enter.





This is what you'll see in the search results.


Thursday, December 6, 2007

Travel Tip

This is a little off-topic compared to what I'm normally blogging about, but it's definitely a useful tidbit of information.

On my way home from a company event this weekend, my wife and I volunteered to take a later flight in exchange for free round-trip tickets and meal vouchers. After receiving these items, we sat down for some food and drinks to pass the time before the next flight. When it came time to leave, we found out the restaurant we were in doesn't accept meal vouchers from the airline we were flying. Go figure....

Travel Tip: Always check with the vendor to make sure they'll take your meal voucher before hand.

Monday, November 5, 2007

Dynamic Partner Links and the UDDI BC

I recently posted a basic example of Dynamic Partner Links in OpenESB here. In this post, I'll show how to use the UDDI BC to dynamically resolve a service URL at runtime and invoke it.

Without dynamic partner links and the UDDI BC, what would you do if a service you're invoking from within your process was moved? Well, you'd have to modify, rebuild, and re-deploy your Composite Application. Using what I'm about to show you, your process can react to that change automatically.

Below is the tutorial (really just some high level steps). I've also uploaded my NetBeans modules and a copy of the tutorial here.

Prerequisites:



Tutorial:


  • Step 1: Create a New BPEL Module


  • Step 2: Create a New SOAP WSDL with one request-response operation, and a simple BPEL process for the backend . We'll invoke this service dynamically later on.




  • Step 3: Create a New UDDI WSDL with one request-resposne operation. (UDDI BC Demos can be found here)


  • Step 4: Add an External WSDL File from http://schemas.xmlsoap.org/ws/2004/08/addressing. The WS-Addressing WSDL defines the EndpointReference element that we'll need.
    • GOTCHA: NetBeans may add a character to the beginning of the wsdl when it imports. Make sure to remove this character. In some cases, this may be a hidden character that will only show up in an editor like VI.




  • Step 5: Create another SOAP WSDL with one request-response operation. This service will provide the dynamic partner link functionality.


  • Step 6: Create another BPEL Process. This process should lookup a service endpoint in UDDI and invoke the service using a dynamic partner link.




  • Step 7: Clean and Build the BPEL Module.


  • Step 8: Create a Composite Application and add your BPEL Module to it.


  • Step 9: Clean and Build the Composite Application.


  • Step 10: Correct the Composite Application's configuration using the CASA Editor.
    • Generated:





    • Corrected:





  • Step 11: Clean, Build, and Deploy the Composite Application Again


  • Step 12: Create a test case to invoke the service we've created.


  • Step 13: Create another service to invoke, just as in Step 2. Make the BPEL process do something a little different so we will be able to tell which service was invoked.
    • This WSDL must have the same target namespace and operation to invoke as the WSDL in step 2.



  • Step 14: Update the service endpoint in UDDI to point to the new service you created.


  • Step 15: Run the testcase again. The output will show the new service was invoked.




Sunday, November 4, 2007

Dynamic Partner Links in JBI

I've put together an example of using a dynamic partner link in OpenESB. This example shows the basics of assigning an EndpointReference to a partner link at runtime, and then invoking that partner link.

Below is the tutorial I've put together (really just some high level steps). I've also uploaded the tutorial and NetBeans modules I've created here.

Prerequisites:




Tutorial:

  • Step 1: Create a New BPEL Module


  • Step 2: Create a New SOAP WSDL with one request-response operation, and a simple BPEL process for the backend . We'll invoke this service dynamically later on.


  • Step 3: Add an External WSDL File from http://schemas.xmlsoap.org/ws/2004/08/addressing. The WS-Addressing WSDL defines the EndpointReference element that we'll need.
    • GOTCHA: NetBeans may add a character to the beginning of the wsdl when it imports. Make sure to remove this character. In some cases, this may be a hidden character that will only show up in an editor like VI.



  • Step 4: Create another SOAP WSDL with one request-response operation. This service will provide the dynamic partner link functionality.
    • Add a schema to the wsdl that defines an elment that accepts an EndpointReference and xsd:anyType.
    • Modify the request message accordingly






  • Step 5: Create another BPEL Process. This process should assign the EndpointReference to a PartnerLink and invoke it.





  • Step 6: Clean and Build the BPEL Module.


  • Step 7: Create a Composite Application and add your BPEL Module to it.


  • Step 8: Clean and Build the Composite Application.


  • Step 9: Correct the Composite Application's configuration using the CASA Editor.
    • Generated:


    • Corrected:



  • Step 10: Clean, Build, and Deploy the Composite Application Again


  • Step 11: Create a test case to invoke the service we created in step 2.




  • Step 12: Create another service to invoke, just as in Step 2. Make the BPEL process do something a little different so we will be able to tell which service was invoked.
    • This WSDL must have the same target namespace and operation to invoke as the WSDL in step 2.



  • Step 13: Create a second test case to invoke the new service you've created.





Friday, November 2, 2007

Class Dependencies and the Factory Pattern

I listened to a Podcast this morning from Software Engineering Radio on Dependencies. In the context of this podcast, dependencies refers to the relationship between objects. The problem discussed was the lack of support for these object relationships in today's OO languages.

I wanted to touch on one specific topic covered in the podcast; the negative effect on dependency visibility that can come from a... misguided?... use of the Factory pattern.

Here's the problem:

Pretend you have a factory that exposes, lets say, 10 objects. And you have a class that uses the factory to obtain 3 of those objects. Without having intimate knowledge of the class or searching the class's implementation for "Factory.getXXXXXXX()", it's impossible to tell exactly what objects an instance of the class depends on. What you end up with is a spider-web like architecture. Many classes depend on the Factory which in turn depends on many classes itself.

So, what's the solution?

One possibility is to enforce a 1:1 ratio between factories, and classes using a factory. If Class A depends on instances of Class B and Class C, the factory Class, FactoryA must only expose instances of Class B and Class C. Also, Class A must only use FactoryA. Doing this provides confidence that all objects exposed by the factory are dependencies of the class.

Another possibility would be implementing Dependency Injection. If you go with constructor injection, class dependencies are visible as parameters to the constructor. If you go with setter injection, all dependencies are visible via the setter methods.

Food for Thought
1. Is Dependency Injection an alternative to Factory Pattern?
2. Does this problem also arise in the use of Service Locator?
3. What do you gain with clear dependency visibility?

Thursday, October 11, 2007

TAR-ing ginormous amounts of data

James Lorenzen posted a quick how-to on his blog about compressing huge amounts of data. His post can be found here. There's one small piece i'd like to add.

If you're tar-ing up 10Gb of data, you need 10Gb of free space. What if you don't have the free space? Well, if you're moving the data (not wanting to keep the original files), here's a tip.

Just add the --remove-files parameter to your tar command. This will remove files as they're added to the archive. So you can tar up the 10Gb of data w/o having 10Gb free!

tar --remove-files -cf filename.tar directory/*

Tuesday, October 2, 2007

Looking for Podcasts

I finally got an iPod a couple months ago and recently started listening to Podcasts. I've found some good podcasts from .NET Rocks!, Software Engineering Radio, and The Java Posse, but I'm sure there are others out there. So, if you have any recommendations, please let me know!

Monday, September 17, 2007

Determine Local IP Addresses

Here's a quick how-to for determining the IP Addresses your local machine has.

NOTE: This version (i've edited the post a couple of times now), will return all IPs associated with any network interface on the machine. Also, it's been tested on Windows and several flavors of linux.



public ArrayList getIPs() throws SocketException {
ArrayList ips = new ArrayList();
Enumeration m = NetworkInterface.getNetworkInterfaces();
while(m.hasMoreElements()) {
NetworkInterface ni = m.nextElement();
Enumeration addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
String ip = address.getHostAddress();

// filter out Inet6 Addr Entries
if (ip.indexOf(":") == -1) {
ips.add(ip);
}
}
}

return ips;
}

Thursday, September 13, 2007

Generic toString()

Do you ever want a descriptive toString() of a class you just created, but don't feel like taking the time to write it? Here's a generic toString() that uses the java.lang.reflect package and will work in any class.

Note:
This isn't the end-all generic toString() method. It does the bare minimum of printing out each field and its value with the added ability to handle null values and arrays.



@Override
public String toString() {
Field[] fields = getClass().getDeclaredFields();
AccessibleObject.setAccessible(fields,true);

StringBuffer sb = new StringBuffer();
sb.append("Class: " + this.getClass().getName() + "\n");

for (Field field : fields) {
Object value = null;
try {
value = field.get(this);
} catch (IllegalAccessException e) {continue;}

sb.append("\tField \"" + field.getName() + "\"\n");

Class fieldType = field.getType();
sb.append("\t\tType: ");

if (fieldType.isArray()) {
Class subType = fieldType.getComponentType();
int length = Array.getLength(value);
sb.append(subType.getName() + "[" + length + "]" + "\n");

for (int i = 0; i < length; i ++) {
Object obj = Array.get(value,i);
sb.append("\t\tValue " + i + ": " + obj + "\n");
}
} else {
sb.append(fieldType.getName() + "\n");
sb.append("\t\tValue: ");
sb.append((value == null) ? "NULL" : value.toString());
sb.append("\n");
}
}
return sb.toString();
}



Example Output

Class: GenericToString
- Field "myint"
Type: int
Value: 9
- Field "myDouble"
Type: java.lang.Double
Value: 999.095
- Field "myString"
Type: java.lang.String
Value: My String
- Field "myNullObject"
Type: java.lang.Object
Value: NULL
- Field "myStringArray"
Type: java.lang.String[2]
Value 0: one
Value 1: two
- Field "myintArray"
Type: int[3]
Value 0: 1
Value 1: 2
Value 2: 3
- Field "myHashMap"
Type: java.util.HashMap
Value: {val3=3, val1=val1, val2=val2}

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>

Saturday, July 21, 2007

Unit Testing Private Methods

So I've always thought that when it comes to writing unit tests against private methods, you have two options; use reflection, or break encapsulation. However, I just read an article that discusses this very topic in a good amount of detail. It points out 4 options for testing private methods.

If you're just interested in a summary of those 4 options, keep reading. Otherwise, here is the article I came across.

1. Don't Test Private Methods

  • If you're testing the class's non-private methods, then the private methods are being tested indirectly. You can maintain a high confidence level in your code w/o unit testing those private methods.

  • Feeling the need to test private methods may indicate that those methods should be moved into their own class. There they would become non-private (easily tested) and become reusable as well.


  • 2. Break Encapsulation
  • Changing the method from private to package-access is probably the quickest and easiest solution to testing private methods.

  • Seeing a private methods tells you something. When it's package-access, it doesn't speak so loudly.


  • 3. Use Reflection
  • Using reflection (java.lang.reflect), you can bypass encapsulation and gain access to the private method you'd like to test.

  • Your tests are more verbose. You've got to gain access to the private method before you can test it.


  • 4. Use an Inner Class
  • An inner class inside the class you're testing will have access to the private methods.

  • Your production class contains more than production code.


  • My $.02
    I really don't like the idea of using a nested test class, but I'd love to hear arguments promoting this option. Also, I don't like sacrificing encapsulation for the sake of testing. If you want to test the private method, do it right and use reflection. Other than that, I'm sure indirectly testing private methods has its time and place, but how often is determined by how you write your code.

    Thursday, July 5, 2007

    Sun Certified Java Programmer

    So, I'm getting ready to start working on my 2nd Java Certification, Web Component Developer. I can remember when I used to question whether or not getting a certification was even worth it. I heard a lot about how certifications don't prove anything. Anyone can memorize some material and pass a test.

    I decided to work towards the Java Certified Programmer certification anyway. I made up my mind that I would at least improve my Java skills, which at the time I had only been working with Java for 6 months or so. After a few months reading SCJP Sun Certified Programmer for Java 5 Study Guide, taking practice tests, and putting my newfound knowledge into practice at work, I became a Sun Certified Java Programmer.

    There was no question. Taking the certification was with out a doubt, extremely beneficial. The biggest factor was the amount I learned about the Java language. This was especially helpful being a newcomer to Java. Plus, it does take more than just memorizing material to pass this certification. It takes an understanding of key Java concepts and OOP, in-depth knowledge of several Java 5 features, and the ability to put these things to work.

    If you're new to OOP and working with Java, or just new to Java, I strongly recommend working towards the SCJP certification. It will build your Java skills and add to your resume.