<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Martin Ahrer - Together we&#039;ll make IT &#187; Java</title>
	<atom:link href="http://www.martinahrer.at/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.martinahrer.at</link>
	<description>Java Enterprise Softwareentwicklung und Consulting</description>
	<lastBuildDate>Sun, 11 Dec 2011 16:19:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
<meta name="generator" content="deSignum 0.8.1" />
		<item>
		<title>Analyzing class metadata with the Springframework</title>
		<link>http://www.martinahrer.at/2011/08/16/analyzing-class-metadata-with-the-springframework/</link>
		<comments>http://www.martinahrer.at/2011/08/16/analyzing-class-metadata-with-the-springframework/#comments</comments>
		<pubDate>Tue, 16 Aug 2011 20:11:45 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Bytecode]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Springframework]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=805</guid>
		<description><![CDATA[What a shame I haven&#8217;t published anything for a long time. To make up for this long pause, I&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>What a shame I haven&#8217;t published anything for a long time. To make up for this long pause, I&#8217;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).</p>
<p><strong>A simple use-case showing how to detect classes annotated as components</strong></p>
<p>This use-case is using a few Spring APIs and some home grown code that controls resource matching (ClassResourceResolver and AnnotationMetadataMatcher).</p>
<pre class="brush:java">
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 {
}
</pre>
<p><strong>ClassResourceResolver is doing the resource matching all from a set of resource paths</strong></p>
<pre class="brush:java">
	public String[] select(ClassResourceMetadataMatcher matcher) throws IOException {
		List&lt;String&gt; result = new ArrayList&lt;String&gt;();

		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()]);
	}
</pre>
<p><strong>A ClassResourceMetadataMatcher is looking at the annotations present on a class resource</strong></p>
<pre class="brush:java">
	@Override
	public MetadataReader match(Resource resource, ResourceLoader resolver) throws IOException {
		for (Class&lt;? extends Annotation&gt; annotationType : annotationTypes) {
			MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
			if (new AnnotationTypeFilter(annotationType, considerMetaAnnotations).match(metadataReader,
					metadataReaderFactory)) {
				return metadataReader;
			}
		}
		return null;
	}
</pre>
<p>Under the hood Spring is using the <a href="http://asm.ow2.org/">ASM</a> 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&#8217;t end up scanning through you full classpath.</p>
<p>The full code just is available as a gist
<pre class="brush:bash">git clone git@gist.github.com:73f21e68d24032ad7672.git</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2011/08/16/analyzing-class-metadata-with-the-springframework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing static methods…</title>
		<link>http://www.martinahrer.at/2011/01/19/testing-static-methods/</link>
		<comments>http://www.martinahrer.at/2011/01/19/testing-static-methods/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 11:46:42 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=685</guid>
		<description><![CDATA[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&#8217;m facing the situation that the use of a framework or that some technical infrastructure requires me to implement [...]]]></description>
			<content:encoded><![CDATA[<p>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&#8217;m facing the situation that the use of a framework or that some technical infrastructure requires me to implement static methods.<br />
So for testing I found <a href="https://code.google.com/p/powermock/">PowerMock</a> which nicely integrates with <a href="https://code.google.com/p/powermock/wiki/EasyMock">EasyMock</a> and Mockito.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2011/01/19/testing-static-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Nexus and the Nexus REST API for implementing a software update tool</title>
		<link>http://www.martinahrer.at/2010/05/25/using-nexus-and-the-nexus-rest-api-for-implementing-a-software-update-tool/</link>
		<comments>http://www.martinahrer.at/2010/05/25/using-nexus-and-the-nexus-rest-api-for-implementing-a-software-update-tool/#comments</comments>
		<pubDate>Tue, 25 May 2010 20:03:42 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=456</guid>
		<description><![CDATA[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. That tool performs the following steps Detect the current software [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nexus.sonatype.org/">Nexus </a> is using a pretty well documented REST API which is usable externally as well.<br />
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.</p>
<p><span id="more-456"></span></p>
<p>That tool performs the following steps</p>
<ol>
<li>Detect the current software version from the artifact metadata that is embedded into any Maven-built artifact</li>
<li>Query Nexus for available artifacts for the installed software (identified by Maven groupId and artifactId).</li>
<li>Test if any of the available artfacts has a version number higher than the installed one</li>
<li>If a newer version is available then download it</li>
<li>Move the new version to the target directory (e.g. the deployment folder of the application server)</li>
</ol>
<p>The Nexus REST url for a simple query for some artifact looks like <code>http://localhost/nexus/service/local/data_index/repositories/releases/content?q=commons-lang</code>. This query asks for the <em>commons-lang</em> artifact from the <em>releases repository</em>.</p>
<p>More URL schemes are documented <a href="https://docs.sonatype.com/display/NX/Nexus+Rest+API">here</a> and <a href="https://grid.sonatype.org/ci/view/Nexus/job/Nexus/label=ubuntu/ws/trunk/nexus/nexus-rest-api/target/classes/docs/index.html">there</a>.</p>
<p>The result from this query is like (only the latest versions are included for brevity):</p>
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;search-results&gt;
	&lt;totalCount&gt;5&lt;/totalCount&gt;
	&lt;from&gt;-1&lt;/from&gt;
	&lt;count&gt;-1&lt;/count&gt;
	&lt;tooManyResults&gt;false&lt;/tooManyResults&gt;
	&lt;data&gt;
		&lt;artifact&gt;

			&lt;resourceURI&gt;http://localhost/nexus/service/local/repositories/central/content/commons-lang/commons-lang/2.4/commons-lang-2.4.jar&lt;/resourceURI&gt;
			&lt;groupId&gt;commons-lang&lt;/groupId&gt;
			&lt;artifactId&gt;commons-lang&lt;/artifactId&gt;
			&lt;version&gt;2.4&lt;/version&gt;
			&lt;packaging&gt;jar&lt;/packaging&gt;
			&lt;extension&gt;jar&lt;/extension&gt;

			&lt;repoId&gt;central&lt;/repoId&gt;
			&lt;contextId&gt;Maven Central (Cache)&lt;/contextId&gt;
			&lt;pomLink&gt;http://localhost/nexus/service/local/artifact/maven/redirect?r=central&amp;g=commons-lang&amp;a=commons-lang&amp;v=2.4&amp;e=pom&lt;/pomLink&gt;
			&lt;artifactLink&gt;http://localhost/nexus/service/local/artifact/maven/redirect?r=central&amp;g=commons-lang&amp;a=commons-lang&amp;v=2.4&amp;e=jar&lt;/artifactLink&gt;

		&lt;/artifact&gt;
		&lt;artifact&gt;
			&lt;resourceURI&gt;http://localhost/nexus/service/local/repositories/central/content/commons-lang/commons-lang/2.4/commons-lang-2.4-sources.jar&lt;/resourceURI&gt;
			&lt;groupId&gt;commons-lang&lt;/groupId&gt;
			&lt;artifactId&gt;commons-lang&lt;/artifactId&gt;
			&lt;version&gt;2.4&lt;/version&gt;
			&lt;classifier&gt;sources&lt;/classifier&gt;

			&lt;packaging&gt;jar&lt;/packaging&gt;
			&lt;extension&gt;jar&lt;/extension&gt;
			&lt;repoId&gt;central&lt;/repoId&gt;
			&lt;contextId&gt;Maven Central (Cache)&lt;/contextId&gt;
			&lt;pomLink&gt;&lt;/pomLink&gt;
			&lt;artifactLink&gt;http://localhost/nexus/service/local/artifact/maven/redirect?r=central&amp;g=commons-lang&amp;a=commons-lang&amp;v=2.4&amp;e=jar&amp;c=sources&lt;/artifactLink&gt;

		&lt;/artifact&gt;

	&lt;/data&gt;
&lt;/search-results&gt;
</pre>
<p>That only needs to be parsed using a SAX parser for extracting the most important elements. This is the Maven GAV, packaging, classifier, and  the download url which are stored in a POJO. This POJO implements the algorithm for selecting the latest version by its compareTo method.</p>
<pre class="brush:java">
public class MavenArtifactMetadata implements Comparable&lt;MavenArtifactMetadata&gt; {
	private String groupId;
	private String artifactId;
	private String version;
	private String resourceURI;
	private String packaging;
	private String classifier;

	@Override
	public int compareTo(MavenArtifactMetadata o) {
		if (!this.groupId.equals(o.groupId) || !this.artifactId.equals(o.artifactId)) {
			return -1;
		}
		return versionCompareTo(o.version);
	}

	int versionCompareTo(String version) {
		Integer[] thatVersion = versionComponents(version);
		Integer[] thisVersion = versionComponents(this.version);
		int length = Math.min(thatVersion.length, thisVersion.length);
		for (int i = 0; i < length; i++) {
			if (thatVersion[i].equals(thisVersion[i])) {
				continue;
			}
			return thisVersion[i].compareTo(thatVersion[i]);
		}
		return thisVersion.length - thatVersion.length;
	}

	Integer[] versionComponents(String version) {
		String[] splitted = StringUtils.delimitedListToStringArray(version, ".");
		if (splitted.length>0 &#038;&#038; splitted[splitted.length-1].endsWith("-SNAPSHOT")) {
			splitted[splitted.length-1]=splitted[splitted.length-1].replaceAll("-SNAPSHOT", "");
		}
		Integer[] components = new Integer[splitted.length];
		for (int i = 0; i < splitted.length; i++) {
			components[i] = (Integer.valueOf(splitted[i]));
		}
		return components;
	}
}
</pre>
<p>While implementing the download part I had learned an important lesson. For downloading and moving large files it is much more efficient to use the Java NIO API.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2010/05/25/using-nexus-and-the-nexus-rest-api-for-implementing-a-software-update-tool/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Java5 Generics are implemented by type erasure, but &#8230;</title>
		<link>http://www.martinahrer.at/2010/05/22/java5-generics-are-implemented-by-type-erasure-but/</link>
		<comments>http://www.martinahrer.at/2010/05/22/java5-generics-are-implemented-by-type-erasure-but/#comments</comments>
		<pubDate>Sat, 22 May 2010 19:51:22 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=443</guid>
		<description><![CDATA[&#8230; 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. An example: public class EntityFormController&#60;T&#62; extends [...]]]></description>
			<content:encoded><![CDATA[<p>&#8230; still it is possible to get hold of the actual type parameters of <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/ParameterizedType.html">parameterized types</a>. 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.<br />
<span id="more-443"></span><br />
An example:</p>
<pre class="brush:java">
public class EntityFormController&lt;T&gt; extends FormController&lt;T&gt; {
	private Class&lt;T&gt; entityClass;

	public String create() {
		Object instance=getEntityClass().newInstance();
		...
	}
}
</pre>
<p>So for every specific instance of the property entityClass must be initialized explicitely by implementing a proper constructor, using dependency injection, etc.</p>
<pre class="brush:java">
public class AddressFormController extends EntityFormController&lt;Address&gt; {
	public class AddressFormController() {
		super(Address.class);
	}
}
</pre>
<p>This is kind of violating the<a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself"> DRY principle</a>. The actual type is already given through the type parameter. So I was trying to eliminate this few lines of code and come up with a solution that can analyze any parameterized type from a class declaration (super class hierarchy + interfaces).</p>
<pre class="brush:java">
/**
 * @author Martin Ahrer
 *
 */
public class GenericTypeArgumentExtractor {
	private final Class&lt;?&gt; candidateClass;

	public GenericTypeArgumentExtractor(Class&lt;?&gt; candidateClass) {
		super();
		this.candidateClass = candidateClass;
	}

	public Class&lt;?&gt;[] getGenericTypeArguments(Class&lt;?&gt; clazz) {
		// TODO: hopefully clazz.getGenericSuperclass() == clazz.getSuperclass()
		Type[] types = Arrays.copyOf(clazz.getGenericInterfaces(), clazz.getGenericInterfaces().length
				+ (clazz.getGenericSuperclass() != null ? 1 : 0));
		if (clazz.getGenericSuperclass() != null) {
			types[types.length - 1] = clazz.getGenericSuperclass();
		}
		// Iterate all types from which the clazz inherits. i.e all generic
		// interfaces and the generic super class.
		for (Type type : types) {
			Class&lt;?&gt;[] arguments = getGenericTypeArguments(type);
			if (arguments != null) {
				return arguments;
			}
		}
		return null;
	}

	private Class&lt;?&gt;[] getGenericTypeArguments(Type type) {
		if (type instanceof ParameterizedType) {
			ParameterizedType parameterizedType = (ParameterizedType) type;
			if (isCandidate(parameterizedType)) {
				Type[] arguments = parameterizedType.getActualTypeArguments();
				Class&lt;?&gt;[] result = new Class&lt;?&gt;[arguments.length];
				for (int i = 0; i &lt; result.length; i++) {
					result[i] = (Class&lt;?&gt;) (arguments[i] instanceof ParameterizedType ? ((ParameterizedType) arguments[i])
							.getRawType()
							: arguments[i]);
				}
				return result;
			}
		} else if (type != null) {
			Class&lt;?&gt;[] result = getGenericTypeArguments((Class&lt;?&gt;) type);
			return result;
		}
		return null;
	}

	/**
	 * Detects the type from which we want the type arguments. Can be overridden
	 * in subclasses.
	 *
	 * @param type
	 *            the parameterized type to check for.
	 * @return true if type arguments of the passed type are reqeusted.
	 */
	protected boolean isCandidate(ParameterizedType type) {
		return candidateClass.isAssignableFrom((Class&lt;?&gt;) type.getRawType());
	}
}
</pre>
<p>Using the above class for extracting type parameters would return an array containing the Address class object.</p>
<pre class="brush:java">
Class<?>[] genericTypeArguments = new GenericTypeArgumentExtractor(EntityFormController.class)
		.getGenericTypeArguments(AddressFormController.class);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2010/05/22/java5-generics-are-implemented-by-type-erasure-but/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rendering a FacesMessage reliably</title>
		<link>http://www.martinahrer.at/2010/02/09/rendering-a-facesmessage-reliably/</link>
		<comments>http://www.martinahrer.at/2010/02/09/rendering-a-facesmessage-reliably/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 18:13:56 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=418</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>Quite a while ago I had <a href="http://www.martinahrer.at/2008/02/09/create-facesmessage-within-a-get-method/">posted</a> 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.</p>
<p>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.<br />
<span id="more-418"></span></p>
<pre class="brush:xml">
&lt;div id="messagesTarget"&lt;/div&gt;

...
...

&lt;rich:panel id="messagesSource" rendered="#{! empty facesContext.maximumSeverity}"&gt;
	&lt;rich:messages showDetail="true" showSummary="true" errorClass="errorSeverity" warnClass="warningSeverity"
		infoClass="infoSeverity" /&gt;
&lt;/rich:panel&gt;

&lt;rich:jQuery selector="$('messagesTarget')" query="append($('messagesSource'))" timing="onload" /&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2010/02/09/rendering-a-facesmessage-reliably/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ServiceLoader or &quot;Sometimes you just don&#039;t need a full blown dependency injection container&quot;</title>
		<link>http://www.martinahrer.at/2009/08/31/serviceloader-or-sometimes-you-just-dont-need-a-full-blown-dependency-injection-container/</link>
		<comments>http://www.martinahrer.at/2009/08/31/serviceloader-or-sometimes-you-just-dont-need-a-full-blown-dependency-injection-container/#comments</comments>
		<pubDate>Mon, 31 Aug 2009 03:34:01 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Springframework]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=238</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 <a href="http://jboss.org/envers/">Hibernate Envers</a> 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 <code>org.hibernate.envers.RevisionListener</code>. This is instantiated by the Envers runtime. That listener required access to the <code>FacesContext</code> (it&#8217;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.<br />
As I said I&#8217;m a fan of Spring and this would be the perfect job and eventually one would propose &#8220;yeah, let&#8217;s do Spring AOP with AspectJ weaving&#8221;. As this application was already in production I didn&#8217;t want to add that at this time and was seeking for something more simple but still elegant.</p>
<p>Java as  of 1.6 has the concept of SPI and <a href="http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html">ServiceLoader</a> already built-in. I had never used it before. Here it seemed to perfectly match and it did.</p>
<pre class="brush:java">
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";
			}
		};
	}
}
</pre>
<p>A file named <code>META-INF/services/at.package.auditing.UserPrincipalProvider</code> would be responsible for registering the provider implementation, it only contains one or multiple class names:</p>
<pre class="brush:java">
at.package.auditing.TestUserPrincipalProvider
</pre>
<p>For getting a runtime instance of such a provider I implemented a helper like</p>
<pre class="brush:java">
public static &lt;T&gt; T lookup(Class&lt;T&gt; clazz) {
	Iterator&lt;T&gt; iterator = ServiceLoader.load(clazz).iterator();
	return iterator.hasNext() ? iterator.next() : null;
}</pre>
<p>It is called like <code>...lookup(UserPrincipalProvider.class)</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2009/08/31/serviceloader-or-sometimes-you-just-dont-need-a-full-blown-dependency-injection-container/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>eclipse 3.5</title>
		<link>http://www.martinahrer.at/2009/06/08/eclipse-35/</link>
		<comments>http://www.martinahrer.at/2009/06/08/eclipse-35/#comments</comments>
		<pubDate>Mon, 08 Jun 2009 16:38:30 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=143</guid>
		<description><![CDATA[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, [...]]]></description>
			<content:encoded><![CDATA[<p>Since <a href="http://archive.eclipse.org/eclipse/downloads/index.php">eclipse 1.0</a> 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.<br />
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 &#8211; also with my favourite eclipse plugins that I use in my daily business.</p>
<p><strong>Here I briefly show some of the many features that I like:</strong></p>
<p><em>Install New Software</em></p>
<p>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 &#038; 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).</p>
<p><a href="http://www.martinahrer.at/wp-content/uploads/2009/06/available-software-export.png"><img alt="Available Software Export" src="http://www.martinahrer.at/wp-content/uploads/2009/06/available-software-export.png" title="Available Software Export"  width="100%" height="100%"/></a></p>
<p><em>Type Filter  (eclipse 3.4)</em></p>
<p>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.<br />
By defining a type filter you can suppress any package you are not interested in.</p>
<p><img src="http://www.martinahrer.at/wp-content/uploads/2009/06/type-filter.png" alt="type-filter" title="type-filter"  width="100%" height="100%" /></p>
<p><em>toString() Method</em></p>
<p>I usually would use the <a href="http://commons.apache.org/lang/api-release/org/apache/commons/lang/builder/ToStringBuilder.html">ToStringBuilder </a>from the Apache commons-lang package to implement any toString() method.<br />
As of eclipse 3.5 the <strong>Source->generate toString()&#8230;</strong> feature can be customized to support the commons-lang ToStringBuilder pattern.</p>
<p><img src="http://www.martinahrer.at/wp-content/uploads/2009/06/tostring.png" alt="tostring" title="tostring"  class="alignnone size-full wp-image-160" width="100%" height="100%"/></p>
<p><em>Format edited lines only (eclipse 3.4)</em></p>
<p>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.</p>
<p><img src="http://www.martinahrer.at/wp-content/uploads/2009/06/format-edited-lines.png" alt="format-edited-lines" title="format-edited-lines"  class="alignnone size-full wp-image-163" width="100%" height="100%"/></p>
<p><em>Breadcrumbs (eclipse 3.4)</em></p>
<p>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.<br />
With eclipse 3.4 the eclipse team introduced the so called breadcrumbs (<strong>Alt-Shift-B</strong>) which is showing almost they same information but much is more compact. It allows you to quickly jump between packages, classes, members, etc.</p>
<p><img src="http://www.martinahrer.at/wp-content/uploads/2009/06/breadcrumbs.png" alt="breadcrumbs" title="breadcrumbs" class="alignnone size-full wp-image-165" width="100%" height="100%" /></p>
<p><em>Block selection</em></p>
<p><strong>Alt-Shift-A</strong> activates a special editing mode where it is possible to select any rectangular text area and copy / paste it.</p>
<p><img src="http://www.martinahrer.at/wp-content/uploads/2009/06/block-selection.png" alt="block-selection" title="block-selection" class="alignnone size-full wp-image-168" width="100%" height="100%"/></p>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2009/06/08/eclipse-35/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>java.util.logging</title>
		<link>http://www.martinahrer.at/2009/05/03/javautillogging/</link>
		<comments>http://www.martinahrer.at/2009/05/03/javautillogging/#comments</comments>
		<pubDate>Sun, 03 May 2009 08:53:53 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[slf4j]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=115</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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</p>
<pre class="brush:xml">
<bean class="org.slf4j.bridge.SLF4JBridgeHandler" init-method="install" scope="singleton"/>
</pre>
<pre class="brush:xml" line="1">
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jul-to-slf4j</artifactId>
			<version>1.5.4</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.5.4</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2009/05/03/javautillogging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>java.net.SocketException: Address family not supported by protocol family: bind</title>
		<link>http://www.martinahrer.at/2009/04/16/javanetsocketexception-address-family-not-supported-by-protocol-family-bind/</link>
		<comments>http://www.martinahrer.at/2009/04/16/javanetsocketexception-address-family-not-supported-by-protocol-family-bind/#comments</comments>
		<pubDate>Thu, 16 Apr 2009 15:28:36 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[IPV6]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Windows Vista]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=108</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<pre lang="java">Endpoint endpoint = Endpoint.publish("http://localhost:8090/queryservice", endpointImplementation);</pre>
<p>I got this strange
<pre lang="java">java.net.SocketException: Address family not supported by protocol family: bind</pre>
<p> execption and did a search for this. Fortunately very recently somebody else had the same <a href="http://forums.sun.com/thread.jspa?threadID=5373410&#038;tstart=0">issue</a>.</p>
<p>The workaround is to either update your System32\drivers\etc\hosts file, replace &#8220;::1 localhost&#8221; with &#8220;127.0.0.1 localhost&#8221;<br />
or use 127.0.0.1 as a replacement for localhost when creating the socket.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2009/04/16/javanetsocketexception-address-family-not-supported-by-protocol-family-bind/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bytecode version check</title>
		<link>http://www.martinahrer.at/2008/10/10/bytecode-version-check/</link>
		<comments>http://www.martinahrer.at/2008/10/10/bytecode-version-check/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 06:39:05 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Bytecode]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=89</guid>
		<description><![CDATA[Currently I&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>Currently I&#8217;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).<br />
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 <a href="http://alumnus.caltech.edu/~leif/opensource/bcver/index.html">tool </a>ready to do the job.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2008/10/10/bytecode-version-check/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

