Archive

Archive for the ‘Technical’ Category

Deployit, deployment automation made easy

May 5th, 2013 2 comments

DeployitTwo weeks ago, I attended the first Swiss JDuchess workshop in Geneva. It was about Deployit, a software to enable continuous deployment. I had already been introduced to it at Devoxx France 2012, and it had been a surprise… a very good one.

Unfortunately, the workshop was a failure, at least for me: I couldn’t import the provided Virtual Machine. Given the very positive feedback of the other attendees, I decided to run it some time later at home. This time, it worked like a charm.

By the way, congrats to Benoit Moussaud, Technical Director at Xebialabs France, because everything in the workshop works flawlessly. I’ve attended paid trainings with material of much worse quality.

Deployit is based on the following core concepts:

  • Deliverables are versioned artifacts to be deployed, e.g. a WAR, a EAR, a ZIP archive of web resources, a SQL script, …
  • Environments are containers artifacts run in, e.g. a servlet container, an application server, a web server, a database, …
  • Bindings between a pair of the former
  • Dictionaries to resolve placeholders, so that the same deliverable can be deployed in different environments

There’s no magic in how Deployit works, it uses existing parts of modern development environments, most notably CI servers. The only requirement is to have a dedicated Maven project that creates so-called DAR archives, which are nothing more than ZIP files wrapping all resources mandatory for a deployment. A dedicated Jenkins plugin takes care of providing produced artifact to Deployit console.

At that point, only one action is necessary: bind between each resource and a container (or multiple containers). For example, I would map the WAR to Tomcat and the SQL scripts to MySQL. Even better, if matching tags are set on both deliverable and environment, this step becomes optional. Also, providing the right dictionary for this deployment plan may also be needed (see above).

Deployit admin console

Now, the Jenkins plugin is able to see the plan, so we can launch it as part of the build process! In effect, this means we achieved a whole automated build pipeline, from compiling to deployment and including all needed tests.

Of course, there are some more features provided by Deployit (for example, how to launch a plan with the CLI, but those are only nice-to-have, not core. If you want to see more, I suggest heading toward the product page.

Notes:

  1. Deployit is (unfortunately) not OpenSource
  2. I don’t know about any Deployit competitor. Hints welcome as I think competition is a sure way to up the ante…

To go further

Categories: Technical Tags: ,

Integration tests from the trenches

April 28th, 2013 No comments

This post is the written form of one of my submission for Devoxx France 2013. As it was only chosen as backup, I lacked the necessary motivation to prepare it. The subject is important though, so I finally decided to write it down.

In 2013, if you’re a standard developer, it is practically a given that you test your code. Whether you’re a practicioner of TDD or just create them afterwards, most realize a robust automated test harness is not optional but mandatory.

Unit Test vs Integration Test

There’s some implicit behind the notion of ‘test’ though. Depending on the person you ask, there may be some differences of what a test is. Let us provide two definitions to prevent potential future misunderstanding.

Unit test
A unit test tests a method in isolation. In this case, the unit is the method. Outside dependencies should be mocked to provide known input(s). This input can be set different values, including bordercase values, to check all code branches.
Integration test
An integration test tests the collaboration of two (or more) units. In this case, the unit is the class. This means that as soon as you want to check the execution result of more than one class, it is an integration test.

On one hand, achieving 100% UT sucess with 100% code coverage is not enough to guarantee a bug-free application. On the other hand, a complete IT harness is not feasible in the context of real-world project since it would cost too much. The consequence is that both are complementary.

Knowing the good IT & UT ratio is part of being a successful developer. It depends on many factors, including some outside the pure technical, such as the team skills and experience, application lifetime and so on.

Fail-fast tests

Most IT are usually inherently slower than UT, as they require some kind of initialization. For example, in modern-day applications, this directly translates to some DI framework bootstrap.

It is highly unlikely that IT be successful while UT fail. Therefore, in order to have the shortest feedback loop in case of a failure, it is a good idea to execute the fastest tests first, check if they fail, and only execute slowest ones then.

Maven provides the way to achieve this with the following plugins combination:

  1. maven-surefire-plugin to execute unit tests; convention is that their names end with Test
  2. maven-failsafe-plugin to execute integration tests; names end with IT

By default, the former is executed during the test phase of the Maven build lifecycle. Unfortunately, configuration of the latter is mandatory:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-failsafe-plugin</artifactId>
        <version>2.14.1</version>
        <executions>
          <execution>
            <goals>
              <goal>integration-test</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Note the Maven mojo is already bound to the integration-test phase, so that it is not necessary to configure it explicitly.

This way, UT – whose name pattern is *Test, are executed during the test phase while IT – whose name patter is *IT, are executed in the integration-test phase.

System under test boundaries

The first step before writing IT is to define the SUT boundaries. Inside lies everything that we can manage, outside the rest. For example, the database clearly belongs to the SUT because we can easily provide test data, whereas a web service does not.

Inside the SUT, mocking or initializing subsystems depend on the needed/wanted integration level:

  1. To UT a use-case, one could mock DAOs in the service class
  2. Alternatively, one could initialize a test database and use real world data. DBUnit is the framework to use in this case, providing ways to initialize data during set up and check results afterwards.

Doing both would let us test corner cases in the mocking approach (faster) and the standard case in the initialization one (slower).

Outside the SUT, there is an important decision to make regarding IT. If external dependencies are not up and stable most of the time, the build would break too often and throws too many red herrings. Those IT will probably we deactivated very quickly.

In order to still benefit from those IT but so that they do not get ignored (or even worse, removed), they should be put in a dedicated module outside the standard build. When using a continuous integration server, you should set two jobs: one for the standard build and one for those dependent IT.

In Maven, it is easily achieved by creating a module at the parent root and not referencing it in the parent POM. This way, running mvn integration-test will only launch tests that are in the standard modules, those that are reliable enough.

Fragile tests

As seen above, fragility in IT comes from dependency on external systems. Those fragile tests are best handled as a separate module, outside the standard build process.

However, another cause of fragility is unstability. And in any application, there’s a layer that is fundamentally unstable and that is the presentation layer. Whatever the chosen technology, this layer is exposed to end-users and you can be sure there will be many changes there. Whereas your service API are your own, GUI is subject to users whims, period.

IT that uses GUI, whether dedicated GUI tests or end-to-end tests should thus also be considered fragile and isolated in a dedicated module, as above.

My personal experience, coupled by some writings by Gojko Adzic, taught me to bypass the GUI layer and start my tests at the servlet layer. Whether you use  Spring Test provides a bunch of Fakes regarding the Servlet API.

Tests ordering

Developers unfamiliar with IT should probably be more than astounded by this section title. In fact, as UT should be context-independent and not be ordered in any case.

For IT, things are a little different: I like to define some UT as user stories. For example, user logs in then performs some action and then another. Those steps can of course be defined in the same test method.

The negative side of this, is that if the test fails, we have no way of easily knowing what went wrong and during which step. We could remedy to that by isolating each step in a single method and ordering those methods.

TestNG – a JUnit offshoot fully integrated in Maven and Spring, let us do that easily:

public class MyScenarioIT {

    @Test
    public void userLogsIn() {
        ...
    }
    @Test(dependsOnMethod = "userLogsIn")
    public void someAction() {
        ...
    }
    @Test(dependsOnMethod = "someAction")
    public void anotherAction() {
        ...
    }
}

This way, when an error occurs or an assert fails, log displays the faulty method: we just need to have adequate name for each method.

Framework specifics UT

Java EE in-container UT

Up until recently, automated UT were executed independently of any container. For Spring applications, this was no big deal but for Java EE intensive applications, you had to fake and mock dependencies. In the end, there was no guarantee really running the application inside the container would produce expected results.

Arquillian brought a paradigm shift, with the ability to produce UT for applications using Java EE. If you do not use it already, know that Arquillian let you automate creation of the desired archive and its deployment on one or more configured application servers.

Those can be either existing or downloaded, extracted and configured during UT execution. The former category would need to be segregated in a separate module as to prevent breaking the build while the latter can safely be assimilated to regular UT.

Spring UT

Spring Test provide a feature to assemble different Spring configuration fragments (either XML or Java classes). This means that by designing our application with enough modularity, we can use desired production-ready and tests-only configuration fragments.

As an example, by separating our data source and DAO in two different fragments, we can reuse the regular DAO fragment in UT and use a test fragment declaring an in-memory database. With Maven, this means having the former in src/main/resources and the latter in src/test/resources.

@ContextConfiguration(locations = {"classpath:datasource.xml", "classpath:dao.xml"})
public class MyCustomUT extends AbstractTestNGSpringContextTests {

    ...
}

Conclusion

This is the big picture regarding my personal experience regarding UT. As always, they shouldn’t be seen as hard and fast rules but be adapted to your specific project context.

However, tools listed in the article should be a real asset in all cases.

Design by contract and bean validation

April 21st, 2013 4 comments

I must confess that despite all benefits of defensive programming, I usually limit myself to not expose mutable attribute to the outside world. Why is that? I believe this is mostly because of readability. Have a look at the following piece of code:

public List<Person> getPersons() {
    return Collections.unmodifiableList(persons);
}

Easy enough to read and understand. Now, consider a design by contract approach, where I want to enforce pre-conditions, i.e. conditions that have to be met to run the code.

public void sendEmail(String email) {
    Assert.assertNotNull(email);
    // Real code after that
    ...
}

Not really hard. But now, I want to surface-check the email so as not to query the JNDI tree for a SMTP server for nothing.

public void sendEmail(String email) {
    Assert.assertNotNull(email);
    Validator validator = new EmailValidator(email);
    validator.validate(email);
    // Real code after that
    ...
}

It only so much harder to read… for now. Should I have more than one parameter and multiple checks for each parameter, complexity would quickly grow out-of-hand, and this only for pre-condition!. Post-condition checks would take place at the end of the method, and disturb readability even more. Besides, the outside world doesn’t know about those: they have to be manually written in Javadoc and kept in sync with the code.

What if those limitations could be waived? Would I be more inclined toward using design by contract? I do believe that’s the case. And when I attended Emmanuel Bernard‘s talk at Devoxx France, I couldn’t believe usage would be so simple. My goal can be reached by only using Bean Validation API 1.1 (aka JSR-349). This newer version reuses Bean Validation 1.0 (aka JSR-303) annotations, but where in the previous version only attributes could be annotated, now methods can too. Or to say it more generally, before state was validated, now we can design by contract.

The previous method could be updated like so:

public void sendEmail(@Email String email) {
    // Real code after that
    ...
}

You can see by yourself, not only is it more readable but it communicates my intent to the method callers: this should be an email, not just any string. Icing on the cake, the JSR is open, in all senses. You can contribute to the specs, to the implementation, to anything you like!

Kill-joys would probably object that it is nice and good, but it is still in draft. That would be true, except it is nothing like HTML5 scope. Besides, Hibernate Validator was Bean Validation API 1.0 Reference Implementation. It is only natural that it is also the case for version 1.1, with Hibernate Validator 5. However, it already provides everything we need with version 4.2. If you’re willing to use Spring, it is a breeze:

  1. Get the right dependencies in your POM
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>2.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.3.1.Final</version>
    </dependency>
  2. Annotate your methods as above
  3. Add the right Spring bean post-processor
    @Configuration
    public class SpringConfiguration {
    
        ...
    
        @Bean
        public static MethodValidationPostProcessor methodValidationPostProcessor() {
    
            return new MethodValidationPostProcessor();
        }
    }
  4. Enjoy! Really, it is over, you can use design by contract to your heart’s content.

Sources for this article can be found in Eclipse/Maven format here.

To go further: see relevant links in the article

Note: regular readers of this blog may have noticed I’m using Spring Java configuration whereas I was previously an advocate of XML configuration. Please read this post.

Categories: Java Tags:

The middle path approach

April 14th, 2013 No comments

hybris software, the future of commerce

I’ve been doing software development for most of my career, so that I think myself as a software developer (or software architect), even though I’ve dabbled in solutions engineering more than once. This surely has an effect on how I see the architecture landscape, but I’ll try to be as objective as possible.

Historically, there have been two approaches in providing software solutions to business requirements:

  • Either create custom software to address the requirements
  • Or purchase an out-of-the-box solution to do the same

My software developer side was formerly more in favor of the first option. I thought that this way provided more flexibility than an editor package. During my professional life, I’ve come to realize that management sits on the opposite side, viewing out-of-the-box packages as less risky and less expensive. Even if I agree to the risk point, there are numerous cons to purchase such a solution:

  1. All projects I encoutered only planned for license costs. However, users generally ask for numerous adaptations that require a long configuration
  2. Some, if not most, of those adaptations require more than configuration, but hacking the product itself, which costs even more
  3. Changing the product has a great influence on the maintenance costs, especially toward upgrading: you’ll have to patch the code in the newer version, provided it is compatible
  4. Cutting on the adaptation side will also have an effect on the business side and will require a stronger change management planning
  5. Most products used are provided by (really) big companies: you’ll need to also purchase the associated infrastructure in order to benefit from full editor support (believe, I’ve tried going the other way to my chagrin)

Preaching that out-of-the-box solutions are thus cost-effective is the biggest lie of all!

So basically, it’s either take the risky development road or the costly/coupled product one. Shouldn’t there be an alternative path, that could address these issues?

Since the beginning of the year, I’m working for a company that I think provide such an alternative. It comes in the form of a product whose features include:

  • a basic platform developed with Java & Spring and providing a plugin architecture
  • an extensible business model
  • a service layer, designed around an interface and an out-of-the-box implementation. Implementations can be replaced through a developed plugin
  • a templated web layer, based on Spring MVC that can be modified as needed

IMHO, this is the best alternative I’ve ever seen. This way, you can get the whole shebang in production very quickly, adapt the system to your specific needs (either before production or by incremental steps) and still be able to upgrade easily with each version. Software companies should probably invest in migrating their products to this kind of architecture.

The company is hybris, and I’m very happy to have joined their ranks since the start of this year.

Categories: Technical Tags: , ,

JavaScript namespace and restricted access

April 7th, 2013 1 comment

I began developing with JavaScript more than 10 years ago in order to handle DOM updates on the client-side. At this time, this usage was called DHTML and I was one of the few Java developers that had some interest in it. Still, JavaScript was considered a second-class language, something that was somewhat necessary but wasn’t professional enough.

Fast-forward: the year is 2013 and JavaScript is everywhere:

  • developers are using JavaScript both server- and client-side
  • HTML5 uses JavaScript for dynamic behaviour
  • Client-side data binding is featured by major JavaScript frameworks to build modern web applications

On my part, I’m still the same developer in regard to JavaScript. There always had been more important matters to pursue, and I find myself lost when looking at JavaScript most advanced features. At Devoxx France, I was extremely impressed by HTML5 animation features, and I wanted to play with them in my spare time. I had to develop some JavaScript, with right scoping and good isolation.

As opposed to Java, JavaScript provides global variables. Also, JavaScript functions are available from everywhere. Isolation is not built-in, but has to be designed. The first rule is: do not use global variables. Global variables are a bug waiting to happen, encapsulation should be enforced, period.

Also, Java provides namespaces, a way to create different classes with the same name and still avoid collision, even when using other third-party libraries. The first way I stumbled upon to achieve this made my heart sink:

var CustomNamespace = CustomNamespace || {};

CustomNamespace.doThis = function() {
    ...
}

Not only do I find this extremely unwieldy from a developer point of view as members do not have to be encompassed in the same block, it doesn’t provide isolation: members are accessible.

Next I found the Module pattern, which resolves both problems: code is written inside a single block, and provides ways to offer both internal and public members by using closures:

var CustomNamespace = (function() {
    var varPrivate = ...;
    function doThatPrivate() {
        ...
    }
    return {
        doThisPublic: function() {
            ...
        },
        doThisPublic2: function() {
            ...
        }
    };
})();

This syntax let use encapsulate variables and functions we want to keep private while providing publicly-available functions under a specific namespace. Usage is as follow:

CustomNamespace.doThisPublic();

I find this syntax clear enough to write and easy to use, while providing namespace and restricted access to only desired members. Of course, being newbie in this field, I haven’t encountered disadvantages of it… yet.

Categories: Development Tags:

Devoxx France 2013 – Day 3

March 30th, 2013 1 comment

Classpath isn’t dead… yet by Alexis Hassler

Classpath is dead!
Mark Reinold

What is the classpath anyway? In any code, there are basically two kinds of classes: those coming from the JRE, and those that do not (either becasue they are your own custom class or becasue they come from 3rd-party libraries). Classpath can be set either with a simple java class load by the -cp argument or with a JAR by the embedded MANIFEST.MF.

A classloader is a class itself. It can load resources and classes. Each class knows its classloader, that is which classloader has loaded the class inside the JVM (i.e. sun.misc.Launcher$AppClassLoader). JRE classes classloader is not not a Java type, so the returned classloader is null. Classloader are organized into a parent-child hierarchy, with delegation from bottom to top if a class is not found in the current classloader.

The BootstrapClassLoader can be respectively replaced, appended or prepended with -Xbootclasspath,-Xbootclasspath/a and -Xbootclasspath/p. This is a great way to override standard classes (such as String or Integer); this is also a major security hole. Use at your own risk! Endorsed dir is a way to override some API with a more recent version. This is the case with JAXB for example.

ClassCastException usually comes from the same class being loaded by two different classloaders (or more…). This is because classes are not identified inside the JVM by the class only, but by the tuple {classloader, class}.

Classloader can be developed, and then set in the provided hierarchy. This is generally done in application servers or tools such as JRebel. In Tomcat, each webapp has a classloader, and there’s a parent unified classloader for Tomcat (that has the System classloader as its parent). Nothing prevents you from developing your own: for example, consider a MavenRepositoryClassLoader, that loads JAR from your local Maven repository. You just have to extends UrlClassLoader.

JAR hell comes from dependencies management or more precisely its lack thereof. Since dependencies are tree-like during development time, but completely flat at runtime i.e. on the classpath, conflicts may occur if no care is taken to eliminate them beforehand.

One of the problem is JAR visibility: you either have all classes available if the JAR is present, or none if it is not. The granularity is at the JAR level, whereas it would be better to have finer-grained visibility. Several solutions are available:

  • OSGi has an answer to these problems since 1999. With OSGi, JARs become bundles, with additional meta-data set in the JAR manifest. These meta-data describe visibility per package. For a pure dependency management point of view, OSGi comes with additional features (services and lifecycle) that seem overkill [I personally do not agree].
  • Project Jigsaw also provides this modularity (as well as JRE classes modularity) in the form of modules. Unfortunately, it has been delayed since Java 7, and will not be included in Java 8. Better forget it at the moment.
  • JBoss Module is a JBoss AS 7 subproject, inspired by Jigsaw and based on JBoss OSGi. It is already available and comes with much lower complexity than OSGi. Configuration is made through a module.xml description file. This system is included in JBoss AS 7. On the negative side, you can use Module either with JBoss or on its own, which prevents us from using it in Tomcat. An ongoing Github proof-of-concept achieves it though, which embeds the JAR module in the deployed webapp and overrides Tomcat classloader of the webapp.
    Several problems still exists:

    • Artefacts are not modules
    • Lack of documentation

Animate your HTML5 pages with CSS3, SVG, Canvas & WebGL by Martin Gorner

Within the HTML5 specification alone, there are 4 ways to add fun animations to your pages.

CSS 3
CSS 3 transitions come through the transition property. They are triggered though user-events.Animations are achieved through animation properties. Notice the plural, because you define keyframes and the browser computes intermediate ones.2D transformations -property transformation include rotate, scale, skew, translate and matrix. As an advice, timing can be overriden, but the default one is quite good. CSS 3 also provides 3D transformations. Those are the same as above, but with either X, Y or Z appended to the value name to specify the axis name.The biggest flaw from CSS 3 is that they lack draw features.
SVG + SMIL
SVG not only provides vectorial drawing features but also out-of-the-box animation features. SVG is described in XML: SVG animations are much more powerful that CSS 3 but also more complex. You’d better use a tool to generate it, such as Inkscape.There are different ways to animate SVG, all through sub-tags: animate, animateTransform and animateTransform.Whereas CSS 3 timing is acceptable out-of-the-box, default in SVG is linear (which is not pleasant to the eye). SVG offers timing configuration through the keySplines attribute of the previous tags.Both CSS 3 and SVG have a big limitations: animations are set in stone and cannot respond to external events, such as user inputs. When those are a requirement, the following two standard apply.
Canvas + JavaScript
From this point on, programmatic (as opposed to descriptive) configuration is available. Beware that JavaScript animations comes at a cost: on mobile devices, it will dry power. As such, know about method that let the browser stop animations when the page is not displayed.
WebGL + THREE.js
WebGL let use a OpenGL API (read 3D), but it is very low-level. THREE.js comes with a full-blown high level API. Better yet, you can import Sketchup mesh models into THREE.js.In all cases, do not forget to use the same optimization as in 2D canvas to stop animations when the canvas is not visible.

Tip: in order to not care about prefix, prefix.js let us preserve original CSS and enhance with prefix at runtime. Otherwise, use LESS / SASS. Slides are readily available online with associated labs.
[I remember using the same 3D techniques 15 years ago when I learnt raytracing. That's awesome!]

The Spring update by Josh Long

[Talk is shown in code snippets, rendering full-blown notes mostly moot. It is dedicated to new features of the latest Spring platform versions]

Version Feature
3.1
  • JavaConfig equivalents of XML
  • Profiles
  • Cache abstraction, with CacheManager and Cache
  • Newer backend cache adapters (Hazelcast, memcached, GemFire, etc.) in addition to EhCache
  • Servlet 3.0 support
  • Spring framework code available on GitHub
3.2
  • Gradle-based builds [Because of incompatible versions support. IMHO, this is one of the few use-case for using Gradle that I can agree with]
  • Async MVC processing through Callable (threads are managed by Spring), DeferredResult and AsyncTask<?>
  • Content negotiation strategies
  • MVC Test framework server
4
  • Groovy-configuration support. Note that all available configuration ways (XML, JavaConfig, etc.) and their combinations have no impact at runtime
  • Java 8 closures support
  • JSR 310 (Date and Time API) support
  • Removal of setting @PathVariable‘s value need, using built-in JVM mechanism to get it
  • Various support for Java EE 7
  • Backward compatibility will still include Java 5
  • Annotation-based JMS endpoints
  • WebSocket aka “server push” support
  • Web resources caching

Bean validation 1.1: we’re not in Care Bears land anymore by Emmanuel Bernard

All that will be written here is not set in stone, it has to be approved first. Bean Validation comes bundled with Java EE 6+ but it can be used standalone.

Before Bean Validation, validations were executed at each different layer (client, application layers, database). This led to duplications as well as inconsistencies. The Bean Validation motto is something along the lines of:

Constrain once, run anywhere

1.0 has been released with Java EE 6. It is fully integrated with other stacks including JPA, JSF (& GWT, Wicket, Tapestry) and CDI (& Spring).

Declaring a constraint is as simple as adding a specific validation annotation. Validation can be cascaded, not only on the bean itself but on embedded beans. Also, validation may wrap more than one property to validate if two different properties are consistent with one another. Validation can be set on the whole, but also defined subsets – called groups, of it. Groups are created through interfaces.

Many annotations come out-of-the-box, but you can also define your own. This is achieved with the @Constraint annotation on a custom annotation. It includes the list of validators to use when validating. Those validators must implement the Validator interface.

1.1 will be included in Java EE 7. The most important thing to remember is that it is 100% open. Everything is available on GitHub, go fork it.

Now, containers are in complete control of Bean Validation components creation, so that they are natively compatible with CDI. Also, other DI containers, such as Spring, may plug in their own SPI implementation.

The greatest feature of 1.1 is that not only properties can be validated, but also method parameters and method return values. Constructors being specialized method, it also applies to them. It is achieved internally with interceptors. However, this requires an interception stack – either CDI, Spring or any AOP, and comes with associated limitations, such as proxies. This enables declarative Contract-Oriented Programming, and its pre- and post-conditions.

Conclusion

Devoxx France 2013 has been a huge success, thanks to the organization team. Devoxx is not only tech talks, it is also a time to meet new people, exchange ideas and see old friends.

See you next year, or at Devoxx 2013!

Thanks to my employer – hybris, who helped me attend this great event!

Categories: Event Tags: , , ,

Devoxx France 2013 – Day 2

March 29th, 2013 3 comments

Object and Functions, conflict without a cause by Martin Odersky

The aim of Scala is to merge features of Object-Programming and Functional Programming. The first popular OOP language was Simula in 67, aimed at simulations; the second one was Smalltalk for GUIs. What is the reason OOP became popular: only because of the things you could do., not because of its individual features (like encapsulation). Before OOP, the data structure was well known with an unbounded number of operations while with OOP, the number of operations is fixed but the number of implementation is unbounded. Though it is possible for procedural languages (such as C) to apply to the field of simulation & GUI, it is to cumbersome to develop with them in real-life projects.

FP has advantages over OOP but none of them is enough to led to mainstream adoption (remember it has been around for 50 years). What can spark this adoption is the complexity to develop OOP applications multicores and cloud computing ready. Requirements for these scopes include:

  • parallel
  • reactive
  • distributed

In each of these, mutable state is a huge liability. Shared mutable state and concurrent threads leads to non-determinism. To avoid this, just avoid mutable state :-) or at least reduce it.

The essence of FP is to concentrate on transformation of immutable values instead of stepwise updates of a single mutable data structure.

In Scala, the .par member turns a collection into a parallel collection. But then, you have to became FP and forego of any side-effects. With Future and Promise, non-blocking is also possible but is hard to write (and read!), while Scala for-expressions syntax is an improvement. It also make parallel calls very easy.

Objects are not to put put away: in fact, they are not about imperative, they are about modularization. There are no module systems (yet) that are on par with OOP. It feels like using FP & OOP is like sitting between two chairs. Bridging the gap require letting go of some luggage first.

Objects are characterized by state, identity and behavior
Grady Booch

It would be better to focus on behavior…

Ease development of offline applications in Java with GWT by Arnaud Tournier

HTML5 opens new capabilities that were previously the domain of native applications (local storage, etc.). However, it is not stable and mature yet: know that it will have a direct impact on development costs.

GWT is a tool of choice for developing complex Java applications leveraging HTML5 features. A module called “elemental” completes lacking features. Moreover, the JNSI API is able to use JavaScript directly. In GWT, one develops in Java and a compiler transforms Java code into JavaScript instead of bytecode. Generated code is compatible with most modern browsers.

Mandatory features for offline include application cache and local storage. Application cache is a way for browsers to store files locally to use when offline. It is based on a manifest file, and has to be referenced by desired HTML pages (in the <html> tag). A cache management API is provided to listen to cache-related events. GWT already manages resources: we only need to provide a linker class to generate the manifest file that includes wanted resources. Integration of the cache API is achieved through usual JSNI usage [the necessary code is not user-friendly... in fact, it is quite gory].

Local storage is a feature that stores user data on the client-side. Some standards are available: WebSQL, IndexedDB, LocalStorage, etc. Unfortunately, only the latter is truly cross-browser and is based on a key-value map of strings. Unlike application cache, there’s an existing out-of-the-box GWT wrapper around local storage. Objects stored being strings and running client-side, JSON is the serialization mechanism of choice. Beware that standard mandates 5MB maximum of storage (while some browsers provide more).

We want:

  1. Offline authentication
  2. A local database to be able to run offline
  3. JPA features for developers
  4. Transparent data synch when coming online again for users

In regard to offline authentication, it is not a real problem. Since local storage is not secured, we just have to store the password hash. Get a SHA-1 Java library and GWT takes care of the rest.

SQL capabilities is a bigger issue, there are many incomplete solutions. sql.js a JavaScript SQLite port that provides limited SQL capabilities. As for integration, back to JSNI again ([* sigh *]). You will be responsible for developing a high-level API to ease usage of this, as you have to talk to either a true JPA backend or local storage. Note that JBoss Errai is a proposed JPA implementation to resolve this (unfortunately, it is not ready for production use – yet).

State sync between client and server is the final problem. It can be separated into 3 ascending complexity levels: read-only, read-add and read-add-delete-update. Now, sync has to be done manually, only the process itself is generic. In the last case, there are no rules, only different conflict resolution strategies. What is mandatory is to have causality relations data (see Lamport timestamps).

Conclusion is that developing offline applications now is a real burden, with a large mismatch between possible HTML5 capabilities and existing tools.

Comparing JVM web frameworks by Matt Raible

Starting with JVM Web frameworks history, it all began with PHP 1.0 in 1995. In the J2EE world, Struts replaced proprietary frameworks in 2001.

Are there many too many Java web frameworks? Consider Vaadin, MyFaces, Struts2, Wicket, Play!, Stripes, tapestry, RichFaces, Spring MVC, Rails, Sling, Stripes, Grails, Flex, PrimeFaces, Lift, etc.

And now, for SOFEA architecture, there are again so many frameworks on the client-side: Backbone.ja, AngularJS, HTML5, etc. But, “traditional” frameworks are still relevant because of client-side development limitations, including development speed and performance issues.

In order to make relevant decision when faced with a choice, first set your goals and then evaluate each option in regard to these goals. Pick your best option and then re-set your goals. Maximizers trie to make the best possible choice, satisficers try to find the first suitable choice. Note that the former are generally more unhappy than the latter.

Here is a proposed typology (non-exhaustive):

Pure web Full stack SOFEA
Apache GWT JSF Miscellaneous API JavaScript MVC
  • Wicket
  • Struts
  • Spring
  • Tapestry
  • Click
  • SmartGWT
  • GXT
  • Vaadin
  • Errai
  • Mojarra (RI)
  • MyFaces
  • Tomahawk
  • IceFaces
  • RichFaces
  • PrimeFaces
  • Spring MVC
  • Stripes
  • RIFE
  • ZK
  • Rails
  • Grails
  • Play!
  • Lift
  • Spring Roo
  • Seam
  • RESTEasy
  • Jersey
  • CXF
  • vert.x
  • Dropwizard
  • Backbone.js
  • Batman.js
  • JavaScript MVC
  • Ember.js
  • Sprout Core
  • Knockout.js
  • AngularJS

The former matrix with fine-grained criteria is fine, but you probably have to create your own, with your own weight for each criterion. There are so many ways to tweak the comparison: you can assign more fine-grained grades, compare performances, locs, etc. Most of the time, you are influenced by your peers and by people who have used such and such frameworks. Interestingly enough, performance-oriented tests show that most of the time, bottlenecks appear in the database.

  • For full stack, choose by language
  • For pure web, Spring MVC, Struts 2, Vaadin, Wicket, Tapestry, PrimeFaces. Then, eliminate further by books, job trends, available skills (i.e. LinkedIn), etc.

Fun facts: a great thing going for Grails and Spring MVC is backward compatibility. On the opposite side, Play! is the first framework that has community revive a legacy version.

Conclusion: web frameworks are not the productivity bottleneck (administrative tasks are as show in the JRebel productivity report), make your own opinion, be nether a maximizer (things change too quickly) nor a picker.

Puzzlers and curiosities by Guillaume Tardif & Eric Lefevre-Ardant

[Interesting presentation on self-reference, in art and code. Impossible to resume in written form! Wait for the Parleys video...]

Exotic data structures, beyond ArrayList, HashMap & HashSet by Sam Bessalah

If all you have is a hammer, everything looks like a nail

In some cases, problem can be solved in an easier way by using the right data structure instead of the one we know. Those 4 different “exotic” data structures are worth knowing:

  1. Skip lists are ordered data sets. The benefit of skip lists over array lists is that every operation (insertion, removal, contains and retrieval, ranges) is in o(log N). It is achieved by adding extra levels for “express” lines. Within the JVM, it is even faster with JVM region localizing feature. The type is non-locking (thread-safe) and included in Java 6 with ConcurrentSkipListMap and ConcurrentSkipListSet. The former is ideal for cache implementations.
  2. Tries are ordered trees. Whereas traditional trees have complexity of o(log N) where N is the tree depth, tries have constant time complexity whatever the depth. A specialized kind of trie is the Hash Array Mapped Trie (HAMT), a functional data structure for fast computations. Scala offers CTrie structure, a concurrent trie.
  3. Bloom filters are probabilistic data structures, designed to return very fast whether an element belongs to a data structure. In this case, there are no false negatives, accurately returning when an element does not belong to the structure. On the contrary, false positives are possible: it may return true when it is not the case. In order to reduce the probability of false positives, one can choose an optimal hash function (cryptographic functions are best suited), in order to avoid collision between hashed values. To go further, one can add hash functions. The trade off is memory space consumption.
    Because of collisions, you cannot remove elements from Bloom filters. In order to achieve them, you can enhance Bloom filters with counting, where you also store the number of elements at a specific location.
  4. Count Min Sketches are advanced Bloom filters. It is designed to work best when working with highly uncorrelated, unstructured data. Heavy hitters are based on Count Min Sketches.
Categories: Event Tags: , ,

Devoxx France 2013 – Day 1

March 28th, 2013 No comments

Rejoice people, it’s March, time for Devoxx France 2013! Here are some notes I took during the event.

Java EE 7 hands-on lab by David Delabasse & Laurent Ruaud

An hands-on lab by Oracle for good old-fashioned developers that want to check some Java EE 7 features by themselves.

This one, you can do it at home. Just go to this page and follow instructions. Note you will need at least Glassfish 4 beta 80 and the latest NetBeans (7.3).

You’d better reserve a day if you want to go beyond copy-paste and really read and understand what you’re doing. Besides, you have to some JSF knowledge if anything goes wrong (or have a guru on call).

Angular JS by Thierry Chatel

The speaker comes from a Java developer background. He has used Swing in the past and since then, he has searched for binding features: a way to automate data exchange between model and views. Two years ago, he found AngularJS.

AngularJS is a JavaScript framework, comprised of more than +40 kloc and weights 77 kb minified. The first stable version was released one year ago, codenamed temporal-domination. The application developed by Google with AngularJS is Doubleclick for publishers. Other examples include OVH’s future management console and Youtube application on PS3. Its motto is:

HTML enhanced for web apps

What does HTML enhanced means? Is it HTML6? The problem is HTML has never been designed to create applications: it is only to display documents and link between them. Most of the time, one-way binding between Model & Template is achieved to create a view. Misko Hevery (AngularJS founder) point of view is instead of trying to go around this limitation, we’d better add this feature to HTML.

So, AngularJS philosophy is to compile the View from the Template, and then 2-way bind between View & Model. AngularJS use is easy as pie:

Yout name: <input type="text" ng-model="me">
Hello {{me}}

AngularJS is a JavaScript framework, that free developers from coding too manyJavaScript lines.

The framework uses simple concepts:

  • watches around expressions (properties, functions, etc.)
  • dirty checking on events (keyboard, HTTP request, etc.)

Watches are re-evaluated on each dirty checks. This means expressions have to be simple (i.e. computation results instead of the computations themselves). The framework is designed to handle up to 2000 simple watches. Keep note that standards (as well as user agents) are evolving and that ECMAScript next version will provide Object.observer() to handle x50 the actual number of watches.

An AngularJS app is as simple as:

<div ng-app="myapp"></div>

This let us have as many applications as needed on the same page. AngularJS is able to create single-page applications, with browser navigation (bookmarks, next, previous) automatically handled. There’s no such thing like global state.

AngularJS also provides core concepts like modules, services and dependency injection. There’s no need to inherit from specific classes or interfaces: any object is available for any role. As a consequence, code is easily unit-testable, the preferred tool to do this is Karma (ex-Testacular). For end-to-end scenarii testing, the same dedicated tool is also available, based on the framework and plays tests in defined browsers. In conclusion, AngularJS is not only a framework but also a complete platform with the right level of abstraction, so that developed code is purely business.

There are no AngularJS UI components, but many are provided by third-party like AngularUI, AngularStrap, etc.

AngularJS is extremely structuring, it is an opinionated framework. You have to code the AngularJS way. A tutorial is readily available to let you do that. Short videos dedicated to a single focused theme are available online.

Wow, this the second talk I attend about AngularJS and it looks extremely good! My only complaints are that is follows the trend of pure client-side frameworks and that is not designed for mobile.

Gradle, 30 minutes to change all by Sébastien Cogneau

In essence, Gradle is a Groovy DSL to automate build. It is extensible through Java & Groovy plugins. Gradle is based on existing principles: it let you reuse Ant tasks, it reuses Maven convention and is compatible with both Ivy & Maven repositories.

A typical gradle build file looks like this:

apply plugin: 'jetty'

version = '1.0.0'

repositories {

    mavenCentral()
}

configuration {
    codeCoverage
}

sonarRunner {
    sonarProperties {
        ...
    }
}

dependencies {
    compile: 'org.hibernate:hibernate-core:3.3.1.GA'
    codeCoverage: 'org.jacoco....'
}

test {
    jvmArgs '...'
}

task wrapper(type:Wrapper) {
    gradleVersion = '1.5-rc3'
}

task hello(type:Exec) {
    description 'Devoxx 2013 task'
    group 'devoxx'
    dependsOn wrapper
    executable 'echo'
    args 'Do you have question'
}

Adding plugins add tasks to the available build. For example, by adding jetty, we get jettyStart. Moreover, plugins have dependencies so you also have tasks from dependent plugins.

Gradle can be integrated with Jenkins, as there is an available Gradle plugin. There are two available options to run Gradle build on Jenkins:

  • either you install Gradle and configure its installation on Jenkins. From this point, you can configure your build to use this specific install
  • or you generate a Gradle wrapper and only configure your build to use this wrapper. There’s no need to install Gradle at all in this case

Gradle power let also add custom tasks, such as the aforementioned hello task.

The speaker tells us he is using Gradle because it is so flexible. But that’s exactly the reason I’m more than reluctant to adopt it: I’ve been building with Ant for ages, then came to Maven. Now, I’m forced to use Ant again and it takes so much time to understand a build file compared to a Maven POM.

Space chatons, bleeding-edge HTML5 by Phillipe Antoine & Pierre Gayvallet

This presentation demoed new features brought by HTML5.

It was too quick to assimilate anything, but demos were really awesome. In particular, one of them used three.js, a 3D rendering library that you should really have a look into. When I think it took raytracing to achieve this 15 years ago..

Vaadin & GWT 2013 Paris Meetup

Key points (because at this time, I was more than a little tired):

  • My presentation on FieldGroup and Converters is available on Slideshare
  • Vaadin versions are supported for 5 years each. Vaadin 6 support will end in 2014
  • May will see the release of a headless of Vaadin TestBench. Good for automated tests!
  • This Friday, Vaadin 7.1 will be out with server push
  • Remember that Vaadin Ltd also offers Commercial Support (and it comes with a JRebel license!)
Categories: Event Tags: , , ,

KISS your architecture

March 17th, 2013 No comments

The project I’m working on these days is not properly “legacy” but has seen some twists that renders it less than ideal.

On this project, one of the worst point that has been an obstacle for me to develop a simple feature is layered architecture. “What”, shout all experienced developers, “layered architecture is at the root of maintainability!” and I agree wholeheartedly. So, how could layer architecture be an obstacle?

  1. First, adding too many layers kill layering. I’ve always been a proponent of keeping the layers count low – especially DTO – when not strictly necessary. Too many layers and you will not only add complexity at development time but also performance overhead at runtime.
  2. Second, mapping is extremely important. If you completely change attribute names from one layer to another, newcomers are bound to endlessly scratch their heads.
  3. In all cases, the point of those layers is to separate code. So, keep it that way.
  4. Finally, if you need to do one (or all) of the former point, document it!

In my case, I stumbled upon an aggregation of all 4 points, as well as a previously unknown component (at least to me), jQuery template. This jQuery plugin is used to handle AJAX (but this is just a coincidence, as I suspect you could replace it with any equivalent and still get unmaintainable code).

Though I understand the intent to help with JavaScript by adding one more plugin, I tend to frown on how client-side is actually managed: not at all. Now that we finally have a decent build process including quality metrics (Jenkins + Sonar), developers and architects running like mad toward JavaScript without putting in place equivalent infrastructure – yes, it is possible, is utter nonsense. This is it for point 1.

Server-side, Spring MVC is the framework. A controller returns DTO which are processed through JSON converter. Guess what, JSON sent back by the server is mapped to another JSON entity client-side, one that has all fields of the original, but not all with the same name. Point 2 just makes it harder to understand what happens, and client means full-text search. Welcome into your new home…

I won’t pretend I understand all intricacies of jQuery Template, so I’ll just be factual about code I saw: it’s completely against all I know to create HTML on the fly by aggregating HTML snippets (including div with CSS class attribute) and parameter values. This is even worse if it takes more than 20 lines of strings, even though they are neatly aligned. Now, you’re really asking for pain, because not only is your JavaScript code untested, but it mingles HTML, CSS and JavaScript: I pity the poor maintainers of this application (I’ve done my part). That was point 3.

Point 4: are you kidding?

Now that I’m slightly psychotic because of this feature I had to implement, and since I will know where you live in a not-so-distant future, I suggest you start designing your architecture by respecting KISS! This will render all aforementioned points moot and keep me happy.

Categories: Development Tags:

Consider replacing Spring XML configuration with JavaConfig

March 10th, 2013 5 comments

Spring articles are becoming a trend on this blog, I should probably apply for a SpringSource position :-)

Colleagues of mine sometimes curse me for my stubbornness in using XML configuration for Spring. Yes, it seems so 2000′s but XML has definite advantages:

  1. Configuration is centralized, it’s not scattered among all different components so you can have a nice overview of beans and their wirings in a single place
  2. If you need to split your files, no problem, Spring let you do that. It then reassembles them at runtime through internal <import> tags or external context files aggregation
  3. Only XML configuration allows for explicit wiring – as opposed to autowiring. Sometimes, the latter is a bit too magical for my own taste. Its apparent simplicity hides real complexity: not only do we need to switch between by-type and by-name autowiring, but more importantly, the strategy for choosing the relevant bean among all eligible ones escapes but the more seasoned Spring developers. Profiles seem to make this easier, but is relatively new and is known to few
  4. Last but not least, XML is completely orthogonal to the Java file: there’s no coupling between the 2 so that the class can be used in more than one context with different configurations

The sole problem with XML is that you have to wait until runtime to discover typos in a bean or some other stupid boo-boo. On the other side, using Spring IDE plugin (or the integrated Spring Tools Suite) definitely can help you there.

An interesting alternative to both XML and direct annotations on bean classes is JavaConfig, a former separate project embedded into Spring itself since v3.0. It merges XML decoupling advantage with Java compile-time checks. JavaConfig can be seen as the XML file equivalent, only written in Java. The whole documentation is of course available online, but this article will just let you kickstart using JavaConfig. As an example, let us migrate from the following XML file to a JavaConfig

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <bean id="button" class="javax.swing.JButton">
        <constructor-arg value="Hello World" />
    </bean>

    <bean id="anotherButton" class="javax.swing.JButton">
        <property name="icon" ref="icon" />
    </bean>

    <bean id="icon" class="javax.swing.ImageIcon">
        <constructor-arg>
            <bean class="java.net.URL">
            	<constructor-arg value="http://morevaadin.com/assets/images/learning_vaadin_cover.png" />
            </bean>
        </constructor-arg>
    </bean>
</beans>

The equivalent file is the following:

import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MigratedConfiguration {

    @Bean
    public JButton button() {

        return new JButton("Hello World");
    }

    @Bean
    public JButton anotherButton(Icon icon) {

        return new JButton(icon);
    }

    @Bean
    public Icon icon() throws MalformedURLException {

        URL url = new URL("http://morevaadin.com/assets/images/learning_vaadin_cover.png");

        return new ImageIcon(url);
    }
}

Usage is simpler than simple: annotate the main class with @Configuration and individual producer methods with @Bean. The only drawback, IMHO, is that it uses autowiring. Apart from that, It just works.

Note that in a Web environment, the web deployment descriptor should be updated with the following lines:

<context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.packtpub.learnvaadin.springintegration.SpringIntegrationConfiguration</param-value>
</context-param>

Sources for this article are available in Maven/Eclipse format here.

To go further:

  • Java-based container configuration documentation
  • AnnotationConfigWebApplicationContext JavaDoc
  • @ContextConfiguration JavaDoc (to configure Spring Test to use JavaConfig)
Categories: Java Tags: ,