Tag Archives: java

Reading JAX Magazine #1

Not too long ago I managed to read the previous issue of jaxenter.com’s magazine. The magazine was called Java Tech Journal but it has now been re-branded as JAX Magazine. Next after a few opinions I’ll be taking a peek at the contents of this issue and writing this as I scroll.

Continue reading

Ranting about a rant

First I stumble upon a rant. I often read these, write a long comment about all their faults or misunderstandings leading to their outburst of hatred, but this time it turned out that the site hosting the article has a botched comment form. It tries to load WYSIWYG editor which in turn hides the original <textarea>. Sigh.

Continue reading

Waiting for Java 8: JSR-310, the threeten

For Java 7 the Fork/Join looked created, but I guess no one was eager to use it as Lambdas were still missing. Also interesting was the new filesystem API, which I’m yet to try out. I was really disappointed when JSR-310 was not included in Java 7. The current JDK time/date API’s are a shame. I thought to take a look at what’s the status of JSR-310.

Continue reading

Asserting generic implementations in Java

A while back I ended up creating a simple interface like Predicate<T> as follows:

public interface Predicate<T> {
  boolean evaluate(T state);
}

Now when you create a bean that requires a predicate on some object, you’d code a setter for it:

package org.example.foos;

public class Foo {
  private Predicate<Bar> guardPredicate;

  public void operate(Bar bar) {
    if (!guardPredicate.evaluate(bar)) {
      throw new IllegalStateException();
    }

    // do stuff with bar
  }

  public void setGuardPredicate(Predicate<Bar> guardPredicate) {
    this.guardPredicate = guardPredicate;
  }
}

And embed this bean in your Spring ApplicationContext like:

<beans ...>
	<bean class="org.example.foos.Foo">
		<property name="guardPredicate">
			<bean class="org.example.foos.support.SomeBarPredicate" />
		</property>
	</bean>
</beans>

From the name of “SomeBarPredicate” you’d expect it to implement Predicate<org.example.foos.Bar>, but there’s no guarantee on that; an implementation of Predicate<java.lang.String> could be passed in as well. There’s no automatic runtime checking because of type erasure.

Class metadata to the rescue!

Whenever your class implements or extends a generic interface or class, this data is recoverable through Class.getGenericInterfaces() or Class.getGenericSuperclass().

Getting the information out is rather painful tough, and I’m not going to re-iterate the examples out there for this. For one, please see Reflecting generics by Ian Robertson.

Luckily Spring 3.0 has a utility class for this: GenericTypeResolver.

For our example, the setter should be rewritten as:

  public void setGuardPredicate(Predicate<Bar> guardPredicate) {

	Class<?> param = GenericTypeResolver.resolveTypeArgument(guardPredicate.getClass(), 
		Predicate.class);
	if (param != null // if null, it was unrecovarable, treat it as Class<Object>
		  && !param.isAssignableFrom(Bar.class)) {
		throw new IllegalArgumentException();
	}
	this.guardPredicate = guardPredicate;
  }

So lets test this with JUnit 4 and Spring testing utitilities:

package org.example.foos;

import static org.junit.Assert.fail;

import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

public class FooTest {

	private Foo foo = new Foo();
	
	@Test
	public void testSetGuardPredicate() {
		setGuardPredicateScenario(new Predicate<Bar>() {
			public boolean evaluate(Bar state) {
				return state.toString().contains("Bar");
			}
		});
	}
	
	@Test(expected=IllegalArgumentException.class)
	public void testSetGuardPredicateWithWrongTyped() {
		setGuardPredicateScenario(new Predicate<String>() {
			public boolean evaluate(String state) {
				return state != null && !state.isEmpty();
			}
		});
	}
	
	@SuppressWarnings("rawtypes")
	@Test
	public void testSetGuardPredicateWithUntyped() {
		setGuardPredicateScenario(new Predicate() {
			public boolean evaluate(Object state) {
				return state != null;
			}
		});
	}
	
	private void setGuardPredicateScenario(Object predicate) {
		ReflectionTestUtils.invokeSetterMethod(foo, "guardPredicate", 
				predicate, Predicate.class);
		foo.operate(new Bar());
	}
}

Voila, tests pass. Be sure to test it without our assertions as well; look at “testSetGuardPredicateWithWrongTyped” result to see a not so nice ClassCastException:

java.lang.Exception: Unexpected exception, expected<java.lang.IllegalArgumentException> but was<java.lang.ClassCastException>
Caused by: java.lang.ClassCastException: org.example.foos.Bar cannot be cast to java.lang.String
	at org.example.foos.FooTest$2.evaluate(FooTest.java:1)
	at org.example.foos.Foo.operate(Foo.java:11)
	at org.example.foos.FooTest.setGuardPredicateScenario(FooTest.java:49)
	at org.example.foos.FooTest.testSetGuardPredicateWithWrongTyped(FooTest.java:27)

With assertions we catch that configuration problem in earlier refresh stage.

Injecting “foreign beans” into a new ApplicationContext

While moving towards full OSGi supported application I’ve started to restrict my application modules by Spring context to confine them almost as if they were OSGi modules. As we don’t have any static lookups anywhere this is practically OSGi without any package-imports and less class loader security; but we are getting there.

I need to give some services away to my modules and now, how do I do that? Quickly browsing through Pro Spring 2.5 and Spring Recipes and not finding anything I just started to look at GenericApplicationContext api after failing to access it’s BeanFactory before refreshing it.

There’s a method addBeanFactoryPostProcessor() which allows you to register beans into the newly initialized ConfigurableListableBeanFactory through various register* methods.

As in my case, the dependencies I needed to publish were autowired to my context building bean by it’s ApplicationContext and so adding them to any instantiated contexes was a breeze.

Another way to accomplish almost the same would be to simply set the parent ApplicationContext to the new ApplicationContexes but that would had allowed my modules to fetch other “non-specified” beans as well.

Not sure how ApplicationEvents would be propagated up if you set the parent application context, but as the GenericApplicationContext.addApplicationListener(..) methods documentation says that the new application listeners will only get events after the next refresh those might not get propagated in both directions; most likely only from childContext -> parentContext.

If you however choose to somehow specify what events can be and cannot be transferred between the contexes you might opt to add your custom ApplicationEventListener to propagate only the supported events.