Thread Local Storage in Java


This post is part of the Java Advent Calendar and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, Tweeting, FB, G+, etc!      
It was also republished under https://www.voxxed.com/blog/2014/12/thread-local-storage-in-java/


One of the rarely known features in Java among developers is Thread-local storage. The idea is simple, and the need for it comes in  scenarios where we need data that is, well, local for the thread. For example, if we have two threads that refer to the same global variable but we want them to have separate values independently initialized of each other.
Most major programming languages have implementations of the concept. For example, C++11 has the thread local keyword, and Ruby has chosen an API approach.
Java has also an implementation of the concept with  java.lang.ThreadLocal<T> and with subclass java.lang.InheritableThreadLocal<T> since version 1.2, so nothing new and shiny here.
Let's say that for some reason we need to have a Long specific for our thread. Using Thread local that would simply be:

public class ThreadLocalExample {

  public static class SomethingToRun implements Runnable {

    private ThreadLocal threadLocal = new ThreadLocal();

    @Override
    public void run() {
      System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());

      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
      }

      threadLocal.set(System.nanoTime());
      System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());
    }
  }

  public static void main(String[] args) {
    SomethingToRun sharedRunnableInstance = new SomethingToRun();

    Thread thread1 = new Thread(sharedRunnableInstance);
    Thread thread2 = new Thread(sharedRunnableInstance);

    thread1.start();
    thread2.start();
  }

}



One possible sample run of the following code will result in:

Thread-0 null

Thread-0 132466384576241

Thread-1 null

Thread-1 132466394296347

In the beginning the value is set to null to both threads, obviously each of them works with separate values since after setting the value to System.nanoTime() on Thread-0 it will not have any effect on the value of Thread-1 exactly as we wanted, a thread scoped long variable. One nice side effect is a case where the thread calls multiple methods from various classes. They will all be able to use the same thread scoped variable without major API changes. Since the value is not explicitly passed through one might argue it difficult to test and bad for design, but that is a separate topic altogether.

In what areas are popular frameworks using Thread Locals?

Spring, being one of the most popular frameworks in Java, uses ThreadLocals internally for many parts - easily demonstrated by a simple GitHub search. Most of the usages are related to the current user's actions or information. This is actually one of the main uses for ThreadLocals in JavaEE world, storing information for the current request like in RequestContextHolder:
private static final ThreadLocal<RequestAttributes> requestAttributesHolder = 
    new NamedThreadLocal<RequestAttributes>("Request attributes");
Or the current JDBC connection user credentials in UserCredentialsDataSourceAdapter. If we get back on RequestContextHolder, we can use this class to access all of the current request information from anywhere in our code. A common use case for this is  LocaleContextHolder, which helps us store the current user's locale. Mockito uses it to store the current "global" configuration and if we take a look at any framework out there is a high chance we'll find it as well.

Thread Locals and Memory Leaks

Now that we've learned about this awesome little feature, let's use it all over the place! Well, we can do that, but if you try a few Google searches, you'll find that most posts out there claim that ThreadLocal is evil. That's not exactly true. It's a nice utility, but in some contexts,  you could easily accidentally create a memory leak.
“Can you cause unintended object retention with thread locals? Sure you can. But you can do this with arrays too. That doesn’t mean that thread locals (or arrays) are bad things. Merely that you have to use them with some care. The use of thread pools demands extreme care. Sloppy use of thread pools in combination with sloppy use of thread locals can cause unintended object retention, as has been noted in many places. But placing the blame on thread locals is unwarranted.” - Joshua Bloch
It is very easy to create a memory leak in your server code using ThreadLocal if it runs on an application server. ThreadLocal context is associated to the thread where it runs and will be garbaged once the thread is dead. Modern app servers use pool of threads instead of creating new ones on each request, meaning you can end up holding large objects indefinitely in your application.  Since the thread pool is from the app server, our memory leak could remain even after we unload our application. The fix for this is simple - free up resources you do not need. One other ThreadLocal misuse is API design. Often I have seen use of RequestContextHolder(that holds ThreadLocal) all over the place, like the DAO layer, for example. Later on, if one were to call the same DAO methods outside a request, for instance, and scheduler, he would get a very bad surprise. Even though, the variables in ThreadLocal are local to the thread they are very much global in your code. So, if you want to avoid maintenance developers hunting you down and taking their revenge, make sure you really need this thread scope before you use it.

More info on the topic

http://en.wikipedia.org/wiki/Thread-local_storage
http://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/
https://plumbr.eu/blog/how-to-shoot-yourself-in-foot-with-threadlocals
http://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable
https://plumbr.eu/blog/when-and-how-to-use-a-threadlocal
https://weblogs.java.net/blog/jjviana/archive/2010/06/09/dealing-glassfish-301-memory-leak-or-threadlocal-thread-pool-bad-ide
https://software.intel.com/en-us/articles/use-thread-local-storage-to-reduce-synchronization



Published on Dec 18, 2014 by Mite Mitreski
Updated on 12/18/2014 10:56:00 PM

How to Not Hate JavaScript: Tips from the Frontline


This article was originally published on voxxed under, https://www.voxxed.com/blog/2014/11/how-to-not-hate-java-script-tips-from-the-frontline/


In my work assisting teams with JavaScript related problems, I’ve noticed some common issues. If you're experiencing frustrations with the language too, this article might be of some assistance. Disclaimer: a few of my tips might be obvious to some of you, but hopefully you’ll find at least some useful nuggets of information here! These pointers are especially useful when dealing with enterprise applications and CMS solutions. This is where we have our code, the CMS code, the code from that team nobody wants to mention...and, of course, all of them are loaded asynchronously.

The Debugger Statement


This is one of the most underused features when dealing with JavaScript, especially since it’s supported by the majority of browsers. The debugger statement was part of the first edition of ECMA Script so it's been here for quite some time.

Fundamentally it’s a simple way of adding a breakpoint. If we have code where we loop over an element list and then process the elements...



...we can add the debugger statement inside the loop so that we have a breakpoint on each iteration:



The triggering of the breakpoint happens when the execution of the code is done in the place where we have added it. In cases where there is no debugger handler - for example in most browsers without dev tools - this statement has no effect.

On the dev tools side, it will appear as if we have manually placed the breakpoint.



Of course, this is not for code you want to leave in production, but it is an extremely useful feature during the development period. It has been a life changing feature for me, especially when dealing with the vendor based JavaScript and a whole lot of callbacks.

Use the Console Luke!


Most of the developers use the console.log in for debugging purposes, but did you know about console.warn, console.error, and console.info? :




All of these support C style formatted output like:

console.log("Hello %s", "Brian");

There are also plenty of JS logging frameworks. Proper logging is essential in most programming languages, and JavaScript is no exception to this. Note that not all logging functions are standardized, and you might need to provide fallback for certain browsers. For reference, there is a more extensive article regarding logging in the real world here.

Overview of JS objects using Console.table()


Often we load data from various services and want have a nice view of it on our console - especially when the data is represented as a list of objects. For example, if we were to load a list of beers from openbeerdatabase.com (yes this database exists, and it is awesome). Using the HTTP GET beers, http://openbeerdatabase.com/documentation/beers-get call we receive a list of objects. After receiving the list, we just print it out using console.log:




The resulting list is difficult to navigate in the console. It’s tricky to get a clear picture of what the data represents. Even if we were to loop through the data, it would still be tedious. Same goes for any large JavaScript object or a list.

If we were to replace the console.log with console.table and make the call again we'd get this:


Obviously, the data is shown in a table and it is now sortable using the attributes of the objects. This makes the navigation easier. For example, this is a simple way to visually compare two arrays:

console.table([[1,2,3], [2,3,4]]);

would result in more clear version, especially if we had more sub-arrays:


Getting the Call Trace


Sometimes we want to know the call trace, aka "Who called my function". This is often visible when we get a failure - but even on success, we could get the call trace using console.trace :


Note that console.trace is a non-standard functionality and is not something you should have in production. It is, however, supported by major desktop browsers.
Async Call TraceConsole.trace works just fine for normal function calls. In most developer tools, we get the same call trace when we stop on the breakpoint. When the call is async(callback) this information is not available because the scope of the closure(callback function) is limited to the data that it holds. Fortunately, in the newer version of Chrome dev tools we have the flag async. So what previously would have been a portion of the call information...



...now becomes a full call trace containing the scope of the caller and the callback:



Most definitely an essential feature in today's asynchronous world, in my opinion. For an extensive explanation of how the async call trace works, I recommend this HTML5rocks article.

Who’s Changing My Object?: Objects.observe + console.trace

Sometimes objects get some of their properties changed, but we cannot figure out the cause. In this case, objects.observe comes to the rescue. Let's say we want to check for all changes to our person object:



Since we have combined this with the console.trace, we can also see the call trace. Awesome right?

Well, not so much, since at the time of writing only Chrome supports this and it is a non-standard functionality. Fortunately, it is proposed as part of ECMAscript 7. There is also a similar internal variant for this in Gecko based browser object.watch. Then again, when it comes to debugging, anything we can get is useful. Note that Objects.observe primary function is not debugging, but it is a great side effect.

Who’s Changing My DOM/HTML Element - Aka, Who’s F***ing Up My Code?


In complex applications, we may end up in a situation where we do not know how a certain HTML element got changed, moved, added, or had some of it's attributes modified. One way to figure out is to attach the now deprecated mutation event listeners. The API for this is far from ideal, and there are other shortcomings. The newer browser version comes with an object called MutationObserver, which enables us to watch a certain DOM element.

Suppose we wanted to list all mutations on the entire document, where the document can also be any DOM element selected:



There is also the non-programmable solution we can use in Chrome called DOM breakpoints which still uses mutation events in the background.

Server Side Logging of Client Side Errors


As simple as that, just add the error handler to the window object and you're done with the client side. The handler can then make an AJAX request to a REST endpoint which will store the error information on your server. You might find out that a client using IE 8 has a lot of issues this way because IE versions predating 9 have no string.trim(). I guess string trim is just not that essential.

Anyway, this what the most basic server side logging of client side errors might look like:


Of course, this is the most basic of solution you can have. There are tons of better solutions out there like http://www.stacktracejs.com/ or http://jsnlog.com/ and a more extensive article on Mozilla hacks. There is also a great Hacker News discussion on this topic, but hey, this is certainly a good start!
Use Google Or Other Analytics Tools to Store Data



I know you are way too busy to be writing any backend code. so why not just store the data in Google Analytics?



You can certainly do this, but note that this is a hack, and there are a lot of better commercial options out there like http://usersnap.com if you want to be really thorough - but even a hack is better than no information, which is what most people have.

So, You Don’t Think JavaScript is “Real” Code?



I had been mulling over this idea for a long time, when, a few years back, I realized that I was making a huge mistake in my approach to JavaScript. You should take it just as seriously as Java, C# or Ruby.

Diseases are something you pick up, JavaScript is something you have to learn.

Just like other programming languages, you need a book, programming exercises and multiple projects. JavaScript also needs coding style guides, testing frameworks, and code analysis, and so on. Basically everything that you have a "real code". There are complete solutions like Yeoman and JHipster that will help you with full integration.

Unless you do this, you will always end up hating JavaScript - which is a shame considering that JavaScript is all around you! If you follow best practices, most of the time you won't be debugging any code nor resorting to clever tricks. Unless you’re Chuck, that is.

More Resources:

https://github.com/DeveloperToolsWG/console-object/blob/master/api.md
https://developer.chrome.com/devtools#debugging-JavaScript
https://developer.mozilla.org/en-US/docs/Tools/Debugger
http://msdn.microsoft.com/en-us/library/dd565625%28v=vs.85%29.aspx
https://developer.mozilla.org/en-US/docs/Web/JavaScript
www.HTML5rocks.com




Published on by Mite Mitreski
Updated on 12/18/2014 10:48:00 PM

Java2Days 2014: From JavaSpaces, JINI and GigaSpaces to SpringBoot, Akka – reactive and microservice pitfalls

This my 5-th year in a row where together with jugmk attend Java2days, a conference in Sofia, Bulgaria. While not so obvious from the name it is a 2-day java conference and currently the biggest one near us that we can take a bus to go to.
This year I had a talk titled "From JavaSpaces, JINI and GigaSpaces to SpringBoot, Akka – reactive and microservice pitfalls."
or buzz words and hate words all in one.

About the topic 


My talk this year was about microservices even though it had a long title with lots of strange words it was more of a concepts talk.
I gave a basic introduction into what reactive programming means for different people, the reactive manifesto and of course Microsoft Excel.
Long title = crowds of attendees
Next part was to define what microservies are and what they can be for different organization.
The Unix aspect of microservices had to be covered so I did just that.

My goal with the talks was not really to compare frameworks for this or that, but I just gave a short overview of what ideas are behind the development of some libraries.

The last major section was the real conclusion phase called how not to fail at microservices.
I gave some  recommendations from my personal experience as well as references to important books on the subject.
One of them available on early access:


And also the famous Release It book which covers some of the scenarios that are essential for microservice development.
My main take out from the talk was:
 Don't fall for the hype and make sure you start small and then grow. If your team and operations can  handle it then increase the granularity. 

Here are the full slides of the talk:



Microservice pitfalls from Mite Mitreski


The conference 


As for the full conference it was great  to meet up with BG-JUG folks like Ivan St. Ivanov, Mihail Stoynov, Martin Tosev  and improve the cooperation between JUGMK and BG-JUG.
 There were also the  standard visitor's Josh Long and Andrew Lombardi who are there to stay :


I got to meet with John Davis and learn how others use archaic tuple space technologies and how the banking world functions. Overall it was a great experience and even though at time some of the conference topics were overly light or outdated for my taste but the social aspect of it was more than sufficient to cover any shortcomings on the technical side.
For example Mani Sarkar had a great talk on "Learning the two Ts", it was great to meet up with him as well.


One other positive trend that is happening this year is we had record number of JUGMK speakers and participants on Java2Days. The same trend is also on other conferences and is a great thing to see.




The JUG Factor


I know I'm forgetting someone to mentions, but overall an interesting social experience and a great meetup. 

Published on Nov 25, 2014 by Mite Mitreski
Updated on 11/25/2014 01:14:00 AM

Virtual Java User Group - simple concept with quality content

Virtual JUG is a simple concept based on the idea to organize a group that would generate quality content.
It is simpler to get technical leaders from around the world to present online and there are no travel cost concerns.  The intent is not to replace local JUG's but rather increase their value and also represent a sort of global JUG. Additionally it enables developers without an access to a local jug with a means to connect with many developers around the world.


Live sessions are streamed online and as chat ##virtualJUG on Freenode is used. But you don't have to trust my word for the quality of the content, here is a list of the past sessions: 


Many thanks to Simon Maple the organizing team Anton ArhipovGeert BevinJames GoughOliver White. Keep up the good work. 


Published on Apr 13, 2014 by Mite Mitreski
Updated on 4/13/2014 10:36:00 PM

*nix for developers

Unix and Linux in their various forms are everywhere. Werther you are working on some server-side application or mobile app at any stage it is very likely that it will use Unix at some point.
That is why at our company we decided to have a small introduction demo/discussion on some useful concepts and command line tools.
We also went through a high-level overview starting with initial with run level and job control.
While most of the demoing is not visible via the slides I decided to share the slides anyway:


Published on Apr 9, 2014 by Mite Mitreski
Updated on 4/09/2014 08:39:00 PM

Redneck conditional anti-pattern

Sometimes I encounter weird looking if statements. By weird, I'm thinking of multiple negations all over the code base. Just a few days ago together with my colleague we found them very exotic during debug of an external library. From this point on, I'll call the following anti-pattern redneck negation or "I ain't not going to do that".



 So let's take a look at a snippet:
if(!some_flag_that_means_off) {
   //handle negative scenario where we change the flag value
} else {
   //handle positive scenario where we also change the flag value
}
//decide upon my flag
The simpler version would be an extracted method with:
 if(some_condition) {
    //return positive
 } else {
    //return negative
 }
Now the code is easier to read and simpler to maintain.

State of mind

You might be wondering how someone writes this or how we end up with this type of multiple negation codes. It is easy to judge people, but the reality is that this might have been done at some crazy pressure to "save time". It is possible the programmer working on this part was solving some bug and did not consider the readability. It could be also the lack of knowledge or attention or maybe cosmic rays. No matter the reasoned judgment is not the answer.

I once had a discussion with a friend about a related topic and he said on his team they have banned the debugger. This might seem crazy at first, but when you think about it, we usually add various redundant if's during debugging. We add them without seeing the bigger picture and that is one other way we can end up with conditionals all over the place. Now his argument against the debugger looks less crazy.

While not all if's are made the same, the vast majority of them can be avoided and the complexity they bring with them. Of course, this is a broader topic but it is something to keep in mind.

How do we fix this?

Even though this should be simple enough to change I would first start with the following:
Whenever I do refactoring, the first step is always the same. I need to build a solid set of tests for that section of code. The tests are essential because even though I follow refactorings structured to avoid most of the opportunities for introducing bugs, I'm still human and still make mistakes. Thus I need solid tests.
Martin Fowler - Refactoring: Improving the Design of Existing Code
It is truly one of the best advice someone can give you before you start refactoring. The statement switch from negative to positive should be simple enough to start off with. Then again, it should be simple enough to not even introduce this but that is obviously not the case.
Next step would be to remove the changing of the flag either by extracting this into a separate method or even possibly removing it altogether.

There are plenty of options in the simplification of the conditionals. One way is to [replace conditional] with polymorphism. There is a great talk by Misko Hervey part of the Google Clean Code Talks titled "Inheritance, Polymorphism, & Testing". Also, we can run into the conditionals arrow anti-pattern and the related text from Jeff Atwood titled Flattening Arrow Code.

Published on Mar 3, 2014 by Mite Mitreski
Updated on 3/03/2014 10:40:00 PM

[Book review] OAuth 2.0 Identity and Access Management Patterns


I accepted to do a review of the newly published OAuth 2.0 Identity and Access Management Patterns by Martin Spasovski. He is a friend of mine so with impartiality in mind it would be fail enough of me to give this information beforehand.

OAuth is the most widely known and used authorization framework. There are many service providers like Facebook and Twitter making it easy to connect with millions of users. From the users perspective is significantly simpler than remember and managing different passwords which is easily manipulated. The book make nice introduction to integration of OAuth 2.0 on web applications, desktop and mobile. It also covers various flows and a server side implementation using SpringMVC. While the examples throughout the book are clean one part really caught my attention :
  tokenEndpoint
  .concat("?grant_type=client_credentials")
  .concat("&client_id=").concat(clientId)
  .concat("&client_secret=").concat(clientSecret)
  .concat("&user_id=").concat(user_id)
Concatenating strings using String.concat is something I would consider a premature optimization for speed. Much cleaner way would be the regular + based concatenation or even maybe String.format. In any case that is something that is probably completely irrelevant and off topic but I just can't help it.

What I found really interesting is the chapter titled "Additional Security with SAML", mostly because I did not know there is a thing like this out there let alone used it. SAML or Security Assertion Markup Language is a XML based protocol for exchange of authentication and authorization data between user and provider where the user can be a provider itself. SAML provides Single Sign-on across multiple domains and identity federation which is useful for many enterprise applications.

A thing to note is that the proofreader did not made a good job since even me with my many typos and grammar error noticed this. This is a problem I had in my book  and is an issue with most of the Packt publishing books. Some folks on reddit and over the "internets" have claimed that this was the case because most of the authors are non-native english speakers. This is is not be the case since there many non-native authors for other publishers and they do a great job so why can't Packt?
For me this does not affect the overall impression but I know there are some grammar nazi out there.

One incorrect assumption I made before starting with the book is that it will only cover Java related tooling and implementation. There are sections with references to all major programming languages and various tooling support that will assist you independent from your preferred language.

To sum it up the book is an awesome reference for OAuth 2.0 and the various pattern for integrating it into your system. I know I will get back to it at some point in the future. You should get it if you expect to do any OAuth integration in the future whether it is server or client side.


Published on Feb 22, 2014 by Mite Mitreski
Updated on 2/22/2014 12:11:00 AM

"Thou shalt not spam" or what are web notifications

Web notifications are one of the newer features added into modern browsers. They are intended as alerts for the user outside of the web page context. The idea is for them to be browsers and system independent, for example, when using a mobile browser notification could go into the home screen of the device. On the desktop usually they show up on the right-corner of the screen, at least on most desktop environments. They can be very annoying thing and you should think if thoroughly before you decide this is the right way to inform the users. There are some restrictions that avoid the creation of popup but I still have a bad feeling whenever I see one of these. One example of these notifications are the gmail/gtalk updates that show up on new messages (they are useful and annoying at the same time). This is done via the Notification API and we will do a simple example of its usage.

The implementation

First we can start with a simple wrapper for the Notification API that will have a fallback for the WebKit temporary implementation. We will define a simpleNotification object that will be the wrapper and it will contain a function called show that accepts data parameter. This data parameter is also a wrapper object that contains all the required info for a simple notification. For example :

var data = {
    icon: "http://upload.wikimedia.org/wikipedia/commons/7/7e/Jacob_de_Gheyn_-_Wapenhandelinge_4.jpg",
    title: "The Art of War - The Use of Spies ",
    body: "text",
    timeout : 7000,
    errorCallback: function(){
      $("#fallback").text(this.body);
    }
  };

Where the errorCallback is executed if non of our implementations are supported by the browser, as for the others, they should be self descriptive.

var simpleNotification = (function () {
   var my = {};
    my.show = function (data) {
     if (window.webkitNotifications) {
       //check if there is a support for webkitNotifications
       if (window.webkitNotifications.checkPermission() == 0) {
         var notification = webkitNotifications.createNotification(data.icon, data.title, data.body);
         notification.show();
         //set timeout to hide it
         setTimeout(function(){
             notification.cancel();
          }, data.timeout);
       } else {
         webkitNotifications.requestPermission(function () {
           //call the same function again
           my.show(data);
         });
       }
     }else if (window.Notification) {
   //Currently a fallback, but this should be the real implementation on all browsers
       if ("granted" === Notification.permissionLevel()) {
         var notification = new Notification(data.title, data);
         notification.show();
       } else if ("default" === Notification.permissionLevel() ) {
         Notification.requestPermission(function () {
           //call the same function again
           my.show(data);
         });
       }
     }else{
       //Notifications not supported,going with fallback
      data.errorCallback();
     }
   };
 return my;
}());

The standard based implementation is the one that uses window.Notification. An interface defined by W3C

  [Constructor(DOMString title, optional NotificationOptions options)]
  interface Notification : EventTarget {
    static readonly attribute NotificationPermission permission;
    static void requestPermission(optional NotificationPermissionCallback callback);

    attribute EventHandler onclick;
    attribute EventHandler onshow;
    attribute EventHandler onerror;
    attribute EventHandler onclose;

    readonly attribute NotificationDirection dir;
    readonly attribute DOMString lang;
    readonly attribute DOMString body;
    readonly attribute DOMString tag;
    readonly attribute DOMString icon;

    void close();
  };

Since our data object already contains similar values it can be passed directly in the instantiation of the Notification object. For example :

var notification = new Notification(data.title, data);

On the other hand window.webkitNotifications is the non-standard Chrome implementation. For a more detailed usage of the webkit version please see decadecity blogpost.

In order for us to be able to trigger the notification it is important in the html snippet to have some element that can be user triggered. We have some simple html containing a button

 <body>
   <button id="show">Show quote</button>
   <div id="fallback"> my fallback notification</div>
 </body>

This is needed in order to have request for the permission and to avoid “spam” notification. In our case this is the onClick function on the button. More specifically the jQuery click event. The call now is very simple, we just create the data object using some defaults and load some random data.

$(document).ready(function() {
    $("#show").click(function () {
      var data = {
        icon: "http://upload.wikimedia.org/wikipedia/commons/7/7e/Jacob_de_Gheyn_-_Wapenhandelinge_4.jpg",
        title: "The Art of War - The Use of Spies ",
        body: "text",
        timeout : 7000,
        errorCallback: function() {
          $("#fallback").text(this.body);
        }
      };
      var randomSampleId = Math.floor(Math.random()*sampleData.quotes.length)+1;
      var sample = sampleData.quotes[randomSampleId];
      for (var key in sample) {
        data.title += key;
        data.body = sample[key];
       }

      simpleNotification.show(data);
    });
});

The sample data used is a JSON containing quotes from “Sun Tzu -The Art of War” which is also available for for free on project gutenberg (win for public domain). The data is structured in the following format :

var sampleData = {
    quotes: [
     {
       "1": "Sun Tzu said: Raising a host of a hundred thousand men and marching them great distances entails heavy loss on the people and a drain on the resources of the State.The daily expenditure will amount to a thousand ounce of silver. There will be commotion at home and abroad, and men will drop down exhausted on the highways, As many as seven hundred thousand lies will be impededin their labor."
     },
     {
       "2": "Hostile armies may face each other for years, striving for the victory which is decided in a single day.This being so, to remain in ignorance of the enemy's condition simply because one grudges the outlay of a hundred ounces of silver in honors and emoluments, is the height of inhumanity."
     }
    ]
 };

One more thing to note is that Web Notifications were not supported by IE when this article was written.

You can play around with the jsfiddle to see it in action.

Related links

Published on Jan 20, 2014 by Mite Mitreski
Updated on 1/20/2014 02:37:00 AM

Run, JUnit! Run!!!

This blog post is crossposted and originally part of the 2013 edition Java Advent Calendar a lovely initiative from Attila-Mihaly Balazs and the Transilvania JUG 

JUnit together with JavaScript and SVN are some of the technologies that programmers often start using without even reading a single blog post let alone a book.  Maybe this is a good thing since they look simple enough and understandable so we can use them right away without any manuals, but this also means that they are also underused. In this article we will go through some features of JUnit that I consider very useful.

Parameterized tests 

Sometimes we need to run the same method or functionality with many different inputs and different expected results. One way to do this would be to create separate tests for each of the cases, or you
can use loop but that it would be harder to track down the origin of a possible test failure.

For example if we have the following value object representing rational numbers:

public class RationalNumber {

  private final long numerator;
  private final long denominator;

  public RationalNumber(long numerator, long denominator) {
    this.numerator = numerator;
    this.denominator = denominator;
  }

  public long getNumerator() {
    return numerator;
  }

  public long getDenominator() {
    return denominator;
  }

  @Override
  public String toString() {
    return String.format("%d/%d", numerator, denominator);
  }
}
And we have a service class called App with a method convert that divides the number to a rounded value of 5 decimal :

public class App {

  /**
   * THE Logic
   *
   * @param number some rational number
   * @return BigDecimal rounded to 5 decimal points
   */
  public static BigDecimal convert(RationalNumber number) {
    BigDecimal numerator = new BigDecimal(number.getNumerator()).
        setScale(5, RoundingMode.HALF_UP);

    BigDecimal result = numerator.divide(
        new BigDecimal(number.getDenominator()),
        RoundingMode.HALF_UP);

    return result;
  }
}

And for the actual AppTest class we have

@RunWith(Parameterized.class)
public class AppTest {

  private RationalNumber input;
  private BigDecimal expected;

  public AppTest(RationalNumber input, BigDecimal expected) {
    this.input = input;
    this.expected = expected;
  }

  @Parameterized.Parameters(name = "{index}: number[{0}]= {1}")
  public static Collection<Object> data() {
    return Arrays.asList(new Object[][]{
      {new RationalNumber(1, 2), new BigDecimal("0.50000")},
      {new RationalNumber(1, 1), new BigDecimal("1.00000")},
      {new RationalNumber(1, 3), new BigDecimal("0.33333")},
      {new RationalNumber(1, 5), new BigDecimal("0.20000")},
      {new RationalNumber(10000, 3), new BigDecimal("3333.33333")}
    });
  }

  @Test
  public void testApp() {
    //given the test data
    //when
    BigDecimal out = App.convert(input);
    //then
    Assert.assertThat(out, is(equalTo(expected)));
  }

}


The Parametrized runner or  @RunWith(Parameterized.class)  enables the "parametrization" or in other words the injection of the collection of values annotated with  @Parameterized.Parameters into the Test constructor where each of the sublist is an parameter list.  This means that each of the RationalNumber objects in the data() method will be injected into the input variable and each of the BigDecimal values would be the expected value, so in our example we have 5 tests.

There is also an optional custom naming of the generated test added in the annotation, so "{index}: number[{0}]= {1}" will be replaced with the appropriate parameters defined in the data() method and the "{index}" placeholder will be the test case index, like in the following image

Running the parametrized tests in IntelliJ Idea 











JUnit rules

The simplest definition of JUnit rules is that they are in a sense an interceptors  and very similar to the Spring aspect oriented programming or Java EE interceptors API. Basically you can do useful things before and after the test execution.
OK so let's start with some of the built in test rules. One of them is ExternalResource  where the idea is that we setup an external resource and after the teardown garteet the resource was freed up. A classic example of such test is a creation of file, so for that purpose we have a built in class TemporaryFolder but we can also create our own ones for other resources :



  public class TheRuleTest {
  @Rule
  public TemporaryFolder folder = new TemporaryFolder();

  @Test
  public void someTest() throws IOException {
    //given
    final File tempFile = folder.newFile("thefile.txt");
    //when
    tempFile.setExecutable(true)  ;
    //then
    assertThat(tempFile.canExecute(), is(true));
  }
}

We could have done this in a @Before and @After blocks and use java temp files but it is easy to forget something and leave some of the files unclosed in some of the scenarios where a test fails.

For example there is also a Timeout rule for methods where if the the execution is not finished in given time limit the test will fail with a Timeout exception. For example to limit the running for 20 milliseconds :
 

@Rule
public MethodRule globalTimeout = new Timeout(20);

We can implement our own rules that can do a policy enforcement or various project specific changes. The only thing that needs to be done is for us to implement the TestRule interface.
A simple scenario to explain the behaviour is to add a rule that prints someting before and after test.


import org.junit.rules.TestRule;

import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class MyTestRule implements TestRule {

  public class MyStatement extends Statement {

    private final Statement statement;

    public MyStatement(Statement statement) {
      this.statement = statement;
    }

    @Override
    public void evaluate() throws Throwable {
      System.out.println("before statement" );
      statement.evaluate();
      System.out.println("after statement");
    }

  }

  @Override
  public Statement apply(Statement statement,
                         Description description) {

    System.out.println("apply rule");
    return new MyStatement(statement);
  }

}

So now that we have our rule we can use it in tests, were the tests will just print out different values:

public class SomeTest {

  @Rule
  public MyTestRule folder = new MyTestRule();

  @Test
  public void testA()  {
    System.out.println("A");
  }

  @Test
  public void testB()  {
    System.out.println("B");
  }
}
When we run a test the following output will be created on the  console output :

apply rule
before statement
A
after statement
apply rule
before statement
B
after statement
From the built in one there is one called ExpectedException that can very useful when trying out testing errors. Additionally there is an option to chain the rules that can be useful in many scenarios.

To sum up

If you wanna say that Spock or TestNG or some library build on top of JUnit have more features than JUnit, than that is probably true.
But you know what? We don't always have those on our class path and chances are that JUnit is there and already used all over the place. Than why not use it's full potential ?


Useful links

Published on Jan 8, 2014 by Mite Mitreski
Updated on 1/08/2014 12:40:00 AM