Saturday, July 9, 2016

How to deploy your project to Maven Central

So, you have finally got your project finialized, tested, and ready to go. You would probably want to make it available to users through their build system (Maven, Gradle,..). This post presents steps that you need to take to deploy your project to Maven Central.

1) Create a ticket in Sonatype for the creation of your Group ID:

  This can be done by creating an issue in Sonatype's tracker : https://issues.sonatype.org/. You usually get a response within one day.


2) Get your project ready to deploy:

   Before deploying your project, you need to make sure that your pom.xml contains a number of elements: project name, description, URL, license information, developer information, and SCM information. If you do not include these elements, your pom file will not be validated and you will not be able to deploy to Maven Central.

Here is a pom example: https://github.com/gwidgets/gwty-leaflet/blob/master/pom.xml

3) Snapshot Vs non snapshot :

If your release is a snapshot version, you need to include Sonatype's snapshots server. On deploy, Maven automatically detects if your version ends with -SNAPSHOT and deploys to the snapshot server.

<distributionManagement>
  <snapshotRepository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  </snapshotRepository>
</distributionManagement>


4) Generating Javadocs and including sources:

Including javadocs and sources is also mandatory, and checked by Sonatype at release time. There are several ways you can do it, but the easiest way is to include Maven javadocs and sources plugins which automatically generates them for you on build time.

Maven javadoc plugin : https://maven.apache.org/plugins/maven-javadoc-plugin/
Maven source plugin:  https://maven.apache.org/plugins/maven-source-plugin/

5) Sign your jar and pom:

This is the trickiest part. To be able to successfully release your project to Maven central, you need to generate a signature using GPG which will be used by Sonatype to verify your articacts. First of all, you will need to install GPG. The next step is to generate a public/private key pair. This step is descibed in more details in GPG's manual. Aftewards, you need to distribute your public key to a key server. We use https://pgp.mit.edu/ which allows you to directly copy paste the key. There are plenty of servers, it's a matter of preference. You can refer once again to the manual for how to send your keys to the server. Once done, you can sign your artifacts, you will have to sign both the jar and the pom. You can either do it manually from the termnial using gpg or using maven gpg plugin: http://maven.apache.org/plugins/maven-gpg-plugin/

6) Prepare your deploy:

Before deploying you will need to configure the server and its access information:
<distributionManagement>
  <snapshotRepository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  </snapshotRepository>
  <repository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
  </repository>
</distributionManagement>

<settings>
  <servers>
    <server>
      <id>ossrh</id>
      <username>your-id</username>
      <password>your-pwd</password>
    </server>
  </servers>
</settings>

It's better to include these information in a build profile, so that they are not shared if you ever make your project source code open to public, and also to be able to reuse them for other projects.
It's also a good practice to include maven's source, javadocs, and gpg plugins in a build profile, to avoid having to include them in each project.

7) Deploy to staging:

deploying to staging can simply be done by invoking Maven's deploy goal:

mvn deploy

8) Relase your project to Maven Central:

At this stage, you will able to find your project on Sonatype. You need to go to https://oss.sonatype.org/ and click on staging repositories. After choosing your repository, you need to click on --> close, as shown below. Once the repository is closed, you can click on release and your project will be released to Maven Central.


Sunday, June 26, 2016

the Chain of Responsibility design pattern

The chain of responsibility is a fairly easy to use design pattern. Its main goal is to allow several objects to collaborate in order to solve a problem. Each object knows what it can do, and if the request does not fall into its scope of responsabilty, the objects passes it to the next one, and so on. The rationale behind using this pattern is to enforce separation of concerns and decouple a problem smaller sub-problems to make it easier to solve.

An analogy that might help understanding the pattern is when you call the customer support for your phone operator. When you call the support, you are asked about the category of your request, and then you are dispatched to the agent who has the skills to handle your request. If the agent sees that your request needs another set of skills, he forwards it to another agent, and so on until your request is fullfilled.

In this tutorial, we are going to implement the chain of responsability based on the example above.

First of all, we need an interface (or abstract class) that will constisturte the building block of our chain. Each object that implements the interface will either process the request or forwards it to the next object.

public interface RequestHandler {
 
 public void process(Request request);
 
 public void setNext(RequestHandler handler);

}
Next we need to define the handlers that implements our interface.

public class SecurityRequestHandler implements RequestHandler {
 
 RequestHandler nextHandler;

 @Override
 public void process(Request request) {
  // TODO Auto-generated method stub
  if(request.getCriticityLevel() == CriticityLevel.SECURITY){
   System.out.println("Your request" + request.description + " is being handled by the security departement");
  }else if (nextHandler != null){
   System.out.println("Your request is being forwarded to another departement");
   nextHandler.process(request);
  }
  
 }

 @Override
 public void setNext(RequestHandler handler) {
  // TODO Auto-generated method stub
  this.nextHandler = handler;
  
 }
public class InfrastructureRequestHandler implements RequestHandler {
 
 RequestHandler nextHandler;

 @Override
 public void process(Request request) {
  // TODO Auto-generated method stub
  if(request.getCriticityLevel() == CriticityLevel.INFRACSTRUCTURE ){
   System.out.println("Your request: " + request.description + " is being handled by the financial departement");
   }else if (nextHandler != null){
    System.out.println("Your request is being forwarded to another departement");
    nextHandler.process(request);
   }
 }

 @Override
 public void setNext(RequestHandler handler) {
  // TODO Auto-generated method stub
  this.nextHandler = handler;
  
 }

}


public class FinancialRequestHandler implements RequestHandler {
 
 RequestHandler nextHandler;

 @Override
 public void process(Request request) {
  // TODO Auto-generated method stub
  if(request.getCriticityLevel() == CriticityLevel.FINANCIAL ){
  System.out.println("Your request " + request.description + " is being handled by the financial departement");
  }else if (nextHandler != null){
   System.out.println("Your request is being forwarded to another departement");
   nextHandler.process(request);
  }
  
 }

 @Override
 public void setNext(RequestHandler handler) {
  // TODO Auto-generated method stub
  this.nextHandler = handler;
  
 }

}
For illustration purposes the Request POJO looks like:


public class Request {
 
 String description;
 
 int criticityLevel;
 
 public Request(String description, int clearanceLevel) {
  this.description = description;
  this.criticityLevel = clearanceLevel;
 }

 public String getDescription() {
  return description;
 }

 public int getCriticityLevel() {
  return criticityLevel;
 }

}
Finally, we can chain our handlers according to their level of responsibility.

public class Main {
 
 public static void main(String[] args){
  
  RequestHandler handler1 = new SecurityRequestHandler();
  RequestHandler handler2 = new InfrastructureRequestHandler();
  RequestHandler handler3 = new FinancialRequestHandler();
  
  
  
  handler1.setNext(handler2);
  handler2.setNext(handler3);
  
  Request request = new Request("Error in the last month bill", CriticityLevel.FINANCIAL);
  Request request2 = new Request("Poor network coverage", CriticityLevel.INFRACSTRUCTURE);
  
  System.out.println("--------------Request1");
  handler1.process(request);
  
  System.out.println("--------------Request2");
  handler1.process(request2);
  
  
  
 }

}
Result:






Tuesday, June 7, 2016

Introduction to Rx Java.


It took me lots of reading to get my head around Rx Java, so I decided to write something to simplify it for beginners. Rx Java is a framework or an extention of the Java language that introduces a new way of designing applications called reactive programming. Reactive programming involves a number of principles, but for simplicity sake let's just say that it is about developing applications that reacts quickly and effectively to changes in state. Rx Java can also be defined as advanced form of the gang of four Observer pattern. Rx Java was first developed for internal use of Netflix, and was then open sourced. There are two very important notions to retain while working with Rx Java: Observables, and Subscribers.

Observables are the main concept of Rx Java. They are entites that can be observed by a number of subscribers, and that notifies all of them when a change in state occurs.

A subscriber receives updates from Observables and takes actions. On subsription, a subscriber defines three things: what it will do with the data, what it will do in case of an error, and what he will do on completion.

Let's go through a first example:

List<Integer> list = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList());

 Observable observable = Observable.from(list);

 observable.subscribe(new Observer<Integer>(){
   public void onCompleted() {
    System.out.println("Completed");
   }

   public void onError(Throwable arg0) {
    // Do something on error
   }

   public void onNext(Integer arg0)   {
    System.out.println(arg0 + " ");
   }
   });
Result:

In this example, we created an observable from an iterable. The observable provided the values to the subscriber as a stream. The observable printed each value on reception and printed the word "Completed" on completion.  

Let's explore another way of creating Observables. Suppose we have a service that monitors traffic in an intersection, and sends  updates to a terminal station as the state of traffic changes, we can create our observable using the create() method, and defining what we send to our observers inside the call() method. 

Observable<String> trafficStream = Observable.create(new OnSubscribe<String>() {
  @Override
   public void call(Subscriber<String> sub) {
     //Simulation of a stream  
      while(true){
         sub.onNext(trafficState[random.nextInt(3)]);
      } 
   }
  })

Notice that we used the onNext method to send the data to our subscriber.

Once we subscribe to our observer :

trafficStream.subscribe(new Observer<String>(){
   @Override
   public void onCompleted() {
    
   }
   @Override
   public void onError(Throwable arg0) {
    
   }
   @Override
   public void onNext(String arg0) {
    System.out.println("Traffic state : " + arg0);
   } 
    
   });
We get:

Composing Observers

There are situation where developpers would need to compose several observers into one to be able to subscribe to all of them at once. Rx Java provides several ways of composing observables.

For composing observables of the same type, Rx Java provides the merge() method:

Observable.merge(observable1, observable2)
   .subscribe(new Observer<Integer>(){
   @Override
   public void onCompleted() {
    // Merged completion action
    
   }

   @Override
   public void onError(Throwable arg0) {
    // Merged error handling
    
   }

   @Override
   public void onNext(Integer arg0) {
    // Merged completion action
    System.out.println(arg0);
   }
    
    
   });

For composing observables of different types, Rx Java provides the zip() method:

Observable.zip(observable, observable2, new Func2<Integer, Double, Map<Integer, Double>>(){
    @Override
    public Map<Integer, Double> call(Integer arg0, Double arg1) {
     // TODO Auto-generated method stub
     Map<Integer, Double> map = new HashMap<Integer, Double>();
     map.put(arg0, arg1);
     return map;
    }
     
     
    }).subscribe(new Observer<Integer, Double>(){

    @Override
    public void onCompleted() {
     // TODO Auto-generated method stub
     
    }

    @Override
    public void onError(Throwable arg0) {
     // TODO Auto-generated method stub
     
    }

    @Override
    public void onNext(Map<Integer, Double> arg0) {
     // TODO Auto-generated method stub
     arg0.forEach((k, v) -> System.out.println(" " + k + " " + v ));
     
    }
     
    });

Interesting videos that explains core concepts of reactive programming:
https://www.youtube.com/watch?v=dwP1TNXE6fc
https://www.youtube.com/watch?v=7D9QfMj_KwI

Tuesday, May 17, 2016

Spring boot quick overview


If there is a word they care about at Pivotal, it is production. Deploying apps and services to production effectively is what companies strive for, sometimes without finding the perfect formula. Spring Boot is meant to overcome this challenge, for Spring framework users. Imagine you have a genie that grants your software developement wishes before you even know them,  or, using a more serious definition, a framework that helps you get rid of all the boiler plate code and configuration, and focus on things that matter. It uses your build system (Maven or Gradle) to predict the things that you can possibly do with your application, and auto configure them for you. For example, if you include a Spring Web dependency, Spring Boot gently includes an embedded Tomcat server with an 8080 default port in your jar, no need to deploy, it's already done for you. Another wonder of Spring boot is database configuration. Once you include a database driver, it auto configures the data access layer for you. It also picks up any schemas or data files (.sql) and executes them on start up. Impressive, ha? This is only a drop in the bucket of what Boot could do.
 Spring Boot has some downsides as well. Additional effort is required by the developper to modify the default configuration if  needed, which is not always easy. In any case, let's give it a try.

In this tutorial, we will go through an example of how to quickly build a Rest application with an embeded database using Spring Boot.

We will start first by using SPRING INITIALIZR to quicky bootstrap our app.






There is a bunch of options to choose from. In our case, we chose: Web, JPA, and H2 database dependencies. We can now click on generate to download the project, and import it into an IDE ( eclipse for this tutorial).

We will then take care of the data access by creating our model object and the corresponding data access object (dao) to perform operations on the database.

 @Entity(name="users")
public class User {
 
 @Id @GeneratedValue
 int id;
 String userName;
 String firstName;
 String lastName;
 
 
 public User(){
  
  
 }

//.. getters & setters

}

Using Spring data, there is no need to programtically implement the operations, all we need to do is to extend CrudRepository.

public interface UserDao extends CrudRepository{
      public User findByUserName(String userName);
}
Notice that we have added a findByUserName method, which is also automatically implemented by Spring Data (based on the name of the method). For those, not familiar with Spring data this what this framework is about.

Next we can start implementing our Rest endpoints:



@Controller
public class UserController {
 
 @Autowired UserDao userdao;
 
 @RequestMapping(value="/users", method=RequestMethod.GET)
 public @ResponseBody List<User> getAllUsers(){
  return (List<User>) userdao.findAll();
 }
 
 @RequestMapping(value="/users", method=RequestMethod.POST)
 public ResponseEntity<Void> addUser(@RequestBody User newUser){
     if(newUser != null){
       if( userdao.save(newUser) == null){
         return new ResponseEntity<Void>(HttpStatus.SERVICE_UNAVAILABLE);
       }else{
        return new ResponseEntity<Void>(HttpStatus.CREATED);
       }
     }else{
      return new ResponseEntity<Void>(HttpStatus.CONFLICT);
     }
 }
 
 @RequestMapping(value="/users/{userName}", method=RequestMethod.DELETE)
 public ResponseEntity<Void> deleteUser(@PathVariable String userName){
  User searchedUser = userdao.findByUserName(userName);
  if(searchedUser != null){
   userdao.delete(searchedUser);
   return new ResponseEntity<Void>(HttpStatus.OK);
  }else{
   return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
   
  }
  
 }

}

We defined three endpoints: for listing, adding, and deleting. For demonstration purposes, I added some sample data in /resources forlder, which is also automatically picked by Spring Boot and applied to the database on startup.

insert into users values (1, 'user1', 'john', 'doe');
insert into users values (2, 'user2', 'long', 'beard');
insert into users values (3, 'user3', 'zakaria', 'amine');


Finally, we can launch our app by simply executing the Main class :

 
@SpringBootApplication
public class SpringbootDemoApplication {

 public static void main(String[] args) {
  SpringApplication.run(SpringbootDemoApplication.class, args);
 }
}
Our Rest API is all set. If we go to /users on a browser we get:


I created a html page with some Angular Js code to test the operations. Since the page was named "index.html",  Spring Boot automatically picked up the name and defined it as a welcome page.

I will not say more on the front end part since it is not the focus of this tutorial. You can find the source code here.

Total time in building all this and deploying it: less than 10mins.

Spring Boot is new way of getting things quickly into production, and it keeps on getting better with every release.

The whole application is available here:  https://github.com/zak905/springboot-demo.git

Tuesday, April 26, 2016

Introduction to Java 8 Streams Part 2 - Parallel Streams



We have seen in the first part of this series how to use streams which are considered one of the key features of Java 8. In this post, we will walk through a particular feature of streams: Parallel streams. To give a rather simplistic definition, parallel streams involves doing the work in parallel using more resources to finish faster. They can be used by calling a magic method: parallel(). Java 8 hides all the complexity behind dividing the work and parallelizing it which relieves the developer from carring about things like threads and concurrency. However, many have reservations about using parallel streams for several reasons. Before going into the pitfalls of parallel streams, let's go through a quick example that illustrates their "good" side. Suppose we want to sum all even integers from 1 to one billion, one way of doing it using streams would be:

 static long sum = 0;
    
    public static void main(String[] args){
        
      IntStream.rangeClosed(1, 1000000000)
                .filter(e -> e % 2 == 0)
                .forEach(e -> addToSum(e));
                
    }
    
    public static void addToSum(int num){
      sum += num;
        
    }
The excution time gives:


adding paralllelization to our stream:

static long sum = 0;
    
    public static void main(String[] args){
        
      IntStream.rangeClosed(1, 1000000000)               
                .parallel()
                .filter(e -> e % 2 == 0)
                .forEach(e -> addToSum(e));
                
    }
    
    public static void addToSum(int num){
      sum += num;
        
    }

The excution time gives:

Notice that using parallel(), we have reduced the execution from 27 seconds to 18 seconds which seems like a legitimate advantage in the favor of parallel streams. Let's try and print the result sum for both cases :

Without parralel(): 250000000500000000
With parralel() (try 1): 144666330514402188
With parralel() (try 2): 146443671692846754
With parralel() (try 3): 142515120769803018


Any thoughts? We have gained on excution time, but the result is wrong, and it is not anywhere closer to the correct result. Why is that? The main reason why this occurs is that multiple threads are trying to access a shared variable in parallel. 

So think twice before using parallel stream. Because you can parallelize, it does not mean you should. Questions that the developer needs to ask before making using this construct are: is the collection/environement thread safe? is the problem large enough to be worth parralelizing? Are the resources enough? Hoping that this brief example shed light on what happens behind the curtains when using parallel(). 




Monday, April 18, 2016

Google Code Jam 2016: comments and problem solutions.



Progamming contests are a good measure of how great you are as a programmer. Besides from the broad and theoritical questions of job interviews, contests can be an accurate determinant of one's programming ability. Google Code Jam is a global contest that challenges programmers around the world to solve puzzles with different levels of difficulty. This year was my first participation, and I have to say some problems were tough. Although I did not qualify to the second round because of time consideration (out of the 27 hours given, I only programmed 12 hours),  it was a good programming experience overall.  I used Groovy for its scripting capabilities, and its dynamic typing. I advice programmers to participate in next year's edition. Here are links for two of the problems that I could solve on time.

Problem A: Counting Sheep.

Bleatrix Trotter the sheep has devised a strategy that helps her fall asleep faster. First, she picks a number N. Then she starts naming N, 2 × N, 3 × N, and so on. Whenever she names a number, she thinks about all of the digits in that number. She keeps track of which digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) she has seen at least once so far as part of any number she has named. Once she has seen each of the ten digits at least once, she will fall asleep.

Bleatrix must start with N and must always name (i + 1) × N directly after i × N. For example, suppose that Bleatrix picks N = 1692. She would count as follows:

  • N = 1692. Now she has seen the digits 1, 2, 6, and 9.
  • 2N = 3384. Now she has seen the digits 1, 2, 3, 4, 6, 8, and 9.
  • 3N = 5076. Now she has seen all ten digits, and falls asleep.

What is the last number that she will name before falling asleep? If she will count forever, print INSOMNIA instead.

Input

The first line of the input gives the number of test cases, T. T test cases follow. Each consists of one line with a single integer N, the number Bleatrix has chosen.

Output

For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the last number that Bleatrix will name before falling asleep, according to the rules described in the statement.

Limits

1 ≤ T ≤ 100.

Small dataset

0 ≤ N ≤ 200.

Large dataset

0 ≤ N ≤ 106.

Sample


Input
 

Output
 
5
0
1
2
11
1692

Case #1: INSOMNIA
Case #2: 10
Case #3: 90
Case #4: 110
Case #5: 5076


In Case #1, since 2 × 0 = 0, 3 × 0 = 0, and so on, Bleatrix will never see any digit other than 0, and so she will count forever and never fall asleep. Poor sheep!

In Case #2, Bleatrix will name 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. The 0 will be the last digit needed, and so she will fall asleep after 10.

In Case #3, Bleatrix will name 2, 4, 6... and so on. She will not see the digit 9 in any number until 90, at which point she will fall asleep. By that point, she will have already seen the digits 0, 1, 2, 3, 4, 5, 6, 7, and 8, which will have appeared for the first time in the numbers 10, 10, 2, 30, 4, 50, 6, 70, and 8, respectively.

In Case #4, Bleatrix will name 11, 22, 33, 44, 55, 66, 77, 88, 99, 110 and then fall asleep.

Case #5 is the one described in the problem statement. Note that it would only show up in the Large dataset, and not in the Small dataset.


My Solution: https://github.com/zak905/googlecodejam/blob/master/2016/Qualifying%20Round/CountingSheep.groovy


Problem B: Revenge of the Pancakes.

The Infinite House of Pancakes has just introduced a new kind of pancake! It has a happy face made of chocolate chips on one side (the "happy side"), and nothing on the other side (the "blank side").
You are the head waiter on duty, and the kitchen has just given you a stack of pancakes to serve to a customer. Like any good pancake server, you have X-ray pancake vision, and you can see whether each pancake in the stack has the happy side up or the blank side up. You think the customer will be happiest if every pancake is happy side up when you serve them.
You know the following maneuver: carefully lift up some number of pancakes (possibly all of them) from the top of the stack, flip that entire group over, and then put the group back down on top of any pancakes that you did not lift up. When flipping a group of pancakes, you flip the entire group in one motion; you do not individually flip each pancake. Formally: if we number the pancakes 1, 2, ..., N from top to bottom, you choose the top i pancakes to flip. Then, after the flip, the stack is i, i-1, ..., 2, 1, i+1, i+2, ..., N. Pancakes 1, 2, ..., i now have the opposite side up, whereas pancakes i+1, i+2, ..., N have the same side up that they had up before.
For example, let's denote the happy side as + and the blank side as -. Suppose that the stack, starting from the top, is --+-. One valid way to execute the maneuver would be to pick up the top three, flip the entire group, and put them back down on the remaining fourth pancake (which would stay where it is and remain unchanged). The new state of the stack would then be -++-. The other valid ways would be to pick up and flip the top one, the top two, or all four. It would not be valid to choose and flip the middle two or the bottom one, for example; you can only take some number off the top.
You will not serve the customer until every pancake is happy side up, but you don't want the pancakes to get cold, so you have to act fast! What is the smallest number of times you will need to execute the maneuver to get all the pancakes happy side up, if you make optimal choices?

Input

The first line of the input gives the number of test cases, T. T test cases follow. Each consists of one line with a string S, each character of which is either + (which represents a pancake that is initially happy side up) or - (which represents a pancake that is initially blank side up). The string, when read left to right, represents the stack when viewed from top to bottom.

Output

For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the minimum number of times you will need to execute the maneuver to get all the pancakes happy side up.

Limits

1 ≤ T ≤ 100.
Every character in S is either + or -.

Small dataset

1 ≤ length of S ≤ 10.

Large dataset

1 ≤ length of S ≤ 100.

Sample


Input
 

Output
 
5
-
-+
+-
+++
--+-

Case #1: 1
Case #2: 1
Case #3: 2
Case #4: 0
Case #5: 3

In Case #1, you only need to execute the maneuver once, flipping the first (and only) pancake.
In Case #2, you only need to execute the maneuver once, flipping only the first pancake.
In Case #3, you must execute the maneuver twice. One optimal solution is to flip only the first pancake, changing the stack to --, and then flip both pancakes, changing the stack to ++. Notice that you cannot just flip the bottom pancake individually to get a one-move solution; every time you execute the maneuver, you must select a stack starting from the top.
In Case #4, all of the pancakes are already happy side up, so there is no need to do anything.
In Case #5, one valid solution is to first flip the entire stack of pancakes to get +-++, then flip the top pancake to get --++, then finally flip the top two pancakes to get ++++.
My Solution: https://github.com/zak905/googlecodejam/blob/master/2016/Qualifying%20Round/RevengeOfPancakes.groovy
Contest main page: http://code.google.com/codejam/

Tuesday, April 5, 2016

Introduction to testing with Mockito


Mocking helps alleviate the burden of initiliazing and setting up classes prior to the start of a test. While using a mocking framework is not something indispensable, mocking promotes modularity and can make the life of a developer much easier. There are several mocking Java frameworks that can be coupled with a test framework. Some of the well know ones are: Mockito, EasyMock, and JMockit. In this tutorial, we will go through some basic use cases of mocking. We will be using Mockito and JUnit for demonstration purposes.

Mocking objects and method calls


Account account = Mockito.mock(Account.class);

when(account.getUsername()).thenReturn("opencode");
when(account.getPassword()).thenReturn("password1");

//Test successful
assertEquals(account.getUsername(), "opencode");
assertEquals(account.getPassword(), "password1");

//.....

//Lists can be mocked as well using @Mock
@Mock
List<Profile> profileList;

Profile profile1 = Mockito.mock(Profile.class);
Profile profile2 = Mockito.mock(Profile.class);
  
when(profile1.getDescription()).thenReturn("profile1");
when(profile2.getDescription()).thenReturn("profile2");
  
  
when(profileList.get(0)).thenReturn(profile1);
when(profileList.get(1)).thenReturn(profile2);

//Test successful
assertEquals(profileList.get(0).getDescription(), "profile1");
assertEquals(profileList.get(1).getDescription(), "profile2");


Verifying method invocation and the frequency of invocation


//...

System.out.println(account.getUsername());
//verfies that getUsername() is called -- success 
 verify(account).getUsername();

 //verfies that getUsername() is called twice -- failed
 verify(account, times(2)).getUsername();

         

Testing exceptions


//Junit 4.7 or higher
@Rule
public ExpectedException exception = ExpectedException.none();

@Mock
List<Profile> profileList;

when(profileList.get(2)).thenThrow(NullPointerException.class);

//.....
            
 @Test 
public void testException(){
   //result -- success
     exception.expect(NullPointerException.class);
     profileList.get(2);
     }


There are off course more advanced possiblities offered by Mockito, and other frameworks as well.
  

Saturday, February 20, 2016

Introduction to Java Lambda expressions


Lambdas are considered one of the major changes introduced to the Java language constructs since its release. Sooner or later, Java developers will need to get accustomed to using and manipulating lambdas. To put it a simple way, Lambda expressions can be refered to as a method without a name that can be declared anywhere. We know that the essence of Java is object orientation, so normally methods can only live inside an object or an interface. Lambdas were introduced to deal with this shortcoming. They add a flavor of functional programming to one of the most traditional object oriented languages.
In this tutorial, we will go through some use cases where lambda expressions may be useful.

A quick reminder of the lambdas syntax:

Arguments declaration                         Method body
(a, b, c, ....)                             ->         {expressions;...;...;}


Case 1: Implementing an interface with one method (Functional interface)


 public interface Bank {
  double convertAmountFromEuroToDollar(double amount);
 }

     //.....
  Bank bank = (b) ->   b * 1.11;
  
  System.out.println(bank.convertAmountFromEuroToDollar(10));
Result:
 11.100000000000001

Case 2: UI events

  JButton button = new JButton();
  button.addActionListener(
    
    (e) -> {System.out.println("Action performed");
    
     });

Case 3: Streams

  List cars = Arrays.asList("Mercedes","Volvo","Volswagen","Audi","Peugeot");
  cars.stream().
  filter(c -> c.startsWith("V"))
  .forEach(c -> System.out.println(c));
Result:

Volvo
Volswagen

Case 4: Using Java provided functional interfaces


   
 //Takes two String arguments and return one Boolean result
  BiFunction<String, String, Boolean> checkAnagram = (e1, e2) -> { 
      e1.toLowerCase(); e2.toLowerCase();
      char[] e1Chars = e1.toCharArray(); char[] e2Chars = e2.toCharArray(); 
      Arrays.sort(e1Chars);
      Arrays.sort(e2Chars);
     return String.valueOf(e1Chars).equals(String.valueOf(e2Chars));
   };
 
     //Takes one String arguments and return one Boolean result 
    Function<String, Boolean> checkPalindrome = (p) -> { 
 char[] toChar = p.toCharArray();
     CharBuffer buffer = CharBuffer.allocate(toChar.length);
  for(int i = toChar.length - 1; i >= 0; i--)
        buffer.put(toChar[i]);
   
           return p.equals(String.valueOf(buffer.array())); 
  };
  

  System.out.println(checkAnagram.apply("test", "estt"));
  System.out.println(checkPalindrome.apply("rotator"));

Result:

true
true
Full code available at: https://github.com/zak905/java8features/tree/master/src/opencode/java8features/lambdas

 Interesting reads:
http://zeroturnaround.com/rebellabs/java-8-best-practices-cheat-sheet/
http://viralpatel.net/blogs/lambda-expressions-java-tutorial/

Tuesday, February 9, 2016

Unit Testing a Rest API using Spring Test




 After you have designed your Rest API and implemented it successfully, you need to test it. Testing a Rest Api is not easy because of the application context. By default, to be able to run tests, the Spring MVC container needs to be launched as it contains all of the components that the application needs to run properly ( request mapping, exception handling, ...). However, launching the container will take a considerable amount of time slowing down tests. Usually, tests need to run quicker than the application.
To solve this issue, Spring test provides the speed of an out of container context with only the needed infrastructure of Spring MVC. All the infrastructure that we need to run our tests is bootstrapped in an out of container process. That is to say, we get a standalone web application that does not need to run inside a servlet, which allows unit and integration tests to run quicker. In this tutorial, we will go through how to use Spring Test for unit testing a Rest API.

Requirements:

Application buit previously
Eclipse, Maven
Spring dependencies: pom.xml here.


We have the following end points that we want to unit test:

POST: /person
GET: /person/{id}
GET: /person/{id}/profile
GET: /person/{id}/account


Our test class looks like:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:beans.xml"})
public class PersonControllerUnitTest {

  @Autowired
   private volatile WebApplicationContext webApplicationContext;

    @Before
    public void before() {
 this.mockMvc = webAppContextSetup(this.webApplicationContext).build();    
      }
     
     @Test
     public void createPersonTest() throws Exception{
  this.mockMvc.perform(post("/person"))
   .andExpect(status().isCreated());
      }
     
     @Test
    public void getPerson() throws Exception{
 this.mockMvc.perform(get("/person/{id}", 1))
 .andExpect(status().isOk())
 .andExpect(content().contentType("application/json;charset=UTF-8"))
        .andExpect(jsonPath("$.firstname").value("John"));
      }
  
     @Test
     public void getProfile() throws  Exception{
        this.mockMvc.perform(get("/person/{id}/profile", 1))
 .andExpect(status().isOk())
 .andExpect(content().contentType("application/json;charset=UTF-8"))
 .andExpect(jsonPath("$.description").value("Profile description"));
      }
  
     @Test
    public void getAccount() throws Exception{
     this.mockMvc.perform(get("/person/{id}/account", 1))
     .andExpect(status().isOk())
     .andExpect(content().contentType("application/json;charset=UTF-8"))
     .andExpect(jsonPath("$.username").value("johnk"));
     }
}


Before running tests, we have configured the application context and initialized a MockMvc object that mimics a Spring MVC infrastructure. To test a Rest API operation, we made assertions on the return HTTP status, the content type, and also on the data returned.




Full example at: https://github.com/zak905/rest-spring-example




Wednesday, January 27, 2016

Abstract Factory Design Pattern


Abstract Factory pattern can come really handy when creating sets of related objects. It allows developpers to take advantage of two of the key features of Object Oriented Design to create objects: Polymorphism and Abstraction. Polymorphism is the ability of an object to take many forms. it's done through inheritance. For example, charachteristics of a diesel engine are different from a gasoline engine, but both of them have common functionality such as start, and stop. Abstraction allows hiding functionality of an object. It allows the separation of the implementation from the object itself. It's provided though interfaces and abstract classes. In this tutorial, we will go through how to implement the abstract factory design pattern in Java. Abstract Factory allows the creation of different factories that will be later used to create objects. In other terms, Abstract Factory can be refered to as a Factory of Factories.

Suppose we want to assemble a car with an Engine, and a Gear. an Engine can be either Diesel or Gasoline and a Gear can be either Manual or Automatic.  A car needs an engine and a gear to be assembled. It does not care about what type of Engine and Gear it is using. We will start first of all by designing our abstract engine and gear, and then extend them to define our specific types.

Engine.java
public abstract class Engine {
 
 public abstract void buildEngine();
 public abstract void testEngine();

}

Gear.java
public abstract class Gear {
 
 public abstract void buildGear();
 public abstract void testGear();

}
Now we are going to extend Engine to create DieselEngine and GasolineEngine:
DieselEngine.java
public class DieselEngine extends Engine {

 @Override
 public void buildEngine() {
  System.out.println("Building Diesel Engine");
  
 }

 @Override
 public void testEngine() {
  System.out.println("Testing Diesel Engine");
  
 }

}
GasolineEngine.java
public class GasolineEngine extends Engine {

 @Override
 public void buildEngine() {
  System.out.println("Building Gasoline Engine");
  
 }

 @Override
 public void testEngine() {
  System.out.println("Testing Gasoline Engine");
  
 }

}
We need to extend Gear as well to create ManualGear and AutomaticGear:
AutomaticGear.java
public class AutomaticGear extends Gear {

 @Override
 public void buildGear() {
  System.out.println("Attaching Automatic Gear");
  
 }

 @Override
 public void testGear() {
  System.out.println("Testing Automatic Gear");
  
 }

}
ManualGear.java
public class ManualGear extends Gear {

 @Override
 public void buildGear() {
  System.out.println("Attaching Manual Gear");
  
 }

 @Override
 public void testGear() {
  System.out.println("Testing Manual Gear");
  
 }

}
Our car object needs an Engine and a Gear regardless of whether the engine is diesel or automatic and whether the gear is manual or automatic:
Car.java
public class Car {
 
 Engine engine;
 Gear gear;
 
 public Car(Engine engine, Gear gear){
  this.engine = engine;
  this.gear = gear;
 }
 
 public void assemble(){
  System.out.println("-----------Starting car assembly");
  engine.buildEngine();
  gear.buildGear();
  System.out.println("-----------car assembly done");
 }
 
 public void test(){
  System.out.println("-----------Starting car tests");
  engine.testEngine();
  gear.testGear();
  System.out.println("-----------car tests done");
  
 }

}
Now, we need a method to create "Engines" and "Gears". We can go ahead and just instantiate the objects using their constructors, but there is a more classy way to do it. Since our objects are related, we can use one factory to generate them. We need a flexible factory that can generate both types. In other words, we need an abstract form of a factory that can be extended/implemented.
AbstractFactory.java
public abstract class AbstractFactory {
 abstract Engine getEngine(String engineType);
 abstract Gear getGear(String gearType); 
}
We can extend our factories as needed :
EngineFactory.java
public class EngineFactory extends AbstractFactory {

 @Override
 Engine getEngine(String engineType) {
  
  
  if(engineType.equals("Diesel")){
   
   return new DieselEngine();
   
  }else if(engineType.equals("Gasoline")){
   return new GasolineEngine();
  }
  return null;
 }

 @Override
 Gear getGear(String gearType) {
  //Not needed for Engine
  return null;
 }

}
GearFactory.java
public class GearFactory extends AbstractFactory {
 @Override
 Engine getEngine(String engineType) {
  //Not needed
  return null;
 }

 @Override
 Gear getGear(String gearType) {
  // TODO Auto-generated method stub
  if(gearType.equals("Manual")){
   return new ManualGear();
  }else if(gearType.equals("Automatic")){
   return new AutomaticGear();
  }
  return null;
 }

}
Finally, we need a factory producer that will create the needed factory depending on the class of the object: Gear or Engine.
FactoryProducer.java
public class FactoryProducer {
 public static AbstractFactory getFactory(String factoryType){
  if(factoryType.equals("Engine")){
   return new EngineFactory();
  }else if (factoryType.equals("Gear")){
   return new GearFactory();
  }
  return null;
 }
}
To test our Abstract Factory pattern we can do something like :
public class Test {
 public static void main(String[] args) {  
  AbstractFactory engineFactory = FactoryProducer.getFactory("Engine");
  AbstractFactory gearFactory = FactoryProducer.getFactory("Gear");
  
  Engine dieselEngine = engineFactory.getEngine("Diesel");
  Engine gasolineEngine = engineFactory.getEngine("Gasoline");
  
  Gear manualGear = gearFactory.getGear("Manual");
  Gear automaticGear = gearFactory.getGear("Automatic");
  
  Car car1 = new Car(dieselEngine, manualGear);
  Car car2 = new Car(gasolineEngine, automaticGear);
  
  car1.assemble();
  car1.test();
  
  car2.assemble();
  car2.test();

 }

}
Result:
As you can see, we have abstracted out Engine and Gear using a Factory and hidden their implementation from Car. Car only executes their methods.

Full example at: https://github.com/zak905/java8features/tree/master/src/opencode/designpatterns/abstractfactory

Sunday, January 10, 2016

Implementing Hypermedia (Hateoas) for a Rest Application in Spring


Hypermedia (Hateoas) is considered not only a good practice but also an important aspect of Rest APIs design. It allows better decoupling of resources and subresources and better optimization of the data sent by the server. Suppose we have a resource with a long list of subresources, it would be overwhelming to have all the data sent in one request, while the user only needs data in couple of fields. Hypermedia allows to add links to subresources to the resource. In this tutorial, we will demonstrate how to implement Hatoeas in a Spring Rest based application.

Requirements:
Spring (MVC, Core, Hateoas,...), full list of dependencies can be found here.
Eclipse or any other IDE
Jetty plugin


We have already covered in a previous tutorial how to create a Rest application in Spring, so I suppose you already have that part covered. Suppose we have an object like this:

public class Person {
 private String firstname;
 private String lastName;
 private int age;
 private String departement;
 private Account account;
 private Profile profile;
 
 public Person(){
  
  
 }
 
 /**
  * @return the firstname
  */
 public String getFirstname() {
  return firstname;
 }
 /**
  * @param firstname the firstname to set
  */
 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }
 /**
  * @return the lastName
  */
 public String getLastName() {
  return lastName;
 }


 /**
  * @param lastName the lastName to set
  */
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }


 /**
  * @return the age
  */
 public int getAge() {
  return age;
 }

 /**
  * @param age the age to set
  */
 public void setAge(int age) {
  this.age = age;
 }

 /**
  * @return the departement
  */
 public String getDepartement() {
  return departement;
 }

 /**
  * @param departement the departement to set
  */
 public void setDepartement(String departement) {
  this.departement = departement;
 }

 public Account getAccount() {
  return account;
 }

 public void setAccount(Account account) {
  this.account = account;
 }

 public Profile getProfile() {
  return profile;
 }

 public void setProfile(Profile profile) {
  this.profile = profile;
 }
Notice that person has a Account and Profile objects as fields (or subresource):

public class Account {
 
 private String username;
 private String password;
 
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 

}
public class Profile {
 
 private String description;
 private String interests;
 private String activities;
 
 
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
 public String getInterests() {
  return interests;
 }
 public void setInterests(String interests) {
  this.interests = interests;
 }
 public String getActivities() {
  return activities;
 }
 public void setActivities(String activities) {
  this.activities = activities;
 }
}
Without using Hateoas the Rest representation of our resource is:

You can notice that we have both the data of the profile and the account sent with the Request. So, we need to change these two subresources to links and add the links to the controller.

First, our main resource needs to extend ResourceSupport which used for setting links in a resource object.

public class Person extends ResourceSupport

Also we are going to ignore both the profile and the account subresources so that they are not sent with the resource using Jackson's @JsonIgnore. 


@JsonIgnore
public Profile getProfile() {
 return profile;
 }

@JsonIgnore
public Account getAccount() {
 return account;
 }
We need also to modify our controller accordingly:

@Controller
@RequestMapping("/person")
public class PersonController {
 
 @RequestMapping(value="{id}", method= RequestMethod.GET)
 public @ResponseBody Person getPerson(@PathVariable Integer id){
  ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
  PersonRepository repository = context.getBean(PersonRepository.class);
  
  Person person = repository.retrieve(id);
  
  person.add(linkTo(PersonController.class).slash(id).withSelfRel());
  person.add(linkTo(PersonController.class).slash(id).slash("account").withRel("account"));
  person.add(linkTo(PersonController.class).slash(id).slash("profile").withRel("profile"));
 
  return person;
 }
 
 @RequestMapping(value="{id}/profile", method=RequestMethod.GET)
 public @ResponseBody Profile getProfile(@PathVariable Integer id){
  ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
  PersonRepository repository = context.getBean(PersonRepository.class);
  
  Person person = repository.retrieve(id);
  
 
  return person.getProfile();
  
 }
 
 @RequestMapping(value="{id}/account", method=RequestMethod.GET)
 public @ResponseBody Account getAccount(@PathVariable Integer id){
  
  ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
  PersonRepository repository = context.getBean(PersonRepository.class);
  
  Person person = repository.retrieve(id);
  
 
  return person.getAccount();
 }

You can notice that we have added three links to the Person's resource in the method getPerson() , one that links to self, one for Account, and one for Profile. The reason we have added a link of the resource to itself is that, by convention, the link to self provides more detailed data about the object. But in our case, the self link references the same thing as the current resource. Now, if we request our resource in http://localhost:8080/person/2, the sent data will look something like:


Now if you go to the link of Person's account: http://localhost:8080/person/2/account, the sent data will be only for the account:


Full example can be found here: https://github.com/zak905/rest-spring-example