All posts by deors

senior technology architect in accenture, with a passion for java related stuff, celtic music and the best sci-fi, among other thousand things!

New Releases: Oracle Java ME 8.1 and Java ME SDK 8.1

Originally posted on Across the Universe:

This is bigAt JavaOne a few weeks ago, Oracle made available the Java ME 8.1 Developer Preview release for the Freescale FRDM-K64F (“Java ME 8.1 in 190 KB RAM”) and announced the upcoming full release of Java ME Embedded 8.1 (press release).

On Monday this week, we followed up as promised and posted the General Availability (GA) releases of Oracle Java ME 8.1 and the Oracle ME SDK 8.1.

Oracle Java ME Embedded 8.1 and ME SDK 8.1 New Features and Enhancements

  • Support for ARM Cortex-M3/-M4 micro-controllers
  • Updated Raspberry Pi support 
  • Updated Developer Preview on FRDM-K64 with mbed
  • Improved support for two additional Qualcomm Gobi device families
  • New communication, security, and networking features
  • New support for Eclipse IDE, including major update of the Eclipse MTJ plugin
  • Developer improvements: Tooling over USB, heap analysis, faster communication
  • A number of smaller enhancements and fixes

Java 8: Truly Scalable

With this release…

View original 275 more words

Slides and code examples from JavaOne CON2013 session – Code Generation in the Java Compiler: Annotation Processors Do the Hard Work

The slides for my conference session CON2013 in JavaOne 2014 can be found online here: http://www.slideshare.net/deors/javaone-2014-con2013-code-generation-in-the-java-compiler-annotation-processors-do-the-hard-work

The coding examples can be found on GitHub: https://github.com/deors/deors.demos.annotations

con2013

Speaking at JavaOne 2014 San Francisco!

This year I have been honored to be selected to speak at JavaOne 2014. Awesome news! I’m excited for this opportunity to speak at possibly the larger Java developer conference in the world.

The session that was selected is CON2013: Code Generation in the Java Compiler: Annotation Processors Do the Hard Work. This session is largely based on my work around Annotation Processors as a driver for code generation.

It is really a pleasure to see that what was an experimental work three years ago, matures and get the attention of the JavaOne commitee.

So, if you happen to be at JavaOne, don’t miss the opportunity and come to the session! See you there!

Pitest: Measure the Quality of your Unit Tests with Mutation Testing

It is not uncommon among developers to discuss about the quality of automated unit tests: Are they testing enough of application code? And more importantly, are they really verifying the expected behavior?

The first question has a relatively simple answer: use automated code coverage tools that will track which lines of code and which branches in execution flow are being tested. Code coverage reports are very helpful to 1) determine which portions of application code are not being tested; and 2) if measuring code coverage per individual test, determine whether each test is effectively testing the appropriate piece of application code. If interested in techniques for that, you may want to look at this other blog post: http://deors.wordpress.com/2014/07/04/individual-test-coverage-sonarqube-jacoco/

However, no matter how useful is to measure code coverage, these reports will not let you know one fundamental aspect of tests: which behavior is being verified!

Simply put, your test code may be passing through every single line of your code, and not verifying anything. If you are familiar with JUnit framework, your test code may not contain a single assertion!

To overcome this limitation of automated unit testing, one technique that can be of great help is Mutation Testing.

Mutation Testing… Explained

Let’s assume you have your application code and your test code as usual. A mutation testing tool will take your application code and make small surgical changes, one at a time, a so-called “mutation”. It could be changing a logical operator in an if statement (e.g. > is changed to <=), it could be removing some service call, it could be changing some for loop, it could be altering some return value, and so forth.

Mutation testing is, therefore, based on the assumption that if you are testing your code and making the right assertions to verify the behavior, once you re-execute your unit tests with a mutation in application code some of them should fail.

Pitest – A Mutation Testing Framework for Java

Although very interesting, such a technique would be useless without the proper tools. There are some, and for different languages, like Jester, Jumble or NinjaTurtles, but probably the most mature and powerful we’ve seen to date is Pitest (http://pitest.org).

Working with Pitest is very simple and requires minimal effort to start. It can be integrated with build tools like Maven, Ant or Gradle, with IDEs like Eclipse (Pitclipse plug-in) or IntelliJ, and with quality tools like SonarQube.

Regardless of the way you execute it, Pitest will analyze the application byte codes and decide which mutations will be introduced (for a full list and description of available mutators in Pitest, check their site here: http://pitest.org/quickstart/mutators/).

To optimize the test execution as much as possible, Pitest gathers code coverage metrics in a “normal execution” and then re-executes only the matching test cases for a certain mutation. Total execution time is noticeably longer than a normal unit test execution, basically because the incredible test harness that Pitest adds even to the most simple of code bases.

As a result, Pitest generates a fully detail report showing which mutations “lived” after the execution, that is, which mutations where not detected by any existing assertion. These “lived” mutations are your main focus, because they mean that there is some logic, some return value, or some call that is not being verified.

Of course not all of the mutations will be meaningful. Some may produce out of memory errors or infinite loops. For those cases, Pitest does its best to detect them and remove from the resulting reports. These can be fine-tuned if needed, for example by tuning time outs and other parameters, but sensible defaults work really well to start with.

Pitest in Action

Seeing is believing, so we put Pitest to work on a simple 10-classes Java library. We decided to use the Maven plug-in, as this method requires zero configuration to start. We opened a command prompt at the project directory, and just executed this command:

> mvn org.pitest:pitest-maven:1.0.0:mutationCoverage

After a few minutes (5 to 6 for this project) and lots of iterations showing in the console, the build finishes and the reports are generated in target directory:

> target\pit-reports\201408181908\index.html

When the report loaded in the browser, the first fact that caught our attention was that one class, that we worked hard to be fully tested, AbstractContext, although with a 100% code coverage it showed one lived mutation. Oops, something was not properly verified. Was Pitest right?

mutation-1

After clicking the class name, we could see the detail on where the lived mutation was found:

mutation-2

Pitest was right! Although that method is fully tested, and there are test cases for every single execution flow, we were missing the proper assertion for that if statement. Really really hard to catch if not for a good tool helping us to find out more about our unit tests.

Of course, next step was to add the forgotten assertion to the relevant test method. Once done, we re-launched Pitest. After a few minutes, a new set of reports where created and once loaded in the browser… clean result for that class!

mutation-4

Conclusion

Although arguably a bit fortunate to obtain such a fabulous result at the first try, it is true that after a more thorough inspection of the reports we found many other places where assertions were missing.

Our view is that Pitest is a very valuable tool to write really meaningful and truly useful automated unit test suites, and should be standard gear for Java projects going forward. It is simple to use, requires zero or minimal configuration, and produces valuable results that directly impact in the quality of the test we create, and therefore in the quality of our deliverables.

To mutate, or not to mutate: that is the question.
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous unit tests.

Script to List Key Job Settings in Jenkins at a Glance

One can get addicted to scripting in Jenkins quickly! ;-)

When you have dozens even hundreds of jobs in Jenkins, it is really important to have a way to review or change job settings in one shot. One of my favorite scripts, that I use when I want to get key settings from all jobs at a glance, is this one:

import hudson.model.*
import hudson.maven.*

for (job in Hudson.instance.items) {
  if (job instanceof MavenModuleSet) {
    mms = (MavenModuleSet) job
    def name = mms.name
    def jdk = "def"
    if (mms.JDK != null) {
      jdk = mms.JDK.name
    }
    def mvn = mms.mavenName
    def goals = mms.goals
    printf("%-50s | %-10s | %-15s | %-50s\n", name, jdk, mvn, goals)
  }
}

And this is a example output. I love it! :-D  (Be sure to scroll right to see full output.)

deors.demos.annotations.base                       | jdk-8      | null            | clean install                                     
deors.demos.annotations.base.client                | jdk-8      | null            | clean test                                        
deors.demos.annotations.base.processors            | jdk-8      | null            | clean install                                     
deors.demos.annotations.beaninfo                   | jdk-8      | null            | clean install                                     
deors.demos.annotations.beaninfo.client            | jdk-8      | null            | clean test                                        
deors.demos.annotations.beaninfo.processors        | jdk-8      | null            | clean install                                     
deors.demos.annotations.velocity.client            | jdk-8      | null            | clean test                                        
deors.demos.annotations.velocity.processors        | jdk-8      | null            | clean install                                     
deors.demos.batch.springbatch2                     | jdk-7      | maven-3.2.1     | clean verify                                      
deors.demos.cloud.gae                              | jdk-7      | maven-3.2.1     | clean verify                                      
deors.demos.cloud.heroku                           | jdk-7      | maven-3.2.1     | clean verify                                      
deors.demos.cloud.rhc                              | jdk-7      | maven-3.2.1     | clean verify                                      
deors.demos.cloud.vmc                              | jdk-7      | maven-3.2.1     | clean verify                                      
deors.demos.java8                                  | jdk-8      | maven-3.2.1     | clean verify                                      
deors.demos.testing.arquillian                     | jdk-7      | maven-3.2.1     | clean verify                                      
deors.demos.testing.arquillian-glassfish-embedded  | jdk-7      | null            | clean verify -Parquillian-glassfish-embedded      
deors.demos.testing.arquillian-glassfish-remote    | jdk-7      | null            | clean verify -Parquillian-glassfish-remote,!arquillian-glassfish-embedded
deors.demos.testing.arquillian-jboss-managed       | jdk-7      | null            | clean verify -Parquillian-jboss-managed,!arquillian-glassfish-embedded
deors.demos.testing.arquillian-jboss-remote        | jdk-7      | null            | clean verify -Parquillian-jboss-remote,!arquillian-glassfish-embedded
deors.demos.testing.arquillian-weld-embedded       | jdk-7      | null            | clean verify -Parquillian-weld-embedded,!arquillian-glassfish-embedded
deors.demos.testing.htmlunit                       | jdk-7      | maven-3.2.1     | clean verify                                      
deors.demos.testing.htmlunit-cargo-glassfish       | jdk-7      | null            | -P glassfish cargo:redeploy                       
deors.demos.testing.htmlunit-cargo-jboss           | jdk-7      | null            | -P jboss cargo:redeploy                           
deors.demos.testing.htmlunit-cargo-tomcat          | jdk-7      | null            | -P tomcat cargo:redeploy                          
deors.demos.testing.htmlunit-deploy-glassfish      | jdk-7      | null            | clean install                                     
deors.demos.testing.htmlunit-deploy-tomcat         | jdk-7      | null            | clean install                                     
deors.demos.testing.mocks                          | jdk-7      | maven-3.2.1     | clean verify                                      
deors.demos.testing.selenium                       | jdk-7      | maven-3.2.1     | clean verify                                      
deors.demos.testing.selenium-cargo-glassfish       | jdk-7      | null            | -P glassfish cargo:redeploy                       
deors.demos.testing.selenium-cargo-jboss           | jdk-7      | null            | -P jboss cargo:redeploy                           
deors.demos.testing.selenium-cargo-tomcat          | jdk-7      | null            | -P tomcat cargo:redeploy                          
deors.demos.testing.selenium-deploy-glassfish      | jdk-7      | null            | clean install                                     
deors.demos.testing.selenium-deploy-tomcat         | jdk-7      | null            | clean install                                     
deors.demos.web.gwt2                               | jdk-7      | maven-3.2.1     | clean verify                                      
deors.demos.web.gwt2spring                         | jdk-7      | maven-3.2.1     | clean verify                                      
deors.demos.web.springmvc3                         | jdk-7      | maven-3.2.1     | clean verify                                      
petclinic-1-build-test                             | jdk-7      | maven-3.2.1     | clean test                                        
petclinic-2-package                                | jdk-7      | null            | package -DskipTests=true                          
petclinic-3-tomcat-run                             | jdk-7      | null            | cargo:run -Pcargo-tomcat                          
petclinic-4-verify-selenium-htmlunit               | jdk-7      | maven-3.2.1     | failsafe:integration-test -P selenium-tests       
petclinic-5-verify-jmeter                          | jdk-7      | maven-3.2.1     | jmeter:jmeter -P jmeter-tests                     
petclinic-6-tomcat-stop                            | jdk-7      | null            | cargo:stop -Pcargo-tomcat                         
petclinic-9a-verify-selenium-openshift             | jdk-7      | maven-3.2.1     | failsafe:integration-test -P selenium-tests       
petclinic-9b-verify-selenium-heroku                | jdk-7      | maven-3.2.1     | failsafe:integration-test -P selenium-tests       
petclinic-full-all-browsers                        | jdk-7      | maven-3.2.1     | clean verify -P cargo-tomcat,selenium-tests       
petclinic-full-htmlunit-sonar                      | jdk-7      | maven-3.2.1     | clean verify -P cargo-tomcat,selenium-tests,jmeter-tests

Script to Update Jenkins Jobs to Use a Different Maven Instance

One of the features of Jenkins that I like a lot, very useful when you need to do bulk changes on your jobs configuration, is the script console.

The script console allows to run Groovy scripts that can read and alter the state of the jobs, or any other piece of configuration or state exposed through Jenkins API or through its plug-ins respective APIs.

Today I decided to take a look to Apache Maven 3.2.1 and I wanted to easily test all my existing jobs with this new version. As I’m “lazy” ;-) and didn’t want to update the jobs one by one, I created this script to do the job for me in no time. Hope you enjoy it!

import hudson.maven.*
import hudson.model.*
import hudson.tasks.*
import hudson.tools.*

oldMavenName = "maven-3.0.4"
newMavenName = "maven-3.2.1"

Maven.MavenInstallation oldMaven
Maven.MavenInstallation newMaven

// look for old and new Maven installations
// useful to detect that something is not well configured
for (ti in ToolInstallation.all()) {
  if (ti instanceof Maven.MavenInstallation.DescriptorImpl) {
    for (i in ti.installations) {
      if (i.name.equals(oldMavenName)) {
        oldMaven = i
      } else if (i.name.equals(newMavenName)) {
        newMaven = i
      }
    }
  }
}

println("migrating jobs from Maven: " + oldMaven.name)
println("to Maven: " + newMaven.name)
println()

// locate the jobs and update the Maven installation
// optionally filter them by some prefix or regex
for (job in Hudson.instance.items) {
  if (job instanceof MavenModuleSet) {
    mms = (MavenModuleSet) job
    if (mms.name.startsWith("some.prefix")) {
      println("job " + mms.name + " currently using: " + mms.mavenName)
      // if name is null, it means the default Maven installation
      if (mms.mavenName == null || mms.mavenName == oldMaven.name) {
        mms.mavenName = newMaven.name
        println(" migrate to: " + mms.mavenName)
      } else {
        println(" no migration needed")
      }
    }
  }
}

Java 8 Lambdas explained #1: Map/Reduce with Fork/Join and the Beauty of a One-Line Lambda

Lambdas are cool. Lambdas are sexy. Lambdas are expressive and let you write less code. Are these all a cliché? No! They are so true…

Recently we run a session locally explaining Lambdas with side-by-side comparisons of some coding patterns expressed in Java 7 vs. Java 8. We used the best we could obtain of each version of the language and APIs, including lambdas, stream processing, the new Date and Time API… It was fun seeing people reactions on how dramatically code can be reduced from Java 7 to Java 8 style.

In this post I want to show one example of the above: how a simple Map/Reduce pattern can be radically simplified if you switch the Fork/Join API from Java 7 to parallel stream processing in Java 8.

Setting up the project

Let’s start with setting up the project. A very simple Maven project configuration that explicitly sets Java 8 as source and target for compilation and adds a dependency to JavaTuples library:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>deors.demos</groupId>
  <artifactId>deors.demos.java8</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>deors.demos.java8</name>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <verbose>true</verbose>
          <compilerVersion>1.8</compilerVersion>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>org.javatuples</groupId>
      <artifactId>javatuples</artifactId>
      <version>1.2</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>

The Problem

For this example, this is the problem we want to solve: given a list of integer tuples (pairs of integers), calculate the sum of the product of each pair. As we want the solution to scale, it should be done through parallel computing so the JVM running the code can take advantage of multi-core environments to split the problem in simpler pieces and make the processing faster.

In Java 7 fashion, a clever programmer could choose the Fork/Join API and create a task that, given the list of tuples, split it in halves when its size exceeds some defined threshold, process each half in parallel and recursively, aggregating the results from each piece until the final result is obtained. Not complex but a bit verbose even with the Fork/Join API. This is the code (don’t worry to write it down – this code can be obtained from GitHub here https://github.com/deors/deors.demos.java8):

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import org.javatuples.Pair;

public class SumProductCalculationJava7 extends RecursiveTask<Integer> {
  private static final long serialVersionUID = 6939566748704874245L;
  private int threshold = 10;
  List<Pair<Integer, Integer>> pairList;

  public SumProductCalculationJava7(List<Pair<Integer, Integer>> pairList) {
    super();
    this.pairList = pairList;
  }

  @Override
  protected Integer compute() {
    System.out.printf("fragment %s size %d\n", this, pairList.size());
    if (pairList.size() <= threshold) {
       return computeDirect();
    }
    int split = pairList.size() / 2;

    List<Pair<Integer, Integer>> forkedList1 = pairList.subList(0, split);
    SumProductCalculationJava7 forkedTask1 = new SumProductCalculationJava7(forkedList1);
    forkedTask1.fork();

    List<Pair<Integer, Integer>> forkedList2 = pairList.subList(split, pairList.size());
    SumProductCalculationJava7 forkedTask2 = new SumProductCalculationJava7(forkedList2);
    forkedTask2.fork();

    return forkedTask1.join() + forkedTask2.join();
  }

  private Integer computeDirect() {
    Integer sumproduct = 0;
    for (Pair<Integer, Integer> pair : pairList) {
      sumproduct += pair.getValue0() * pair.getValue1();
    }
    System.out.printf("fragment %s total %s\n", this, sumproduct);    return sumproduct;
  }
}

In short, the compute method from RecursiveTask contract checks the size of the list. If it is lower than the threshold it calculates the sum-product using a private method with a for each loop. If not, it splits the list in two pieces and recursively processes the two fragments. The result of processing the two fragments is, as expected, the sum of both fragment results.

It is verbose, yes, but it does a lot of work in the back stage: use the best concurrency patterns, running the threads, waiting for each fragment to finish before aggregating results bottom-up and returning the final glorious result. Try to do the same with threads in Java 2 style and look how your hair will turn grey during the process!

However, Java 8 still can beat this by a large margin.

Testing the Problem

Now let’s run this task with a main method or JUnit test:

  public static void main(String[] args) {
    List<Pair<Integer, Integer>> thePairList = new ArrayList<>();
    thePairList.add(new Pair<Integer, Integer>(10, 1));
    thePairList.add(new Pair<Integer, Integer>(12, 2));
    thePairList.add(new Pair<Integer, Integer>(14, 3));
    thePairList.add(new Pair<Integer, Integer>(16, 4));
    thePairList.add(new Pair<Integer, Integer>(18, 5));
    thePairList.add(new Pair<Integer, Integer>(20, 6));
    thePairList.add(new Pair<Integer, Integer>(22, 7));
    thePairList.add(new Pair<Integer, Integer>(24, 8));
    thePairList.add(new Pair<Integer, Integer>(26, 9));
    thePairList.add(new Pair<Integer, Integer>(28, 10));
    thePairList.add(new Pair<Integer, Integer>(30, 11));
    thePairList.add(new Pair<Integer, Integer>(32, 12));
    thePairList.add(new Pair<Integer, Integer>(34, 13));
    thePairList.add(new Pair<Integer, Integer>(36, 14));

    SumProductCalculationJava7 theTask = new SumProductCalculationJava7(thePairList);
    ForkJoinPool thePool = new ForkJoinPool();
    Integer result = thePool.invoke(theTask);
    System.out.printf("the final result is %s\n", result);
  }

Well done! As expected, the final result is 2870!

Try now with different lists of tuples or just copy and paste to have a very long list in a few seconds. Change the threshold, measure execution times and fine-tune the program until it is as good as it can be.

You still cannot be sure whether it will be as optimal when executed in a different JVM, though, with different CPU and RAM available resources performance may change and it is likely that the best threshold is different depending on the JVM, machine resources, OS, workload, etc., but you can still deliver this with confidence and fine tune it for production later.

Same Problem. Different Approach

Now let’s do the same calculation above with Java 8 parallel streams and lambda expressions. Don’t expect too much – it’s really as simple as it looks. In fact it is too simple that I just coded everything in the main method:

import java.util.ArrayList;
import java.util.List;
import org.javatuples.Pair;

public class SumProductCalculationJava8 {
  public static void main(String[] args) {
    List<Pair<Integer, Integer>> thePairList = new ArrayList<>();
    thePairList.add(new Pair<Integer, Integer>(10, 1));
    thePairList.add(new Pair<Integer, Integer>(12, 2));
    thePairList.add(new Pair<Integer, Integer>(14, 3));
    thePairList.add(new Pair<Integer, Integer>(16, 4));
    thePairList.add(new Pair<Integer, Integer>(18, 5));
    thePairList.add(new Pair<Integer, Integer>(20, 6));
    thePairList.add(new Pair<Integer, Integer>(22, 7));
    thePairList.add(new Pair<Integer, Integer>(24, 8));
    thePairList.add(new Pair<Integer, Integer>(26, 9));
    thePairList.add(new Pair<Integer, Integer>(28, 10));
    thePairList.add(new Pair<Integer, Integer>(30, 11));
    thePairList.add(new Pair<Integer, Integer>(32, 12));
    thePairList.add(new Pair<Integer, Integer>(34, 13));
    thePairList.add(new Pair<Integer, Integer>(36, 14));

    Integer result = thePairList.parallelStream().
      mapToInt(p -> p.getValue0() * p.getValue1()).sum();
    System.out.printf("the final result is %s\n", result);
  }
}

Just one line of code to solve the same problem. Same result, same magic in the back stage, same powerful performance, but simple, expressive and productive!

Moreover, the JVM does all the optimizations for you. Depending on the variables mentioned above, like CPU, RAM or workload, the JVM can apply different approaches at runtime and make sure that your code runs as quick as possible in all conditions.

This is just one example on how Java 8 lets you write better code, so don’t wait for others to ask you to do it. Try to adopt Java 8 today!