Tuesday, May 17, 2011

Annotation scanner with Spring

Spring framework, from version 2.5, can retrieve bean based on an annotation set such as @Service, @Repository. This mechanism uses an annotation scanner to retrieve the annotated classes through the classpath.

As Spring is easily extendable, it is possible to work with an annotation scanner dedicated to our own annotations.

The annotation

The annotation we want to use as a class marker, is not a psecial Spring define one. The only requirement is the retention must be runtime and the target must be at least TYPE.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation { }

The scanner

Firstly, we need to create an application context:

GenericApplicationContect applicationContext = new GenericApplicationContext();

And now, the annotation scanner:

ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(applicationContext, false);

An annotation scanner needs an application context to store retrieved classes. The second parameter is used to avoid this scanner search after Spring framework defined annotations. Now, we must configure the scanner to retrieve only our annotation:

scanner.addIncludeFilter(new AnnotationTypeFilter(MyAnnotation.class));

Several filters are available to include or exclude classes from the search, such as RegexPatternTypeFilter.

To trigger the scanning, we must call scan method with a package list as string array:

scanner.scan(packageNames);

Now, just refresh the context and get the annotated instance:

applicationContext.refresh();
Map<String, Object> result = applicationContext.getBeansWithAnnotation(MyAnnotation.class);

The map key is the bean Spring id, and the value is an instance. By default, the id is the simple class name.

Thursday, March 3, 2011

Parameterized Unit Tests

Recently, I have to write a unit test to check link reference validity in static HTML pages. The problem is: how to run test for each URL, without hard coded HTML files location (what append if several files are added ;) and with a minimum of code. The answer is provided by JUnit itself. From version 4, parameterized tests are included: it is a runner that is able to get a collection of values and to execute a test for each of these values.

A parameterized test looks as following:

@RunWith(Parameterized.class)
public class ParamTest {

private String msg;

public ParamTest(String msg) {
this.msg = msg;
}

@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {{"first"}, {"second"}, {"third"}});
}

@Test
public void test(){
System.out.println(msg);
}

}

To get a parameterized test, it has to declare a specific runner with: @RunWith(Parameterized.class). And a static method that return a Collection<Object[]>. By this way, several arguments can be passed. This method must be annotated with @Parameters that declares the method as a parameters provider. A constructor with all arguments as parameters must be written. Then runner will execute the parameters method provider, and for each value, it creates an instance of the test and execute it. So, to use parameters, the constructor can save them as class attributes.

The result is:

first
second
third

Parameterized tests mechanism brings a simple and ellegant way to test things that are not fix.

Sunday, February 13, 2011

Emulate a non supported class in GWT

To develop with GWT, only a Java SDK subset is available, plus GWT specific classes. Mainly (look at JRE emulation for details):

  • java.lang
  • java.lang.annotation
  • java.util
  • java.io
  • java.sql

This emulation mechanism is used to bypass GWT limitations, such as, no reflection due to the JavaScript translation.

As GWT support only a few JDK classes, as developers, we often miss something to do the work. To fill the gap, it is easy to use emulation to implement a full GWT compliant class. To do so, the best practice is to create a directory out of the class path named super, that will contain the emulations. The name of this directory has no importance, it is just done that way in GWT sources. Your package structure takes place under this directory. At this place, a module must be created, it contains only a super-source directive as following:

<super-source path="source_location"/>

path attribute provides the root directory of simulated classes. For example, to simulate a class from package java.io:

The reason to not include emulated classes in classpath, is, these classes must declare the package name from the class they emulate, not the package previously defined:

package java.io;

Now, to use these classes, you should only inherits from the emulation module.

Thursday, December 2, 2010

Devoxx 2010 daily notes: day five

Apache Camel, a powerful open source integration framework

Apache Camel is a parent of ServiceMix and Active MQ. The project has been initiated as a routing library.

Why integration?

  • different stack technology
  • business need

This integration framework is:

  • based on Enterprise integration patterns
  • includes 50 patterns
  • 80 components for connecting to other systems
  • 19 data format for transformation
  • 14 expression languages
  • DSL in three languages: XML, Java and Scala
  • security integration
  • event notification
  • route policy
  • threading model (non blocking routing engine)
  • heavy lift
  • focus on business
  • famous pattern-context based router

Tooling is available for IDE.

The roots of Java EE 6: JSR-299 (CDI) and Weld extensions

Weld (reference implementation) is available in servlet container, it implements CDI.

JSR-299 provides:

  • services for Java EE
    • life cycle management for context
    • type safe dependency injection
    • event notification
    • reduce coupling beans/interceptors
    • decorators intercepting beans (AOP)
    • EL integration
  • extension SPI

Available extensions:

  • hooks on container starting
  • hooks JEE transaction boundaries

Definition by XML is available.

Friday, November 19, 2010

Devoxx 2010 daily notes: day four

Java EE Key Note: The Future Roadmap of Java EE

Java EE wil evolved to cloud platform and, to do so, it will needs modularity based on Java SE.

JSF 2.1

JSF 2.1 will propose:

  • transient state saving
  • XML view cleaning
  • targeted to HTML 5

JMS

JMS is an old specification, which need to evelove for addressing new communication layers:

  • resolving specification ambiguities
  • standardized vendor extension
  • integration with other specifications
  • integration with the web tier (websocket, JSON, NIO2)

JPA 2.1

JPA targets to improve standardization, flexibility and control of persistence context synchronization. The metamodel will be extended to ORM.

Several addition will take place in this release:

  • add event listener
  • outer join with ON conditions
  • update and delete query based
  • mapping between JPQL and criteria queries
  • DB and vendor function invocation
  • support stored procedure

The expert group will be done for january 2011, but the release date could be delay by J2EE timeline (modularity is waiting for Java SE 8).

JAX-RS

JAX-RS 2.0 should be commited in december.

Actually, JAX-RS specification is not included into web profile.

A client API will be added:

  • low level builder pattern
  • high level response matching

JAX-RS will be adapted for MVC architecture based on JSP and Scalate.

Asynchronous, base on Atmosphere (HTTP streaming), will be too added with validation and injection. For exeample, @Context will be replaced by @Inject).

Comparing JVM Web Frameworks

In 2004, criteria to choose a web framework were:

  • request, component or RIA
  • stateful or stateless
  • project community
  • project futur
  • maintenance
  • technical features

And the choice could be described this way:

  • High traffic: request framework
  • Intranet: component
  • Products: products vendor

Now, in 2010, criteria are:

  • development productivity
  • developer perception
  • learning curve
  • project health
  • developer availability
  • job trends
  • templating
  • components
  • ajax
  • plugin
  • scalability
  • REST support
  • multi language
  • validation
  • books
  • doc
  • mobile
  • risk

After a comparison, to top five is:

  • Spring MVC (pro: configuration, integrtion, REST support; cons: instant reload)
  • GWT (pro: write in Java, easy to learn; cons: slow compilation)
  • Rails (pro: easy to learn, doc; con: performance, development tools)
  • Grails (pro: esay for Java programmers; cons: targeted to Java programmers)
  • Wiket (pro: for Java developpers; cons: no developpers available)

Standard DI with @Inject and JSR-330

CDI is a joined proposition from Google and Spring. It is resumed by five annotations and one interface.

@Inject identifies injectable members, that can be any visible fields (static or instance).

Injection order is:

  1. constructor
  2. fields
  3. methods

By default each time an injection must be done, a new instance is created.

@Qualifier allows to solve naming ambiguities by providing a way to create annotation to qualify a classe.

Interface Provide is a kind of factory where injection is not enough to create an object.

Guice and Spring Framework implements this JSR.

The Java Persistence Criteria API

JPA started with JPQL, a SQL like query language that can be used in static queries (@NamedQuery) and dynamic queries.

JPQL for dynamic query is:

  • String based: very easy to do
  • SQL like syntax
  • But it is String: risk of performance lost, lost of readability
  • No type safety

Criteria API is object based and typesafe (use of a metamodel).

CriteriaQuery are composite:

  • roots
  • join
  • expression
  • predicates
  • selections
  • ordering
  • grouping
  • method to assign: select(), multiselect(), from()
  • browse result: getSingleResult()

CriteriaBuilder: a factory of CriteriaBuilder for Expression and Predicate:

select c from Customer c;

TypedQuery tq = em.createQuery(Customer);

List resultList = tq.getResultList();

  • join -> root.join("orders");
  • where -> cq.where(cb.equal(root.get("...")).select(root)

There is hole in type safety in join and where: usage of string to specify attribute name.

The solution used by JPA is to generate at compile time a static metamodel (logical view).

Directly accessible via EntityManager.getMetamodel(), it is defined by a hierarchy of interfaces to describes types and attributes. So, browsing the metamodel is possible.

Now, it is possible to replace String in criteria by metamodel attribute or by accessing directly to the metamodel (path navigation).

Path navigation brings tha ability to access attributes of composite object: c.get(attribute_a).get(attribute_b). It is used to compound predicates.

CriteriaQuey is able to create subqueries and to call database specific function: cb.function("NAME", return_type, path);

Criteria parameters are created by using CriteriaBuilder and can be named.

Queries are modifiable.

HTML 5 Fact and Fiction

HTML 5 is mainly a collection of features.

It is actually better supported on mobile devices than on desktop.

HTML 5 is driven by mobile development. Developping a native application for each platform is too cheaper, we need a common platform, and this the web.

Feature detection can be done with Javascript and preferably by using library such as Modernizr.

Now, browser evolution is driven by specification. This can avoid a quirck mode where standard is more or less respected. HTML header file becomes:

HTML brings very feww components. So, developers uses external library, but there is no standard. HTML 5 comes with new input types. If they are not yet supported by browser, a text field is displayed. One of the target of such component is to brings facilities to mobile devices. For example, an email input field results to the @ symbol to be directly available on the keyboard.

It defines too things that are used from decades such as headers and footers.

It brings too:

  • autofocus
  • local storage: response to heavy cookie usage
  • offline mode: cache the application
  • microdata: semantic web
  • multithreading
  • geolocation (not part of HTML 5)

Activiti in Action

Activiti is a BPM open source tool , it is now mainly developed by Alfresco, but these are 2 distinct products, it is supported by SpringSource and Signavio. Activiti is based on the BPMN 2.0 standard, and the data can be persisted in an XML format.

Activiti allows you to model a process in BPMN 2.0 using “Activiti modeler” (from Signavio), or via an eclipse-based interface. At each step of the process, you can define who can execute the task, and define what are the information that should be filled in. Afterwards, you can initiate process instances, and each person involved will have access to the “activiti explorer” where he will have the possibility to fill in the required information. Once a process step is completed, activity notifies the next person involved that he has a task to do. The “activiti explorer” also provides analysts with process instances status and statistics (it is also possible to create easily a BIRT report about process instances report).

Activiti also provides other modules:

  • Activiti Probe (check process status)
  • Activiti Cycle (BPM collaboration platform)
  • iPhone client
  • Grails integration

Finally, Activiti is highly customizable and can be easily embedded into another application (you can, for instance, request to add a document into Alfresco at a particular process step using 5 lines of Java code …)

  • SpringSource provides an integration via a bean
  • A full query API provides access to the Activiti data
  • REST interface provided (used by an iPhone application

Thursday, November 18, 2010

Devoxx 2010 daily notes: day three

Java SE Keynote

Java platform is now targeting:

  • productivity
  • performance
  • universality
  • modularity
  • integration

Java language evolution will be:

  • for generics: declarations like: HashMap<String, List<String>> map = new HashMap<String, List<String>>(); will become: HashMap<String, List<String>> map = new HashMap<>();
  • lambada expressions will be added (JDK 8)
  • type reification: primitive type will be used as generics
  • module will be added: based on descriptor (module-info.java) and manage by JMOD (integration with maven and its repositories)
  • module will be able to be package as RPM, JAR or DEB or directly managed by JMOD

Java evolution has been planned until 2030.

For the roadmap:

  • Java 7: end of july 2011 (project coin, fork/join framework)
  • Java 8: end of 2012

Java Persistence 2.0

JPA 2.0 brings some news:

  • Criteria API
  • pessimistic lock
  • metamodel API
  • standardize configuration
  • collections of basic types

Basic types collections:

  • @ElementCollection: this collection must be stored as an elmeent collection
  • @CollectionTable(...): specify the table name
  • @Colcumn(...): specify the collection column name

Embadable objects:

  • multi level (@AttributeOverride)
  • relationship (@AssociationOverride, @JoinTable)

Persistence order:

  • implemented by provider as an additional column (@OrderColumn)
  • in case of legacy use @OrderBy to use existing schema

Maps usage:

  • key: basic type, embeddable, entity
  • value: basic type, embeddable, entity

JPQL:

  • conditional expression: CASE ... THEN .. (usefull with map)
  • restriction on type TYPE(e) IN (...) (usefull for inheritance)

Criteria API: support object and strinf literals

  • CriteriaQuery: query description
  • CriteriaBuilder: criteria query objects factory
  • How to express: select c from Customer
    CriteriaQuery cq = criteriaBuilder.createQuery(Customer.Class);
    Root root = cq.from(Customer.class);
    cq.select(root);

Metamodel: abstract schema model.

Pessemistic lock: specify mode as properties.

Second level cache API: use of @Cacheable on properties

Standardized configuration by providing a set of default properties.

Validation: automatic validation for PrePersist, PreUpdate and PreRemove.

The Next Big JVM Language

Actually, languages challenge Java by providing more features and different expression ways (have a look to Stephen Colebourn).

What Java has done right:

  • simplify C++ migration
  • take old ideas but JVM make them popular (garbage collector for example)

What Java has done wrong:

  • Checked exception: how to ignored them?
  • primitives: split type system
  • arrays: split type system and expose JVM future
  • monitors: unsafe effects, difficult to optimize
  • static: cannot be override, hurt concurrency
  • method overloading: complexity for compiler and for programmer
  • generics: too complex, background compatibility result in erasure

The New Big JVM Language should be:

  • like C syntax
  • multi paradigm: object oriented and functional
  • type system: static typing
  • easy reflection
  • have properties
  • have closure in language core
  • a better null handling (avoiding NullPointerException and long and borring debugging)
  • thread not exposed
  • have modules
  • good tooling (make tooling esay to build)
  • extensible (combination of language feature)
  • not verbose

No JVM languages fullfil these criteria, so, perhaps it is time for a none backward compatible version of Java: Java 9?

Project Lambda: To Multicore and Beyond

The based of Lambda project is SAM types: interfaces or abstract classes with a single abstract method.

Closure take the following syntax:

#{Person.getLastName()}

Collection framework will be adapted to provides facilities based on closure, such as filtering, sorting, etc...

New key words will be added to define immutable classes and their properties:

value class ImmutableClass {  
properties String lastname;
}

Actually, modifying an interface results to breaking API compatibility. With Lambda, it will be possible to add method with default behavior.

Spring 3.1 - Themes and Trends

Spring 3.0 brings:

  • annotated component model
  • expression language
  • REST support
  • Portlet 2.0
  • support Java EE 6 (JPA 2)
  • custom annotation
  • include JavaConfig (configuration classes)
  • @Value (use of value express with EL)
  • model validation @Valid on parameters
  • type conversion @DateTimeFormat(iso=ISO.DATE)
  • annotation scheduling: @Scheduled

Spring 3.1 will provide:

  • environment profiles
    • activated in command line by: -DspringProfile=env
    • provides environment abstraction as an API
    • custom placeholder resolution
  • java based configuration: @Configuration on class
  • cache abstraction
    • EhCache support (important for cloud)
    • support for Gemfire, Coherence
    • annotation @Cacheable
    • cache could be conditional
    • @CacheEvict to avoid caching
    • new namespace declaration
  • conversation management:
    • HttpSession ++
    • association with browser and tabs
    • foundation for WebFlow 3
  • Groovy will be used as template engine
  • c: namespace for constructor arguments
  • Roadmap:
    • M1 in december
    • 3.1 GA march/april 2011

HTML 5 Websockets: A New World of Limitless, Live, and Wickedly Cool Web Applications

Actually, HTTP is not full duplex, so, Websockets brings full duplex to web.

It is implemented as a Javascript API that uses IETF protocol, but is still compatible with HTTP. The idea is not to replace HTTP.

Websocket allowed cross origin, secured and unsecured communication in standard.

It is supported by browsers:

  • Chrome 4.0+
  • Safari 5.0, iOS 4
  • Firefox 4 beta
  • to check compatibility, go to Websocket web site

Beyond the scene, Websocket allows:

  • connection reuse
  • extends client server protocol (available in JS API)
From the tests, Websocket, compared to pure HTTP, reduce latency from 150 ms to 50 ms.

Visage Android Workshop

Visage is a dynamic UI language inspired by Flex and JavaFX for different target, and especially, for Android.It is declarative, brings data binding, provides closure to implements triggers and brings null safety.

Compilation is divided in two phases:

  • Visage to Java bytecode
  • Bytecode to Dalvik

Tuesday, November 16, 2010

Mockito: a quick tour

Mockito is a test framework for building... mock objects. The development team has known learn from other similar frameworks like JMock, EasyMock. It is based on a DSL to stub the mock implemented by fluent interfaces and can mock classs and interfaces.The restrictions are:
  • can't mock static classes
  • can't mock final classes
  • can't mock static methods
  • can't mock equals and hashCode

So, lets go for a quick tour.

First Sample

As usual, we create a DAO interface, thtat is used by a service:

public interface SampleDao {

Sample findByPrimaryKey(Long id);
}

public class SampleService {

private SampleDao sampleDao;

public void setSampleDao(SampleDao sampleDao) {
this.sampleDao = sampleDao;
}

public boolean exists(Long id) {
return sampleDao.findByPrimaryKey(id) != null;
}
}

To test our service, we need to create a mock of the DAO:


public class SampleServiceTest {

private SampleService sampleService = new SampleService();
private SampleDao sampleDao;

@Before
public void setUp() throws Exception {
if(sampleDao == null) {
sampleDao = Mockito.mock(SampleDao.class);
sampleService.setSampleDao(sampleDao);
}
}

}

Creating a mock is simply done by calling mock method on a class object. Mockito can mock interfaces, it is the minimum for a mocking framework, but it can also mock classes in its standard edition. For example, EasyMock can mock classes, but an extension must be used to do so. When an object is a mock, if no behavior is specified, methods return the default return type value.

Our test is quiet simple, and the return value of findByPrimaryKey is correct. But how can we be sure our DAO code is called. Mockito provides an easy way to check.

public void testExists() {
Random random = new Random(System.currentTimeMillis());
Long id = random.nextLong();
boolean result = sampleService.exists(id);

Mockito.verify(sampleDao).findByPrimaryKey(id);

Assert.assertFalse(result);
}

By this way, Mockito check if the method findByPrimaryKey has been called only one time, and with id as parameter. If no verify is implemented in test, no check is done on the method execution. So, the order in which the behavior is implemented does not have any importance, and mock building is uncoupled to the method call stack.

Implementing behavior

Implementing the behavior is called stubbing in Mockito. In our previous sample, the mocked DAO uses the default behavior, i.e. findByPrimaryKey always return null. But how to configure the DAO for a call to exists return true?

public void testExists() {
Random random = new Random(System.currentTimeMillis());
Long id = random.nextLong();

Mockito.when(sampleDao.findByPrimaryKey(id)).thenReturn(new Sample());

boolean result = sampleService.exists(id);

Mockito.verify(sampleDao).findByPrimaryKey(id);

Assert.assertTrue(result);
}

It is very simple to implement. Method when encapsulate a call to the stubbed method, and method thenReturn provides the object to return on a method call. By stubbing the method this way, we say that a new Sample object is returned for this specific id value. In our case, there is no importance, because we produce this id. But in other case we don't known the id value, Mockito provides us way to implement more complexe behavior depending of the passed arguments.

We can also throw an exception on a method call. For example, we can suppose our findByPrimaryKey does not return null when no data has been found, but throw a EntityNotFoundException (JPA API). Our exists methods becomes:

public boolean exists(Long id) {
try {
sampleDao.findByPrimaryKey(id);
} catch(EntityNotFoundException e) {
return false;
}

return true;
}

And the test:

public void testExistsNotFound() {
Random random = new Random(System.currentTimeMillis());
Long id = random.nextLong();

Mockito.when(sampleDao.findByPrimaryKey(id)).thenThrow(new EntityNotFoundException());

boolean result = sampleService.exists(id);

Mockito.verify(sampleDao).findByPrimaryKey(id);

Assert.assertFalse(result);
}

Now, we have two tests. Each one implements its own behavior on the DAO. To unregister behavior on mock, we have to reset it:

@After
public void tearDown() throws Exception {
if(dao != null) {
Mockito.reset(sampleDao);
}
}

Deal with void return method

Now, we know how to stub a method with a non void return, but how to implement behavior on this kind of method. To do it, we add a method to our DAO interface:

public interface SampleDao {

Sample findByPrimaryKey(Long id);

void update(Sample sample);
}

To mock it, we have to change a little the stubbing syntax. In place of writing:

when(mock.call_to_the_method).then()

The syntax becomes:

doNothing().when(mock).call_to_the_method

The standard behavior of an update method, is to call a findByPrimaryKey method to retrive tha actual stored bean values. In case of no bean has been found, the EntityNotFoundException is thrown.

To implement the case of update success:

Mockito.doNothing().when(dao).update(new Sample());

To implement the case of update failure:

Mockito.doThrow(new EntityNotFoundException()).when(dao).update(new Sample());

Advanced Stubbing

Until now, we have implemented simple stubbing. So, it is time to look at advanced stubbing, and to do so, we take our two test methods on exists and turn them in one, and we implements a behavior, which is able to throw an exception or return something depending of the parameter. I'm agree: if I do that, I can't check service return, but this is only for example, so be indulgent.

public void testExists() {
Random random = new Random(System.currentTimeMillis());
Long id = random.nextLong();

Mockito.when(sampleDao.findByPrimaryKey(id)).thenAsnwer(
new Answer<Sample>() {
@Override
public Sample answer(InvocationOnMock invocation) {
Long id = (long) Invocation.getParameters()[0];
if (id > 10000) {
throw new EntityNotFoundException();
} else {
return new Sample();
}
}
});

sampleService.exists(id);
Mockito.verify(sampleDao).findByPrimaryKey(id);
}

Now, is id is greater than 10000, an exception is thrown, else, a new Sample object is created. Answer is an easy way to implements behavior depending of method parameters. But, its usage must not be systematic. Then().do...() syntax should be mostly used.

For now, we have to specify for which id, our behavior is implemented. But we implements that for any id, isn't it? Mockito comes with matchers to express this kind of constraints:

public void testExists() {
Random random = new Random(System.currentTimeMillis());

Mockito.when(sampleDao.findByPrimaryKey(Mockito.anyLong())).thenAsnwer(
new Answer() {
@Override
public Sample answer(InvocationOnMock invocation) {
Long id = (long) Invocation.getParameters()[0];
if (id > 10000) {
throw new EntityNotFoundException();
} else {
return new Sample();
}
}
});
sampleService.exists(random.nextLong());
Mockito.verify(sampleDao).findByPrimaryKey(Mockito.anyLong());
}

WARNING: it is not possible to use matcher on only one stubbed method parameter. Each method parameter must use matcher, else, Mockito throws a InvalidUseOfMatchersException.

It is finished for this quick tour. For furthur, go to the Mockito documentation page and have a look to documentation.