Posts Tagged ‘java’

JPA2 Metamodel – how to manage that.

Tuesday, February 22nd, 2011

JPA2 added new typesafe Criteria API. This allows us to build query in strongly-typed manner instead of string based. To provide such functionality JPA2 use Metamodel API described in JSR-317: Chapter 5.

When entity manager factory is bootstrapping for persistence unit, then persistence provider have to initialize metamodel classes so this classes have to be accessible. For application developers it is important to easy generate them.

We can automatically generate metamodel classes we use Annotation Processing API. The structure of metamodel classes are described in JSR-317: Chapter 6.2.1.1. Briefly for every managed class there will be similar class with name of metamodel class plus “_”, and for every property there will be SingularAttribute for non-collection and
Attribute for Collection|Set|List|Map attribute.

Thanks to that metamodel classes we can write a query, which is type safe and probably more important we can easy do refactorings. That’s in theory, because IDE have to have access to metamodel classes, so the question arise how to manage this classes. I was wonder about three option here:

  1. Keep generated metamodel as normal code and commit into repository.
  2. Use external tool to generate metamodel and include results as IDE sources.
  3. Use IDE support, if exists.

First solution is portable, no IDE configuration, no problems between different IDE’s and so on. The disadvantage of this solution is that we have to remember about generating metamodel classes after we change our code and than commit metamodel into repository. Obviously we break the version control system rule, “don’t commit generated files“.

Second one assumes that you are using some kind of build tool (eg. maven). Then we can setup generation step into that tool (for maven it is maven-processor-plugin) and we setup our IDE to point to that sources. The bad thing about that is that we have to run the tool, otherwise we have not actual metamodel.

Third one is use your IDE for that. Sadly configuration isn’t automatic and every IDE has it’s own way to do this. JPA 2.0 Typesafe Criteria API and Annotation Processing Howto article describes how to do this in IntelliJ IDEA.

Both second and third solution has one additional flaw. You have to specify which annotation generator you want to use. That ties you to JPA provider implementation.

Here you find annotation processor names:

EclipseLink
org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor
Hibernate
org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor
OpenJPA
org.apache.openjpa.persistence.meta.AnnotationProcessor6

We can find processor parameters and switches in javadocs, in EclipseLink case, processor is in internal package, that makes finding parameters and switches a little bit harder, but we can check source code, or use Google.

I try to use third one and second one as fallback for people which use different IDE than IntelliJ, but I’m not happy with that solution.

How do you process  JPA2 metamodel classes?


Spring Template Objects Testing

Monday, February 21st, 2011

My friend asked me, how we should test this piece of code

public void fire(final NotificationMessage message) {
  jmsTemplate.send(new MessageCreator() {
    @Override
    public Message createMessage(Session session) throws JMSException {
      return session.createObjectMessage(message);
    }
  });
}

Mock, stubs, arguments matchers are not successful here. Of course we can mock jmsTemplate, verify if send method was executed, but this way we only test if springframework works properly. Should we leave this to integration test?

Of course not, and our business part is: session.createObjectMessage(message). We have to change our code. First at all we provide second method.

public void fire(final NotificationMessage message) {
  this.fire(message, getMessageCreator(message));
}
public|protected| void fire(final NotificationMessage message, MessageCreator mc) {
  jmsTemplate.send(mc);
}

This two methods are easily testable by using mocks and verifying object interactions. We can decide about method modifier:

  • public – if we want second function to be available in our API.
  • protected – for future subclass usage.
  • package public – for use in package.
  • or even private

Finally we have decide about getMessageCreator(message).

  1. Provide Factory Method for it: MessageCrator getMessageCreator(NotificationMessage message);
    MessageCreator getMessageCreator(final NotificationMessage message) {
      return new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
          return session.createObjectMessage(message);
        }
      };
    }
    
  2. Create Class which implements MessageCreator interface
    public class NotificationMessageCreator implements MessageCreator {
        private final NotificationMessage message;
    
        public NotificationMessageCreator(NotificationMessage message) {
            this.message = message;
        }
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage(message);
        }
    }
    

I think both approaches are ok, so choose better one for you.

Of course you may argue that you don’t need unit test, you will have integration test for that part of the code. Unfortunately integration tests are slow and from time to time they fail, so for simple check I prefer unit test.

Summary

We use a lot of Spring Template Object helpers, and most of the time we are tempted to create anonymous class in place. This way we make our code hard to unit test. Consider this approach to make your code easier to test and maintain. What do you think about that?


Guava – Google Collections

Saturday, January 9th, 2010

Guava

Guava is Google Core Libraries for Java 1.5, it include extension libraries which provides many common pieces of code. Long long time ago apache starts with commons-* libraries, but unfortunately most of them lack java 5 support.

Currently Google Collection is included into Guava and on 30 Dec google released Google Collection 1.0-fianal version. This version is not 1.0 but it has frozen API. It’s nearly done, but it is used in google production projects now.

So, what’s inside ?

  • Immutable Collections
  • Multisets
  • Multimaps
  • New types
  • Static utilitis

Immutable Collections

JDK currently has utility wrapper in Collections which can change our map/set/list into unmodifiable, but this is just a partial solution because internally our collection is mutable. Immutable means that we can never change the object state. So there are:

com.google.common.collect.ImmutableMap
An immutable, hash-based Map
com.google.common.collect.ImmutableSortedMap
An immutable SortedMap
com.google.common.collect.ImmutableBiMap
An immutable BiMap
com.google.common.collect.ImmutableCollection
An immutable collection.
com.google.common.collect.ImmutableMultiset
An immutable hash-based multiset
com.google.common.collect.ImmutableSet
A high-performance immutable Set
com.google.common.collect.ImmutableSortedSet
An immutable SortedSet that stores its elements in a sorted array.

All this Collections don’t allow Null values and Maps don’t allow Null keys or values.

Multisets

Multiset is a type of collection which allows duplicate elements and has unordered equality (lists have ordered equality). A multiset is also called bag. Multiset is better from list in such operation as contains(), checking if two collection are equal ignoring order and providing histograms (providing info about element count). Additionally Multiset performance depends on the number of distinct elements.

There are a lot of different implementation of Multiset interface.

com.google.common.collect.ConcurrentHashMultiset
A multiset that supports concurrent modifications
com.google.common.collect.EnumMultiset
Multiset implementation backed by an EnumMap.
com.google.common.collect.ForwardingMultiset
A multiset which forwards all its method calls to another multiset. (Decorator pattern alike)
com.google.common.collect.HashMultiset
Multiset implementation backed by a HashMap.
com.google.common.collect.ImmutableMultiset
Immputable hash-based.
com.google.common.collect.LinkedHashMultiset
A Multiset implementation with predictable iteration order.
com.google.common.collect.TreeMultiset
Multiset which maintains the ordering of its elements.

Multimaps

Similar to Multiset is Multimap iterface. It provides abstraction like a Map but keys aren’t unique or we can thing about this that unique key has a list of values, so if you have somewhere in the code type such as Map> Multimap is for you. As 1.0 version we’ve got Multimap interface implementation such as:

BiMap

BiMap is the map with unique values. Than it can be inverted so bimap.inverse().inverse() == bimap. There are few implementation of BiMap interface:

com.google.common.collect.EnumBiMap
BiMap backed by two EnumMap instances
com.google.common.collect.EnumHashBiMap
BiMap backed by an EnumMap instance for keys-to-values, and a HashMap instance for values-to-keys.
com.google.common.collect.HashBiMap
BiMap backed by two HashMap instances.
com.google.common.collect.ImmutableBiMap
Immutable BiMap

Static Utility Class

In this category there are a lot of class which has only static members to extend and provide function which are useful but not available today.

Collections2
Provides filter with Predicate and transform with Function methods
Functions
Function extension eg compose
Lists
Provides such methods as new* for easier List creation and two additional methods partition(create sublists of the same size) and transform which takes Function as a parameter and apply it to every list element.
Maps
Provides such methods as new* for easier Map creation, difference method, filter* methods with Predicate, fromProperties, transformValues with Function parameter.
Multimaps
Provides methods such as new*, synchronized*, unmodifiable*
ObjectArrays
Provides contact and newArray methods
Sets
Provides methods: differece, filter, intersecton, new*, union
Suppliers
Some Supplier extensions
Predicates
Predicate extension eg. and, or, not etc
Preconditions
Static methods to be called at beginning of methods to check preconditions.
Objects
Helper for Object class has great hashCode(Object …) method for generating hash code for multiple objects.

And more …

Ordering
Comparator with added methods to support common functions such as min, max etc. So instead of iterate over list to find min value, we can use min(Iterable) method.
MapMaker
ConcurrentMap builder, providing any combination of these features: soft or weak keys, soft or weak values, timed expiration, and on-demand computation of values.
Function
A transformation from one object to another. Used in transform static utility methods for Collection API extension.
Predicate
Determines a true or false value for a given input. Used in filter static utility methods.
Supplier
Class that supply object of single type. Used in new* static utility methods

Final thoughts

So…, in my opinion this library is must have in every project and there are a chance that this library will be standard JDK7 library, there are a lot of structures and static utility methods which makes our code much cleaner and simpler. Googler made great job!

References


Long Time

Saturday, January 31st, 2009

I’m back.

Probably you think that I’m dead but it far from that. Rather I’ve got so many activities that I can’t manage writing about it on my blog. What’s a shame.

First at all in November I must finalize training. It was a lot of work to do, and preparing labs is very difficult task. The training was conducted in December and January, after that I’m very glad because we’ve got 5.24 note in 1-6 scale. Probably our note will be higher but on one of our training we have frustrated colleague with poor technology knowledge so he get nervous and he give us 2.5 note.

During this preparation, I was on JBoss Training. It was JBoss for Advanced J2EE Developers (JB261). It was in Amersfoort. It was one of the best training I’ve had. Maybe the reason was that was only four of us, so after this training participants and trainee is my freind, we have a lot of time to talk, to do extra exercises, it was great time. I have some thoughts about some post from this training.

Few days latter I went to Devoxx. It was quite good conference and we met there our friends so we had hard time, conference from morning to evening and than we tasted Belgium beers. Belgium beers are famous, if you like beer you should visit Belgium.

First Devoxx day I started with Brian Goetz with “From concurrent to parallel”. It was very nice but also hard topic. He talk about evolving concurrency API to support multi-core processors. The Brian’s wisdom is incredible. I’ve just get familiar with current concurrency API, but he is another step further. Next session I went to “Introduction to the SpringSource dm Server with Sam Brannen. It was nice talk but I went also to “How to hack and secure your java web application”, it was happened due to my involvement into security program in my company. Next session I’ve chosen “Envers” probably because Adam Warski is from Poland :) . Due to training the next session was obvious, so I went on “What’s new in Spring Framework 3.0?” Arjen with Alef was talking about new features in Spring Framework, and where was a lots of questions about schedule sources and new spring license policy. The last slot I was in several session and probably JavaFX with applet out of the browser stay in my mind. There was one quickie about “MinuteProject” by Florian Adler. MinuteProject is generator tool. It can generate DAO operation to hibernate/jpa and even iBatis, after this we have a little discussion about MDA and such projects future.

Next day was harder than a day before, but I started with “Be smart!” with Ivar Jacobson. You probably know Jacobson, if not try to get know something about him. It was one of the best session at Devoxx 2008. It will be on Parleys.com so Be smart and watch it. Next session was about JavaFX and after first impression I was a disappointed, but it just version 1.0 we’ll see what happen. Finally there was my favorite session javaposse.com with Belgium beer from Atlassian. After that I took break with my friends and we went outside to discuss sessions. Than I went on two sessions about Seem and preventing bugs. The last was about Hibernate Performance Tuning it was quite interesting. This day was quite nice quickies, one about Atlassian Connector for InteliJ and what I didn’t know that this plugin is developed in Poland.

The last day was short so I with my friends went to Brussels, when we stay for a whole weekend.

Quite long post. I finish it here, because after Devoxx Christmas was came :) .


about me

My name is Sebastian Pietrowski. I've finished Warsaw University as Master degree. During my studies I started work for merlin.pl. The primary language I use is Java but I have also programmed in Python, Ruby and Scala. I worked as a technical solution architect at merlin.pl. infrastructure when we were moving from PL/SQL to J2EE. I engineering a great performance optimized solution that made the application 10 times faster than requirements and 85 times faster as original solution.

Currently, I am working as a Senior Expert at F.Hoffmann-La Roche to help define future roadmap in design and development of Enterprise software at Roche and Genentech and build adoption for new technologies. I'm continuously mentoring new developers, helping them understand how important test driven development is and empowering them to get better at their daily job. I'm involved in many activities which brings new technologies for better and faster development. You can find more details on my LinkedIn profile.

But don’t get me wrong, I am not your typical nerd. I'm a pleasant guy that you can drink a glass of wine with me and talk about a range of topics with. My leisure activities include playing basketball, soccer and listening to music. I try to be pragmatic while staying focused on application performance and tuning with success in my daily work.

My favorite quote from Yoda's and my life’s motto is: Do, or do not. There is no try.