Analyzing class metadata with the Springframework
What a shame I haven’t published anything for a long time. To make up for this long pause, I’m going to discuss how Spring can support with analyzing class metadata. These days everybody is crazy about using annotations in their frameworks. Occasionally you need to know what classes/methods are annotated. A good example might be to build a list of class names for all JPA entities (those classes annotated with javax.persistence.Entity and the like).
A simple use-case showing how to detect classes annotated as components
This use-case is using a few Spring APIs and some home grown code that controls resource matching (ClassResourceResolver and AnnotationMetadataMatcher).
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.ClassUtils;
public class ClassResourceResolverTest {
@Test
public void testSelect() throws IOException {
// given
ClassResourceResolver scanner = new ClassResourceResolver(
ClassUtils.convertClassNameToResourcePath(AComponent.class.getPackage().getName()));
final MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(
new PathMatchingResourcePatternResolver());
// when
String[] classNames = scanner.select(new AnnotationMetadataMatcher(metadataReaderFactory, false,
Component.class));
// then
Assert.assertArrayEquals(new String[] { AComponent.class.getName() }, classNames);
Assert.assertTrue(metadataReaderFactory.getMetadataReader(classNames[0]).getAnnotationMetadata()
.isAnnotated(Component.class.getName()));
}
}
@Component
class AComponent {
}
@Repository
class ARepository {
}
ClassResourceResolver is doing the resource matching all from a set of resource paths
public String[] select(ClassResourceMetadataMatcher matcher) throws IOException {
List<String> result = new ArrayList<String>();
for (String path : resourcePath) {
String resourcePattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + path + "/**/*.class";
Resource[] resources = this.resourcePatternResolver.getResources(resourcePattern);
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader reader = matcher.match(resource, resourcePatternResolver);
if (reader != null) {
result.add(reader.getClassMetadata().getClassName());
}
}
}
}
return result.toArray(new String[result.size()]);
}
A ClassResourceMetadataMatcher is looking at the annotations present on a class resource
@Override
public MetadataReader match(Resource resource, ResourceLoader resolver) throws IOException {
for (Class<? extends Annotation> annotationType : annotationTypes) {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
if (new AnnotationTypeFilter(annotationType, considerMetaAnnotations).match(metadataReader,
metadataReaderFactory)) {
return metadataReader;
}
}
return null;
}
Under the hood Spring is using the ASM bytecode library for looking into the class files. Not that no class examined by the code above is actually loading any of the class objects so it is fairly lightweight and not filling up your perm gen space. Still you need to make up useful search paths so you don’t end up scanning through you full classpath.
The full code just is available as a gist
git clone git@gist.github.com:73f21e68d24032ad7672.git
Testing static methods…
We all have learned that it is not wise to overuse static methods as these are kind of hard to test and deal with. So in general I strive to get out of their way. Sometimes I’m facing the situation that the use of a framework or that some technical infrastructure requires me to implement static methods.
So for testing I found PowerMock which nicely integrates with EasyMock and Mockito.
Using Nexus and the Nexus REST API for implementing a software update tool
Nexus is using a pretty well documented REST API which is usable externally as well.
For one of my customers I implemented a kind of automatic software update tool that can be embedded into any product. It is based on the Sonatype NEXUS repository manager.
Java5 Generics are implemented by type erasure, but …
… still it is possible to get hold of the actual type parameters of parameterized types. Even if classical reflection does not deliver type information, this type parameters can still be extremely useful. I have a few pieces of code (DAO, controllers, etc.) that are parameterized by class objects.
Rendering a FacesMessage reliably
Quite a while ago I had posted about generating a FacesMessage within a method that is called during the RENDER_RESPONSE phase. Today I had to find a way to display those at the very top of a page and none of the message should get lost.
So I came up with trying that with jQuery (in my case it is already included in Rich-Faces that I was using here). The idea is to actually render all FacesMessage objects at the very bottom of the page and once the page has finished loading move its DOM tree up where it was supposed to be displayed.
ServiceLoader or "Sometimes you just don't need a full blown dependency injection container"
I like Springframework very much and use it in my day to day business as it eases development in many places. A few days ago I started using Hibernate Envers in order to implement a simple auditing solution for a JPA based application. I was faced with the (typical) requirement that the username of the user currently logged in was written into the audit entity. With Envers you would do that using a org.hibernate.envers.RevisionListener. This is instantiated by the Envers runtime. That listener required access to the FacesContext (it’s a JSF based application) to get the user principal from the HTTP request. Not a big deal in general! Still I wanted to keep that testable and usable in various environments, so an abstraction was needed and finally something would have to inject that into my listener.
As I said I’m a fan of Spring and this would be the perfect job and eventually one would propose “yeah, let’s do Spring AOP with AspectJ weaving”. As this application was already in production I didn’t want to add that at this time and was seeking for something more simple but still elegant.
Java as of 1.6 has the concept of SPI and ServiceLoader already built-in. I had never used it before. Here it seemed to perfectly match and it did.
import java.security.Principal;
public interface UserPrincipalProvider {
Principal getUserPrincipal();
}
import java.security.Principal;
public class TestUserPrincipalProvider implements UserPrincipalProvider {
public Principal getUserPrincipal() {
return new Principal() {
public String getName() {
return "TEST";
}
};
}
}
A file named META-INF/services/at.package.auditing.UserPrincipalProvider would be responsible for registering the provider implementation, it only contains one or multiple class names:
at.package.auditing.TestUserPrincipalProvider
For getting a runtime instance of such a provider I implemented a helper like
public static <T> T lookup(Class<T> clazz) {
Iterator<T> iterator = ServiceLoader.load(clazz).iterator();
return iterator.hasNext() ? iterator.next() : null;
}
It is called like ...lookup(UserPrincipalProvider.class).
eclipse 3.5
Since eclipse 1.0 has been released back in November 2001 it has evolved into a pretty popular and feature rich IDE. I remember using eclipse 2.0.1 first time, it was pretty much only a Java development IDE with little support for application containers.
Soon eclipse 3.5 (galileo) arrives supporting a wide palette of programming languages, programming models and execution environments, application containers, etc. The past 3 months I had been testing galileo from early milestone releases and been happy with it – also with my favourite eclipse plugins that I use in my daily business.
Here I briefly show some of the many features that I like:
Install New Software
I believe with eclipse 3.4 the user interface for updating/installing plugins has been pretty much messed up. Seems the eclipse engineers have done a good job to fix it up again. It has never been so easy and intuitive (with drag & drop support for update-site URLs) to install and update an eclipse plugin. But even more important, now it is possible to export bookmarks of your favourite plugins (you can select them plugin by plugin) and import them into another eclipse installation (e.g. for switching to a new eclipse release).
Type Filter (eclipse 3.4)
With a large number of libraries in the classpath it gets pretty overloaded in the type search dialogs. Mostly you find lots of classes that you never want to deal with directly. E.g. classes from the com.sun.* packages. Still you have to skip over them while searching for some other classes.
By defining a type filter you can suppress any package you are not interested in.

toString() Method
I usually would use the ToStringBuilder from the Apache commons-lang package to implement any toString() method.
As of eclipse 3.5 the Source->generate toString()… feature can be customized to support the commons-lang ToStringBuilder pattern.

Format edited lines only (eclipse 3.4)
In a team environment it is important that everybody is using the same formatting rules for auto-formatting the source code. Otherwise code comparison / mergeing can get pretty nasty. However sometimes this is not the case. Still eclipse can help to minimize the impact of autoformatting. You can choose the option to format only the code portion that has been actually changed.

Breadcrumbs (eclipse 3.4)
Eclipse has always had a perspective called Java Browsing (some heritage from good old Visual Age). I never really liked it, as it consumes quite a lot of space of the workbench.
With eclipse 3.4 the eclipse team introduced the so called breadcrumbs (Alt-Shift-B) which is showing almost they same information but much is more compact. It allows you to quickly jump between packages, classes, members, etc.

Block selection
Alt-Shift-A activates a special editing mode where it is possible to select any rectangular text area and copy / paste it.

java.util.logging
Sun mostly sticks with java.util.logging (jul) in their products. jul is fairly unflexible but we need to live with it. However I usually would use log4j with slf4j as logging facade. In order to get more control over jul logging output you can use the slf4j to java.util.logging bridge. Here I show how to set it up with Spring and Maven
org.slf4j jul-to-slf4j 1.5.4 org.slf4j slf4j-log4j12 1.5.4 log4j log4j 1.2.15 com.sun.jmx jmxri com.sun.jdmk jmxtools
java.net.SocketException: Address family not supported by protocol family: bind
Today I encountered a strange phenomen on Windows Vista. I was implementing a JAX-WS web service and trying to bind an endpoint with the JDK6 built-in JAX-WS.
Endpoint endpoint = Endpoint.publish("http://localhost:8090/queryservice", endpointImplementation);
I got this strange
java.net.SocketException: Address family not supported by protocol family: bind
execption and did a search for this. Fortunately very recently somebody else had the same issue.
The workaround is to either update your System32\drivers\etc\hosts file, replace “::1 localhost” with “127.0.0.1 localhost”
or use 127.0.0.1 as a replacement for localhost when creating the socket.
Bytecode version check
Currently I’m doing deployment tests and proof-of-concept tests for various technologies (RMI, Session Bean, JNDI, JSF, Seam, Web Services, Spring, Hibernate, .etc.) on different application servers (JBoss, IBM WebSphere, SAP Netweaver).
Some of the app servers are only certified or supported with Java5. So I frequently ran into problems resulting from having classes around compiled for Java6. I was already thinking of writing a tool that could analyze a Jar or class file and get its version information. But luckily I found a tool ready to do the job.

