Author Archives: fortuna

Service Selector

Sometimes we may have more than one implementation and/or instance of a service to which we need to route requests. Routing may be controlled by a number of different factors, such as the request type, request arguments, runtime configuration, etc.

An implementation of such routing might look something like this:

[java]
public interface SomeService {
void someMethod();
}

public class RoutingSomeService implements SomeService {

private Map delegates = …

private String activeDelegateId = …

public void someMethod() {
SomeService delegate = delegates.get(activeDelegateId);
if (delegate != null) {
delegate.someMethod();
}
else {
// XXX: throw runtime exception???
}
}
}
[/java]

Posted in Java | Tagged , | Leave a comment

Uniform Caching

Typically object caching in Java is managed by the container or framework in use. Occasionally however there is a need to manually cache domain-specific objects, whereby a java.util.Map implementation will not suffice.
Using the popular ehcache framework as an example, the following pattern is typically observed:

public class SomeClass {

private final Cache cache = …

[...]

Posted in Java | Tagged , , | Leave a comment

Whiteboard Registry

In OSGi using a publisher/subscriber design can be somewhat more complicated that traditional Java environments:

public class SomeBundleActivator implements BundleActivator {

private SomeService service = …

private ServiceRegistration registration;

public void start(BundleContext context) {
registration = context.registerService(SomeService.class.getName(), service, null);
}

}

public class AnotherBundleActivator implements BundleActivator {

private [...]

Posted in Java | Tagged , , , | Leave a comment

OSGi Service Locator

The Service Locator pattern is a well-established mechanism for accessing local and remote services in a consistent manner:

public interface ServiceLocator {

<T> T findService(String serviceName) throws ServiceNotAvailableException;
}

Using a structured service name interface we can improve uniformity and reduce the potential for typos:

public enum ServiceName {

SomeService("SomeService");

private final String filter;
[...]

Posted in Java | Tagged , , | 2 Comments

Uniform Logging

Application logging always seems to become one of those code smells, typically regarding duplication of code, or conversely, non-uniform log messages.
There are many different ways to log a message in Java, but variations on the following pattern are common:

public class SomeClass {

private static final Log LOG = LogFactory.getLog(SomeClass.class);

public [...]

Posted in Java | Tagged , , | Leave a comment