Friday, October 19, 2012

Notes on SpringOne 2012

2012 SpringOne was full of good information like usual. The sad part of 2011 was the absence of Rod Johnson who was supposed to give the Key Note but was apparently sick so could not attend. Spring 2012 was not different in this regard. As we already know Rod departed from Vmware in July. Even though this is supposed to be a straight technical note I could not help to write some words of gratitude to the great Engineer that saved us from the complexities of J2EE taking us into a journey of IoC that we still of course enjoy. Thank you Rod, we owe you a lot!

Back to the event here are some of my notes about it.

The classical Spring Triangle (DI/AOP/Portable Service Abstractions) is being re@annotated (Injection Annotations/Composable Stereotypes/Service Oriented Annotations). All this can be defined with two simple words "Annotated Components".

Stereotype means defining a noun for example @Service. You can compose stereotypes meaning you can build an annotation that groups several others. A composable stereotype model is then just an Annotation definition (Interface) which groups some annotations itself. Injection Annotation defines a need for example @Autowired. Service Oriented Annotations define a capacity like @Transactional, @Scheduled, @Cacheable.

Spring supports a programmatic way of configuring applications. While this can be handy it looks to me like a potential problem for some teams lacking of good architectural direction. Separation of concerns could be easily violated if not used with care. Spring 3.1 takes already advantage of Servlet 3.0: WebApplicationInitializer replaces a lot of xml with java code. There is a composition model, some properties can be in web.xml while others in the Java initializer. There is no overriding mechanism. The application can now be initialized without web.xml help. A couple of methods worth mentioning: scan() and register(). A couple of annotations worth mentioning: @Configuration, @Bean.

Spring 3.2 being in github is now more open for contributions. Expected to be released in December 2012 it features Gradle based build.

Spring 3.3 is expected by the end of December next year. It is based on JDK 8 so it will support and use for JDK closures (lambda expressions), Date and Time API (JSR 310), NIO based HTTP client APIs (getting rid as we all know of jakarta commons http-client), parameter name discovery, java.util.concurrent enhancements.

Support for XML free JPA setup is now available.

MVC on the browser is becoming more popular and Spring is promoting that while proposing architectures like having not only the View but also the Controller in the client (in fact even a local model. This is of course not new, look at Gmail for one popular example. However I would expect Google to have an MVC on the Server side of Gmail as well). Spring propose only the service and data access to live on the server side. I personally have advocated for years that the MVC pattern does not necessarily mean you must have all layers in the Server. That is now a reality with frameworks like Backbone and Angular which deploy Controllers on the Front end and support local storage in browsers. However IMO the interaction between back-end and front-end MVCs might suffer of serious lack of DRY. The proposal to eliminate the Controller completely from the backend IMO could make security even a bigger pain of what it is today. Not to say that moving just the Controller to the Browser does not impose already additional security threats. The reality is that rich applications are demanding more and more and it looks like unavoidable to follow at least *part* of such advice.

Programmatic configuration goes further with MVC Java Config which can be used instead of MVC namespace. I would say that Architects have now bigger concerns about the classical "Where did my Architecture go", so my advice would be "Do review the code!".

Current @Cacheable is proprietary but as soon as Java has the implementation available (JCache JSR-107) Spring will integrate with it. We personally have been enjoying caching for while but it is good to go with the standards (whenever they are kept simple of course).

ASM and CGLIB are included into spring module jars.

Async MVC processing: This uses the Servlet 3 Async Thread Model. There are different approaches depending on the use case: Callable (swaps the servlet container thread by an application thread to process the request. The servlet thread is suspended and later resumed when the request is processed), DeferredResult (Out of Spring process which provide a DeferredResult) and AsyncTask (which wraps a callable to add features like timeout). @RequestMapping methods can return any of these objects. Look at the async tab in the Spring MVC showcase. There is chat sample using redis showing a distributed chat application which uses the async concepts. Long Polling is supported through these async approaches. All Spring Filters have been updated to support async-supported features from the specifications.

There is support for annotation driven JMS endpoint model

Spring will not stop support for java 5 and java 6.

To find out what is new in Spring 3.2 look at Stoyanchev presentation accessible from spring-mvc-32 update github project.

Here is a handy class: UriComponentsBuiolder to build urls

If you are using servlet 3 multipart requests, simplify your life using @RequestPart

Do better exception handling in your applications: @ControllerAdvice allows to globally define @ExceptionHandler to handle global exceptions. The same applies for @InitBinder for global binding and @ModelAttributes across all controllers. Global Exceptions is presented in the Spring MVC showcase project as well.

ContentNegotiatingViewResolver looks by default to the extension of the url to determine the View, then the accept header, url extension and parameter (format which I have been calling in my implementations ert or Expected Response type) in that order.

For error handling now we can rely on Custom Error Page in Servlet 3 (error-page in web.xml).

Path segment name-value pairs are supported through @MatrixVariable

Spring Mobile is an extension to Spring MVC for server side. It compliments client-side mobile frameworks. It does device detection, site preference management (storage engine for user preferences - by default cookies), site switcher (to switch from mobile and desktop). LiteDeviceResolver is the default implementation. Other classes to take a look at: DeviceWebArgumentResolver and DeviceResolverHandlerInterceptor. Support for Java configuration will be added soon. The site switcher capability approach which redirects to different sites for different devices does not look very DRY to me.

Platform targeted Sites can be developed using technologies like Lumbar and Thorax. I am not a big fan of this to be honest. I already explained my position about MVC, DRY and the need of a Business Hub when building web applications. In terms of selecting which front-end pieces should be included in one project or the other we have been using Maven overlays with success so I personally am not embarking on this.

Still CouchDB is not supported in Spring Data. I suggested looking at the Ektorp project for this. The familiar Spring Template pattern is used to access the supported NoSQL DBs. CrudRepository, PagingAndSortingRepository are some of the class worth to mention here. Implementing CrudRepository the JPA entity can be directly exposed via REST. JSON is first class universal protocol for this. Even for JPA you can use CrudRepository which exposes basic operation on entities. The entities can be exported automatically using REST semantics. I suggested looking at jpasecurity project for some enhancements in Spring Data project.

QueryDSL is less verbose than JPA2 Criteria API and Spring has embraced it for their data project.

The spring projects are in github which we already know is great for code collaboration as well as code review. Spring team calls the code review part "Jurgenization" prizing Jurgen contributions to coding conventions. They are migrating to Gradle everything they can.

Websockets support is not fully standardized yet but Spring has been working on it. Websockets try to solve issues like too many connections, too much overhead, burden on the client side. Trading, chat, gaming applications, collaboration, visualizing a lot of data are good candidates to take advantage of websockets. The Websocket Protocol (RFC 6455) uses HTTP to bootstrap but it runs on TCP directly, this is a low overhead solution. A simple header is sent by the client "Upgrade: websocket", the server replies a 101 "Switching Protocols" status code with a header "Upgrade: websocket". The library called d3.js is a good library to visualize data which the guys at springsource have used combined with vert.x library to rewrite the application (which uses Long Polling) using websockets (In there are several implementations using different technologies). From chrome the websocket protocol frames can be inspected. The technology is still new and a lot of users are still on browsers which do not support websockets. Existing proxies become a problem for websocket support. Encrypted (wss:) traffic will create better possibilities to go around this issue. Some manual configurations could be needed in browsers and server side proxies. Keeping connections alive is a problem when using websockets. Out of the box there is no confirmation of message delivery (even though there is "ping-pong" which can be used to provide "keepalive" and "heartbeat"). In Java the Java API for websockets (JSR-356) is still evolving and most likely will not be tied to Servlet specification. Spring plus vert.x can be used to develop applications based on websockets. Sock.js is a great client side library to implement websockets applications, it would fall back to other means of push protocols when the client does not support websockets so sock.js is definitely an excellent API to do asynchronous messaging between client and server. The message from Spring team: Websockets is a promising technology as a complement but it is not a silver bullet, the need for fallback options will be there for a long time. Backward protocol support is an important niche for Frameworks which Spring probably will address in future versions.

Springsource is promoting "Spring MVC used less for page rendering, more for REST API". we saw that from the second Key Note and also from several other presentations. Hence the search for a good front end framework starts and the options are really huge. Mustache is one good template library just to mention one, look for alternatives to see the rest. Backbone is one of the most popular MVC javascript frameworks.

REST support is fully supported in Spring, for example @PathVariable binds to the JSON request specific path. Spring (Data) REST uses Spring HATEOAS. Wikipedia says "The HATEOAS constraint serves to decouple client and server in a way that allows the server to evolve functionality independently" which I still have to see to believe. Design by Contract cannot be ignored and developing a client that will adapt on the fly to new servers needs is not something we mere mortals can do in 2012. Just the fact that the resources available can be listed does not guarantee the above, not to mention concerns about security.

While REST might be the way you want to go when all your clients will be speaking REST the reality is that this does not comply with my idea of a Business Hub (BHUB). As a reminder this idea is what allows me to serve the resources from one entry point and leave a View resolver determine what type of response the client needs. This is not just about a javascript client framework but about reports rendered in pdf or Excel for example. Of course is kind of impossible to get both: real REST approach and a Business Hub approach. This is because you cannot force non rich web clients to use JSON posts. On the other hand your REST applications need as much documentation as a proprietary BHUB approach. With BHUB you play just with normal POST, GET parameters and you certainly get JSON (but not limited to) back.

Spring Mobile has cool projects like Urban Air Ship to abstract the way you use push notifications for different platforms like Apple iPhone.

A JBoss presentation discussed the Spring and JEE coexistence. There will be always a space for Service simplification. In particular JPA (and JNDI), JTA, JMS, JCA,EJB, Cache (JSR-107), WebSockets (JSR-356), CDI and Bean Validations 1.1 are services that the JEE application server is already providing and Spring will transparently use those (if available) provided the correct configuration exists. So the point is Spring does support JEE provided services and not just plain servlet container servers like Tomcat where non of these services are available nor deployed by default (certainly there are ways but with Spring there you rarely use those for non JEE containers). Other capabilities like JSONP is simple enough and Spring will not introduce any simplifications. Multithreading and Spring Batch are still preferred to the vendor specific JSR 237 (WorkManager) which was withdrawn anyway in favor of the Java Concurrent API (JSR 236), dormant since 2003 but recently announced it should come to lige in Q1 2013. The use of Arquillian is again proposed to test JEE based code. I think I already blogged about my opinion on this when I posted about JavaOne. The Seam framework/CDI (JSR-299 ) extensions have been donated to Delta Spike and yet CDI beans can be used from Spring. In fact there is work in progress for bidirectional injection from CDI to Spring and the reverse. In JEE7 that bidirectional relation is getting tighter. The integration with JEE is a high priority for Spring.

IOC in Javascript looked appealing for those not happy with functional programming. IMO separation of concerns should reign and a Front End Engineer cannot say Functional Programming is not a perfect paradigm for the event driven nature of UIs.

A migration to a JSR-352 approach was demonstrated showing how Spring adapts easily as in fact many ideas of the specification come from the Spring Batch implementation. I have to say this again this year, I will not comment on Spring Batch versus ETL tools because I believe it is matter of how you structure your team and probably a subject for a lot of complex considerations that go beyond simple software development. For now I am not planning on using Spring Batch.

Some interesting notes on Testing: MockMvc allows to test Controllers. I personally think your behavior tests (with Selenium Web Driver) should cover anything wrong with Controllers however there is more about the Spring Test MVC. New @WebAppConfiguration (defaults to src/main/webapp) in Spring 3.2, @ContextConfiguration defaults to get a local file with the name of the class followed by "-context.xml" in the same path. Using EasyMock and a factory method Spring manages to inject mocked objects for testing. Mockito is also supported through a constructor passing the to-be-mocked class. In both cases a Factory is in charge of generating the mock. MockServletContext, MockHttpSession, MockFilterChain, MockClientHttpRequest and MockClientHttpResponse have been introduced. Here is another concern for Architects: I only hope developers will not put servlet scope objects (request, context, response, session) in services now that you can mock those from Spring. An ApplicationContextInitializer can be used to avoid annotations or xml for initializing the Spring Context for testing. Sprint Test MVC is an independent project, it depends on spring 3.2. Some limitations: No forward nor redirect, no JSP rendering, other rendering technologies do work as they do not depend on a real servlet container. I still believe Selenium WebDriver is the best way to test that tier in any case (Granted the problem is with side effects). In any case there is value on Controller Unit Test of course. IMO this framework creates interesting possibilities to perform automated Security tests like XSS attacks for example, however as noted before JSP won't be supported. You can check not only status, headers and content but flash attributes, handler, model content from Spring context as well. The method alwaysDo(print()) is used to provide information about the "perform" action. Method andReturn() will return all context servlet main objects in case we want to assert more specific data not available yet from the framework. Testing filters is powerful for example for spring security filter testing. HtmlUnit enables using Selenium tests but again that is not available for JSP. Learn more about this from the spring-32-test-webapps github project. In addition there are client and server tests in the Spring Framework itself so get the source code from github and start your own journey of fresh spring simple coding.


Deryl Spielman said...

You can see a full blown no xml Java config only Spring MVC 3.1 app with Spring Data on my GitHub project, which has a lot of the features you have mentioned.

Nestor Urquiza said...

@Deryl good stuff. Thanks for sharing.