Saturday, December 26, 2015

Builder Design pattern


The builder pattern is another useful pattern that helps create complex objects. While using it is not a must, it allows developpers to reduce the complexity while instantiating an object with too many fields. It is also used to make object instantiation code more readable. In this tutorial, we will go through an example of how to implement this pattern in Java.

Suppose we have the following object:
 public class Profile {

     private String salutation;
     private String occupation;
     private String name;
     private String location;
     private String description;
     private String eMail;
     private String pictureUrl;
     private List hobbies;
     private String birthday;
   
     public Profile(String salutation, String name, String position, String location, String description, String eMail, String pictureUrl, List hobbies, String birthday){
         this.name = name;
         this.occupation = position;
         this.location = location;
         this.description = description;
         this.eMail = eMail;
         this.salutation = salutation;
         this.pictureUrl = pictureUrl;
         this.hobbies = hobbies;
         this.birthday = birthday;
     }
   
     public String getName() {
         return name;
     }

     public void setName(String name) {
         this.name = name;
     }

     public String getPosition() {
         return occupation;
     }

     public void setPosition(String position) {
         this.occupation = position;
     }

     public String getLocation() {
         return location;
     }

     public void setLocation(String location) {
         this.location = location;
     }

     public String getDescription() {
         return description;
     }
     public void setDescription(String description) {
         this.description = description;
     }

     public String geteMail() {
         return eMail;
     }

     public void seteMail(String eMail) {
         this.eMail = eMail;
     }

     public String getSalutation() {
         return salutation;
     }

     public void setSalutation(String salutation) {
         this.salutation = salutation;
     }
  public String getPictureUrl() {
   return pictureUrl;
  }
  public void setPictureUrl(String pictureUrl) {
   this.pictureUrl = pictureUrl;
  }
  public List getHobbies() {
   return hobbies;
  }
  public void setHobbies(List hobbies) {
   this.hobbies = hobbies;
  }
  public String getBirthday() {
   return birthday;
  }
  public void setBirthday(String birthday) {
   this.birthday = birthday;
  }
       
 
   
 }


If we want to instantiate a Profile object, one way to do it is: 

Profile profile = new Profile("Mr.", "Developper", "Dummy User", "France", "Cool Profile", "dummy@test.com", "server/profile.png", Arrays.asList("technology","soccer", "blogging") , "26/05/1990");

Notice the important number of parameters used by Profile constructor. While it is 100% ok to build objects this way, it can be confusing for developper figuring out which parameter is for which property. To simplify the creation of Profile, we can use a builder such as: 
public class ProfileBuilder {
   private String salutation;
     private String occupation;
     private String name;
     private String location;
     private String description;
     private String eMail;
     private String pictureUrl;
     private List<String> hobbies;
     private String birthday;
     
     public ProfileBuilder(){
      
      
     }
     
     
     public ProfileBuilder salutation(String salutation){
      this.salutation = salutation;
      
      return this;
     }
     
    public ProfileBuilder occupation(String occupation){
     this.occupation = occupation;
      return this;
     }
    
    public ProfileBuilder name(String name){
     this.name = name;
     return this;
    }
    
    public ProfileBuilder location(String location){
     this.location = location;
     return this;
    }
    
    public ProfileBuilder description(String description){
     this.description = description;
     return this;
    }
    
    public ProfileBuilder eMail(String eMail){
     this.eMail = eMail;
     return this;
    }
    
    public ProfileBuilder pictureUrl(String pictureUrl){
     this.pictureUrl = pictureUrl;
     return this;
    }
    
    public ProfileBuilder hobbies(List hobbies){
     this.hobbies = hobbies;
     return this;
    }
    
    public ProfileBuilder birthday(String birthday){
     this.birthday = birthday;
     return this;
    }
    
    
    public Profile build(){
     
     return new Profile(salutation, occupation, name, location, description, eMail, pictureUrl, hobbies, birthday);
    }

}

We need to adjust the profile constructor accordingly:
     public Profile(ProfileBuilder builder){
         this.name = builder.name;
         this.occupation = builder.occupation;
         this.location = builder.location;
         this.description = builder.description;
         this.eMail = builder.eMail;
         this.salutation = builder.salutation;
         this.pictureUrl = builder.pictureUrl;
         this.hobbies = builder.hobbies;
         this.birthday = builder.birthday;
     }

Now we can instantiate a Profile this way:
Profile profile = new ProfileBuilder()
                         .salutation("Mr.")
                         .occupation("Developper")
                         .name("Dummy User")
                         .location("France")
                         .description("Cool Profile")
                         .eMail("dummy@test.com")
                         .pictureUrl("server/profile.png")
                         .hobbies(Arrays.asList("technology","soccer", "blogging"))
                         .birthday("26/05/1990")
                          .build();
                         
  



Saturday, December 12, 2015

Observer (Pub/Sub) Design Pattern


The observer pattern is among the most used object oriented design patterns. It allows the designer to automate fields updates when there is a dependency between objects. Advocates of the observer pattern have identified many benefits from using it such as:
- promoting loose coupling
- efficiency
- flexibility: you can add an observer to a subject  any time

In this tutorial, we will go through an example of the Observer pattern in Java. As the name Publisher/Subscriber may suggest, there are two entites: a publisher and a subscriber, or an observer and a subject.

Example: Suppose we want to monitor changes in the car engine oil level. There are several units that wants to get updated about these changes: the Engine itsellf, the Dashboard, and the Cooling Unit. We want these parts to be automatically updated on any change without having to intervene manually.

First of all, let's get our interfaces up :

public interface Observer {
 public void update(int oilLevel);
}
public interface Subject {
 public void register(Observer o);
 public void unregister(Observer o);
 public void notifyObserver();
}


Then, as you may have dedcuted from the example, the engine oil level is the Subject. We will call it EngineOil.

public class EngineOil implements Subject {
 
 List<Observer> observers;
 
 int oilLevel;

 
 public EngineOil(){
 observers = new ArrayList();
 }
 public void register(Observer o) {
  // TODO Auto-generated method stub
  observers.add(o);
 }
 public void unregister(Observer o) {
  // TODO Auto-generated method stub
  int index = observers.indexOf(o);
  observers.remove(index);
 }
 public void notifyObserver() {
  for(Observer observer:observers){
   observer.update(oilLevel);
  }
 }
 public void setLiquidLevel(int oilLevel){
  this.oilLevel = oilLevel;
  notifyObserver();
 }
 
 public int getLiquidLevel(){
  return this.oilLevel;
 }
}


The Observers in our case are: CarDashboard, CarEngine, Cooling Unit.


public class CarDashboard implements Observer {


 int oilLevel;
 
 public CarDashboard(int oilLevel){
  this.oilLevel = oilLevel;
 }
 

 public void update(int oilLevel) {
  // TODO Auto-generated method stub
  this.oilLevel = oilLevel;
  System.out.println(this.getClass().getSimpleName() + ": oil level changed to " + oilLevel);
 }


public class CarEngine implements Observer {
 int oilLevel;
 public CarEngine(int oilLevel){
  this.oilLevel = oilLevel;
 }
 
 public void update(int oilLevel){
  this.oilLevel = oilLevel;
  System.out.println(this.getClass().getSimpleName() + ": oil level changed to " + oilLevel);
 }

}


public class CoolingUnit implements Observer {
        int oilLevel;

 public CoolingUnit(int oilLevel){
  this.oilLevel = oilLevel;
 }
 
 public void update(int oilLevel){
  this.oilLevel = oilLevel;
  System.out.println(this.getClass().getSimpleName() + ": oil level changed to " + oilLevel);
 }

}



We can now test our pattern:

public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  EngineOil oil = new EngineOil();
  //No observer yet
  oil.setLiquidLevel(50);
  
  //Adding new observers
  CarEngine engine = new CarEngine(oil.getLiquidLevel());
  oil.register(engine);
  
  CoolingUnit unit = new CoolingUnit(oil.getLiquidLevel());
  oil.register(unit);
  
  CarDashboard board = new CarDashboard(oil.getLiquidLevel());
  oil.register(board);
  
  //changing the level
  
  oil.setLiquidLevel(45);
  oil.setLiquidLevel(25);
  oil.setLiquidLevel(20);

 }

Result:



Sunday, November 29, 2015

Drag and Drop using GWT



Drag and drop can be an important feature in web apps. It allows adding a human touch to UIs. Drag and drag can be easily implemented using Html5 and Javascript, and also using other frameworks such as jquery. For Java web development, GWT provides a good solution. GWT have added a native feature to enable drag and drop for widgets and components. We are going to walk through it in this tutorial.

As the name implies, drag and drop has two sides: the element to be dragged, and the element to be dropped on.

To enable drag for any widget or component in GWT, we have to use the addDragHandler method. For example:
Image image = new Image("images/car.png");
image.addDragStartHandler(new DragStartHandler(){
   @Override
 public void onDragStart(DragStartEvent event) {
       // required: data to be transferred to the drop handler
              event.setData("text", image.getElement().getInnerHTML()); 
   }});
Not all elements have the addDragHandler by default. If an element is not implementing the DragHandler interface, the developper needs to add the handler to the DOM handlers:

        

image.addDomHandler(new DragStartHandler(){
     @Override
     public void onDragStart(DragStartEvent event) {
         // required: data to be transferred to the drop handler
   event.setData("text", image.getElement().getInnerHTML());
    }}, DragStartEvent.getType());
For the drop, we need to implement two handlers: DropHandler and DragOverHandler. Suppose we want to use a FlowPanel as a drop target:

          

FlowPanel target = new FlowPanel();

target.addDomHandler(new DragOverHandler() {
           @Override
           public void onDragOver(DragOverEvent event) {
               //Do something like changing background
       }
   }, DragOverEvent.getType());
   
    target.addDomHandler(new DropHandler() {
      @Override
      public void onDrop(DropEvent event) {
          // required
       event.preventDefault();
        
          // get the data out of the event
          String data = event.getData("text");
          Image image = new Image(data);
   
      }
  }, DropEvent.getType());
That's it. Now we can drag the Image into the FlowPanel.



There are other GWT libraries that implements Drag and Drop out of the box such as: 

It is advised for developpers to roll their own drag and drop in order not to depend on any implementation. 

Friday, November 20, 2015

Paris Open Source Summit Review


I have had the chance to hop into the the Paris Open Source Summit, and I wanted to share my experience. Some of the big players like RedHat, OpenSuse, Microsoft,.. were present which seems like a good reason to go there ,but after attending couple of seminars, it seems like most of the presentations were oriented towards "commercial" open source. For a java developper like myself, I was expecting more code talks. The few things that caught my interest:

        - Storage and Network features in the new Docker 1.9 version released in the 3rd of November:
Docker now gives its containers the possibility of attaching storage and of being accessible through the network. According to their blog, Docker Engine 1.9 includes a completely redesigned volume system that makes them much easier to use and brings plugins to the forefront. Storage can be manipulated using "docker volume" command. Network was introduced as an experimental feature since last June, and is now in the stable release of Docker Engine and ready to use in production.

- A demonstration of Salt, which is a configuration/build automation tool like Puppet and Chef.


- A demonstration of OpenID Connect which is an identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.

Friday, November 13, 2015

Custom form validation in Spring



Validation is an important step in handling forms which is one of the important aspects of building a web application. Spring MVC allow form validation in two different ways:
- By using annotations( using javax and Hibernate validators)
- Without annotation ( by implementing Validator interface)

In this tutorial, we will go through the second method which allows more customization of rules. 

Requirements:
- Eclipse
- Maven
- Spring MVC
- Jetty for testing the application( or any other web server of your choice)

First of all, we are going to create the application skelton by chosing: maven-archetype-webapp. 

  
We are going to use our usual PoJo:
public class Person {

 private String firstname;
 
 private String lastName;

 private int age;
 
 private String departement;
 
 
 /**
  * @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;
 }
 
}

Let's suppose we need  a form to add a new person to the database. We can divide our view layer into two views: one for inputing the data (index.jsp), and the second one for confirmation ( add.jsp).

index.jsp


Notice that we have used Spring form tag instead of HTML regular form tag because we want to bind the form data to our Person object. Also, the form tag has a pre defined error tag that allows displaying errors on the page if any. 

Now we can create our validator. The rules that we are going to implement are as follow: 

- No field must be empty
- age must be an integer between 18 and 120

To create a custom validator, we need to implement Spring Validator interface. 

@Component
public class PersonValidator implements Validator {

 public boolean supports(Class arg0) {
  // TODO Auto-generated method stub
  return Person.class.equals(arg0);
 }


 public void validate(Object object, Errors errors) {
  Person person = (Person)object;
  
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstname", "person.firstname.empty");
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "person.lastName.empty");
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "person.age.empty");
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "departement", "person.departement.empty");
  
  if(person.getAge() < 18 || person.getAge() > 120){
   errors.rejectValue("age", "person.age.notValid");
  }
 }

}


We used @component because we want to use @autowired on our validator when we instantiate it from the controller. Notice also, that we used some error messages (person.firstname.empty,person.lastName.empty,...) that we will configure later. ValidationUtils will look for these message in the application context, so we have to make sure that they are available, otherwise Spring will throw an exception on form submission. The next step is building our controller:

@Controller
public class FormController {
 
 @Autowired
 PersonValidator personValidator;
 
  @InitBinder
     private void initBinder(WebDataBinder binder) {
         binder.setValidator(personValidator);
     }
  
 @RequestMapping(value="/", method = RequestMethod.GET)
 public String displayForm(Map model){
  Person person = new Person();
  model.put("person", person);
  return "index";
 }
 
 @RequestMapping(value="/add", method = RequestMethod.POST)
 public String submitForm(@Validated @ModelAttribute("person") Person person,
            BindingResult result, Map model){
  
  
  if(result.hasErrors()){
   return "index";
  }
  return "add";
 }

}

We have used @Initbinder to set our form validator. @Initbinder is used in general for populating command and form object arguments of annotated handler methods.

Finally we need to add our error messages and configure our beans:
File: validation.properties

person.firstname.empty=First name must not be empty
person.lastName.empty=Last name must not be empty
person.age.empty=age must not be empty
person.age.notValid=age must be between 18 and 120
person.departement.empty=departement must not be empty
typeMismatch.int=age must be a number.

We have added typeMismatch.int to override Spring Message for type mismatch ( integer parsing exception) which displays a long exception message that is not suited to display in a web page.

Our bean configuration file "mvc-dispatcher-servlet.xml":



our file structure looks like:



we can run our application by typing "mvn jetty:run" in eclipse or command line.

if we click add without filling in the right values, we get:


otherwise;




Full example at: https://github.com/zak905/springformvalidation

Saturday, October 31, 2015

Consuming Rest Api data using Angular Js



Angular looks like a promising framework for developping single page applications. Provided that you have the back-end ready, you can get the front side up and running very quickly using Angular and couple of other helper frameworks. In this tutorial, we will go through how to consume data from any Rest API using Angular. We will make use of the application built in the "How to create a Restful application using Spring" tutorial.

Requirements:

  - Sample Rest App
  - Angular


Our sample app provides a list of records in JSON format as show below:

[{

    "firstname": "Zakaria",

    "lastName": "Amine",

    "age": 26,

    "departement": "Accounting"

}, {

    "firstname": "John",

    "lastName": "K.",

    "age": 30,

    "departement": "IT"

}, {

    "firstname": "M.",

    "lastName": "Ibrahim",

    "age": 35,

    "departement": "HR"

}]


Our front end application has the following structure:

- App
       index.html
     - script
           app.js

First of all, we need to configure our controller. Following Angular best practices, the configuration script is written in a separate file under script/app.js. Our file looks like:

angular.module('restExample', [])
.controller('personsCtrl', function($scope, $http) {
    $http.get("http://localhost:8080/person")
    .success(function(data, status, headers, config) {$scope.persons = data;});

});


Literally, we have told angular to get the data from the "http://localhost:8080/person" end-point and put it in the scope which will be used to retrieve the data.
Now we can build our html page:



 Result:


Important: you may need to disable CORS filtering on your web server to be able to run the example. If you are using Jetty, as I did in this example, adding this to web.xml does the trick:



Useful resources:
http://www.w3schools.com/angular/angular_http.asp
https://spring.io/guides/gs/consuming-rest-angularjs/


Tuesday, October 20, 2015

Customized CellTable Header in GWT



GWT CellTable provides almost all what a developper wants from a table: paging, sorting, data binding,..etc. However, customizing the header/footer is not provided out of the box, and there is only few resources online that describes how. In this tutorial, we will go through how to customize the CellTable header with components such as buttons and textfields, and also how to change the span of header cells. same thing applies to footers.

Requirements:
Eclipse with GWT plugin

First of all, lets create a Cell table with some sample data. We are going to use a DTO such as:
public class Period {
	
	private String date;
	
	private String remarks;
	
	
	public Period(String date, String remarks){
		this.setDate(date);
		this.setRemarks(remarks);
	}


	/**
	 * @return the date
	 */
	public String getDate() {
		return date;
	}


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


	/**
	 * @return the remarks
	 */
	public String getRemarks() {
		return remarks;
	}


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

}
We can then create our table in the entry point class:


public class MainPage implements EntryPoint {
	

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		 final CellTable<Period> table = new CellTable<Period>();
		    
		    List<Period> periods = new ArrayList<Period>();
		    periods.add(new Period("2006 / 04 / 06 ", "Hiring 3 developpers"));
		    periods.add(new Period("2011 / 08 / 05", "Project Kick off"));
		    periods.add(new Period("2010 / 02 / 04",  "1st milestone due"));
		    periods.add(new Period("2014 / 11 / 17",  "Three test"));
		    periods.add(new Period("2015 / 12 / 26", "another test"));
		    
		    TextColumn<Period> commentsColumn = new TextColumn<Period>(){
				@Override
				public String getValue(Period object) {
					return object.getRemarks();
				}
		    };
		    
		    TextColumn<Period> datesColumn = new TextColumn<Period>(){
				@Override
				public String getValue(Period object) {
					return object.getDate().toString();
				}
		    };
		    
		    table.addColumn(commentsColumn, "Comments");
		    table.addColumn(datesColumn, "Dates");
		    
		    table.setRowData(periods);
		    
		    RootPanel.get("celltable").add(table);
	}
Our table now looks like:



Suppose we need to customize the header ( thead in HTML terms) by adding two rows: the first spans over two cells and has a button, and the second one has two cells one with a textfield and the other one with a list. To customize a CellTable header, we need to extend the abstract class  AbstractHeaderOrFooterBuilder


public class MyCustomHeaderBuilder extends AbstractHeaderOrFooterBuilder<Period> {

    public MyCustomHeaderBuilder(AbstractCellTable<Period> table,
			boolean isFooter) {
		super(table, isFooter);
		// TODO Auto-generated constructor stub
	}

    @Override
    public boolean buildHeaderOrFooterImpl() {
		TableRowBuilder row = startRow();
		TableCellBuilder th = row.startTH().colSpan(2);
		DivBuilder div = th.startDiv();
		
		Button button = new Button("Option");
		TextBox field = new TextBox();
		ListBox list = new ListBox();
		list.addItem("item 1");
		list.addItem("item 2");
		list.addItem("item 3");
		 
		button.getElement().setId("headerButton");
		 div.html(SafeHtmlUtils.fromTrustedString("Period "+ button.getElement()));
		 
		 div.end();
		 th.endTH();
		 row.endTR();
		 
		 row.startTR();
		 th = row.startTH();
			div = th.startDiv();
			 
			 div.html(SafeHtmlUtils.fromTrustedString("Comment" + field.getElement()));
			 
			 div.end();
			 th.endTH();
		 
		 th = row.startTH();
			div = th.startDiv();
			
			 div.html(SafeHtmlUtils.fromTrustedString("Date " + list.getElement()));
			 
			 div.end();
			 th.endTH();
		 row.endTR();
		
      return true;
    }
  }
Finally, we need to set our new header builder in the cell table we created:

table.setHeaderBuilder(new MyCustomHeaderBuilder(table, false));
Result:


Full example code at: https://github.com/zak905/customgwtcelltableheader

Sunday, October 11, 2015

Generating JSON using Jackson


JSON is the number one format when it comes to exchanging data over the Web. In this tutorial, we will go through how to generate, or serialize, JSON content, using Jackson library.

First of all, there are two different ways of generating JSON with Jackson:
- by mapping an object
- Using a stream

Let's try out both of them.

The maven dependency for Jackson is :



We are using an object such as :

  
public class Concept {
 
 private String conceptName;
 private int score;
 private List conceptOwnerList;
 private Map conceptDataDictionary;
 
 
 public Concept(String name){
  this.conceptName = name;
  conceptOwnerList = new ArrayList();
  conceptDataDictionary = new HashMap();
 }
 
 /**
  * @return the conceptName
  */
 public String getConceptName() {
  return conceptName;
 }
 /**
  * @param conceptName the conceptName to set
  */
 public void setConceptName(String conceptName) {
  this.conceptName = conceptName;
 }
 /**
  * @return the conceptType
  */
 public int getScore() {
  return score;
 }
 /**
  * @param conceptType the conceptType to set
  */
public void setScore(int score) {
 this.score = score;
}
 /**
  * @return the conceptOwner
  */
 public List getConceptOwner() {
  return conceptOwnerList;
 }
 /**
  * @param conceptOwner the conceptOwner to set
  */
 public void addConceptOwner(String conceptOwner) {
  conceptOwnerList.add(conceptOwner);
 }
 public Map getConceptDataDictionary() {
  return conceptDataDictionary;
 }
 public void addConceptToDataDictionary(String entry, String definition) {
  conceptDataDictionary.put(entry, definition);
 } 

}


Let's populate our object with some sample data, and serialize it to JSON using ObjectMapper

  

        Concept concept = new Concept("MyConcept");
        concept.setScore(50);
        concept.addConceptOwner("M. Ali");
        concept.addConceptOwner("D. Jackson");
        concept.addConceptOwner("Z. Amine");
        
        concept.addConceptToDataDictionary("Peniciline", "group of antibiotics");
        concept.addConceptToDataDictionary("Amoxiline", "antibiotic");
        concept.addConceptToDataDictionary("Morphine", "pain killer");
        
        ObjectMapper mapper = new ObjectMapper();
  mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
  
  String json = mapper.writeValueAsString(concept);
  
     System.out.println(json);
Result:




Some useful annotations for object properties:

@JsonAnyGetter: Annotation to add to the getter of a Map. It serializes the content of the map instead of using the map as an object itself.
@JsonIgnore: Ignores a property when serializing
@JsonProperty("someproperty"): uses "someproperty" as key value instead of the property name.


A JSON stream can be useful when the developper needs to build the content interactively:

JsonFactory factory = new JsonFactory();
        JsonGenerator generator = factory.createGenerator(new PrintWriter(System.out));
        generator.writeStartObject();
        generator.writeFieldName("JsonTest");
        generator.writeString("using a stream json generator");
        generator.writeFieldName("ArrayKey");
        // start an array
        generator.writeStartArray();
        
        generator.writeString("object 1");
        generator.writeString("object 2");
        generator.writeString("object 3");
        
        generator.writeEndArray();
        generator.writeEndObject();
 
        generator.close();
        
Result:




Monday, September 28, 2015

Building a Tree Grid using GXT / GWT

There is a large debate among GWT developpers on whether to use native GWT for applications and do everything from scratch or to make use of the large set of ready to use components and widgets provided by GXT. Personally, I prefer GWT as I do not like to be tied to any particular way of styling components. Based on my experience, GXT provide a great set of widgets that proved to be extremely useful; however, customizing them can be very time consuming. GXT components' performance is inferior to native GWT components. That being said, we can not deny that GXT can help developpers save time on developping some components which are considered standard in web UIs.  Building a tree grid is an example. A tree grid can be useful to represent data in a hierarchical fashion. In this tutorial, we are going to build a treegrid using GXT.

Requirements:
- Eclipse with GWT plugin
- GXT library   (Free for personal use or for open source projects)

The first thing we need to do is to create a google web application project. Go to File -> New -> Other  -> Google  and click on  Web application project. The project has the following structure:


Once the project is created, we need to add GXT to referenced libraries and also to GWT module configuration file. Right  click on the project, and then go to build path -> configure build path. Click on "Add External JARs" and add the Jar of GXT.



The GWT module confiugration describes the libraries that will be used in the project, the entry point( which can be translated as Welcome page), and where the translatable code lies.















Now, we are going to create our widget using the following components:

- TreeGrid: the actual treegrid widget
- ColumnConfig: object used for configuring columns
- TreeStore: object that serves as data model for the widget
- PropertyAccess<T>: interface that links the object data to the data model. The methods need to have the same name as the object T properties.


We are going to create a widget called MyTreeGrid that represents the data of an object named "Concept".
  
public class Concept {
 
 private String conceptName;
 private String conceptType;
 private String conceptOwner;
 
 
 
 public Concept(String conceptName, String conceptType, String conceptOwner){
  this.conceptName = conceptName;
  this.conceptType = conceptType;
  this.conceptOwner = conceptOwner;
 }
 /**
  * @return the conceptName
  */
 public String getConceptName() {
  return conceptName;
 }
 /**
  * @param conceptName the conceptName to set
  */
 public void setConceptName(String conceptName) {
  this.conceptName = conceptName;
 }
 /**
  * @return the conceptType
  */
 public String getConceptType() {
  return conceptType;
 }
 /**
  * @param conceptType the conceptType to set
  */
 public void setConceptType(String conceptType) {
  this.conceptType = conceptType;
 }
 /**
  * @return the conceptOwner
  */
 public String getConceptOwner() {
  return conceptOwner;
 }
 /**
  * @param conceptOwner the conceptOwner to set
  */
 public void setConceptOwner(String conceptOwner) {
  this.conceptOwner = conceptOwner;
 } 

}

We can use the same object to hold data for the second level of the hierarchy, but for clarity sake, we are going to use an object that extends "Concept".

public class ConceptMetaInformation extends Concept{
 public ConceptMetaInformation(String metaType, String location){
  super(metaType, location, "");

 }

}

Next, we need to create our PropertyAccess interface that will serve as a glue between the object and the view:


public interface Properties extends PropertyAccess<Concept>{
    ValueProvider<Concept> conceptName();
 
 ValueProvider<Concept> conceptType();
 
 ValueProvider<Concept> conceptOwner();

}

Note: methods need to have the same name as object properties.

Finally, we can create our widget:
public class MyTreeGrid implements IsWidget {
       TreeGrid<Concept> grid;
     ColumnConfig<Concept, String>  nameColumn;
  ColumnConfig<Concept, String> typeColumn;
  ColumnConfig<Concept, String>  ownerColumn;
  TreeStore<Concept> store;
  
//sample data
  Object[][] sampleValues = {
    {new Concept("Car","Transportation","Z.amine"), new ConceptMetaInformation("Location", "MENA"), new ConceptMetaInformation("Revenues", "150 000$")},
    {new Concept("Computer","I.T","H.John"), new ConceptMetaInformation("Location", "Europe"), new ConceptMetaInformation("Revenues", "180 000$")},
    {new Concept("Cookies","Food","R.David"), new ConceptMetaInformation("Location", "North America"), new ConceptMetaInformation("Revenues", "200 000$")},
    {new Concept("Electric Appliance","Home","T.Short"), new ConceptMetaInformation("Location", "China"), new ConceptMetaInformation("Revenues", "500 000$")},
    {new Concept("Air conditioner","Home","F.Jospeh"), new ConceptMetaInformation("Location", "Australia"), new ConceptMetaInformation("Revenues", "120 000$")}
  };
 
 @Override
 public Widget asWidget() {
  Properties properties = GWT.create(Properties.class);
  // TODO Auto-generated method stub
   store = new TreeStore<Concept>(new ModelKeyProvider<Concept>() {
   @Override
   public String getKey(Concept item) {
    if(item instanceof ConceptMetaInformation){
     return String.valueOf(item.getConceptName().hashCode()) + item.getConceptType().hashCode();
    }else {
     return String.valueOf(item.getConceptName().hashCode());
    }
    
   }
   });
   
   FillStore();
   
   nameColumn =  new ColumnConfig<Concept, String> (properties.conceptName(), 180); 
   typeColumn =  new ColumnConfig<Concept, String> (properties.conceptType(), 180); 
   ownerColumn =  new ColumnConfig<Concept, String> (properties.conceptOwner(), 180); 
   
   List<ColumnConfig<Concept, ?>> columns = new ArrayList<ColumnConfig<Concept, ?>>();
   
   columns.add(nameColumn);
      columns.add(typeColumn);
      columns.add(ownerColumn);
 
  ColumnModel<Concept> columnsModel = new ColumnModel<Concept>((List<ColumnConfig<Concept, ?>>) columns);
  
  grid = new TreeGrid<Concept>(store, columnsModel, nameColumn);
  grid.setHideHeaders(true);
  grid.setBorders(false);
  
  grid.setSelectionModel(new TreeGridSelectionModel<Concept>());
  grid.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
  
  return grid;
 }
 
 private void FillStore(){
  for(Object[] conceptInfo: sampleValues){
   Concept concept = (Concept) conceptInfo[0];
   ConceptMetaInformation location = (ConceptMetaInformation) conceptInfo[1];
   ConceptMetaInformation revenues = (ConceptMetaInformation) conceptInfo[2];
   store.add(concept); 
   store.add(concept, location); 
   store.add(concept, revenues); 
  }
 }
}

We can test our widget in our entry point class:
public class TreeGrid implements EntryPoint {
 /**
  * This is the entry point method.
  */
 public void onModuleLoad() {
  MyTreeGrid treegrid = new MyTreeGrid();
  RootPanel.get("treegrid").add(treegrid.asWidget());

 }
}
Result:


we have an out of the box tree grid that we can use as needed. It can be customized with editors for each cell if needed. 

Friday, September 11, 2015

Generating Rest Services documentation using Swagger



We have seen in "How to create a Restful application using Spring", how to build a Rest API using Spring Framework.
After we have built our Rest APIs, we want the developpers and users to have an up-to-date description of  the available operations and resources. The best way to do it is to auto-generate your documentation from code. There are lots of ways for achieving this; one of them is Swagger which is considered one of the best frameworks for this purpose. In this post, we will walk step by step through how to generate documentation for a Rest application built using Spring MVC.

Requirements:
SpringFox ( Swagger Integration for Spring MVC)
Swagger UI
Maven, Spring, Eclipse,..


Let's suppose we have two resources: Person, Concept, and a controller for each resource: PersonController, and ConceptController. The application structure looks like:



We have added the following dependencies for swagger libraries to our pom.xml:



Now we need to configure Swagger, for this we will create a configuration class:
  
@EnableSwagger2
public class SwaggerConfiguration {
  @Bean
   public Docket myApi() {
   return new Docket(DocumentationType.SWAGGER_2)
   .apiInfo(getApiInfo());
  }
  private ApiInfo getApiInfo(){
   //We do not use all info
   ApiInfo info = new ApiInfo("My Rest API", "Auto generated Rest API Documentation","1.0","","","","");
   return info;
  }
}



@EnableSwagger2 tells Spring to generate an api description in JSON at v2/api-docs endpoint
@Bean is the bean for the Docket for configuring the Documentation description. We have only used API info, which configures the Info section of the documentation. More configuration options are described at: http://springfox.github.io/springfox/docs/snapshot/

Next, we need to add some description to our operations, let's take the example of ConceptController:
  
@Api(value="Concept")
@Controller
@RequestMapping("/concept")
public class ConceptController {
 @ApiOperation(value = "Fetch all Concepts")
 @RequestMapping(method= RequestMethod.GET)
 public @ResponseBody Concept displayConcepts() throws Exception {
  Concept concept = new Concept();
  concept.setConceptName("Test Concept");
  concept.setConceptOwner("Me");
  concept.setConceptType("Sample");
  
  return concept;
 }
 @ApiOperation(value = "Creates a new Person in the database")
 @RequestMapping(method= RequestMethod.POST)
 public Concept createConcept(){
  
  
  return null;
 }

}


We have added @Api to the class in addition  to Spring Annotations. This is for telling Swagger that this represents an API with a title Concept.

We have also added @ApiOperation to each operation for telling Swagger to add the description in value to operations.

Both annotations are optional.

Now, if we run our application using Jetty and navigate to localhost:8080/v2/api-docs:

We can see that Swagger generates a description of our API in JSON format. This description is used by Swagger UI, which a JS library that takes this JSON as an input and creates a good looking documentation

In order to display the docs, we are going to download Swagger UI and add it to application resources, and create a html page in which we are going to load the Swagger JS script:




Before navigating to our doc page, we need to add: <mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" /> to our mvc-dispatcher-servlet.xml in order to serve static resources without a controller.

Finally, we can navigate to our docs:


The user can expand operations for more details, and even try them.


Full example at: https://github.com/zak905/swaggerexample

Thursday, September 3, 2015

Introduction to Java 8 Streams

Java 8 has been released a while ago, but lots of developpers still do not make use of its full potential. One of key features of Java 8 that can change how developpers look at collections is: Streams.

Streams introduce a new programming style and let you process collections in a declarative way rather than using loops or iterators.

Let's suppose we have a list of strings and we want to : retrieve strings that are less than 4 charachters, make them upper case, sort the result, and finally print it.

List myList = Arrays.asList("yet","another", "proof", "that", "java8", "streams","rocks"); 

The conventional way of doing it is to loop through the list and retrieve one element at a time, test if they fill the condition, turn them upper case, store them in a new list, sort the list and finally print it. 
 List result = new ArrayList();
  for(int i = 0; i < myList.size(); i++){
   if(myList.get(i).length() <= 4){
    result.add(myList.get(i).toUpperCase()); 
   }
  }
  Collections.sort(result);
  

  for(int i = 0; i < result.size(); i++)
       System.out.println(result.get(i));


Using streams, the process is much shorter and can be written as:

myList.stream()
  .filter( s -> s.length() <= 4)
  .map(s -> {return s.toUpperCase();})
  .sorted()
  .forEach(System.out::println);
Result :
THAT
YET
Another useful feature of Streams API is when the developpers needs to apply a formula such as sum or average or any other mathematical formula.

Suppose we have the following object:

public class Tag {
	
	public enum TYPE{
		NEWS, SPORTS
		
	}
	
	private String name;
	
	private int count;
	
	private TYPE type;
	
	public Tag(String name, int count, TYPE type) {
		this.name = name;
		this.count = count;
		this.type = type;
	}
	
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the count
	 */
	public int getCount() {
		return count;
	}

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

	/**
	 * @return the type
	 */
	public TYPE getType() {
		return type;
	}

	/**
	 * @param type the type to set
	 */
	public void setType(TYPE type) {
		this.type = type;
	}
	
	@Override
	public String toString(){
		return "{name:"+name+", count:"+count+"}";
	}
	
}
Let's suppose we have a list of Tags and we want to calculate the sum or average of the "count" property.
	List tagsList = Arrays.asList(
				new Tag("tag1", 10, Tag.TYPE.NEWS),
				new Tag("tag2", 20, Tag.TYPE.SPORTS), 
				new Tag("tag3", 40, Tag.TYPE.SPORTS));
Once again, the conventional way to do it is loop through all elements apply the desired formula. Using Stream, it can be done in the following way:
		int countSum = tagsList.stream()
		.mapToInt(Tag::getCount)
		.sum();
Average:
		tagsList.stream()
		.mapToInt(Tag::getCount)
		.average()
		.ifPresent(System.out::println);
Another very useful feature of Streams is grouping elements by a common property:
		
		Map<TYPE, List> map = tagsList.stream()
		.collect(Collectors.groupingBy(Tag::getType));

System.out.println(map);
Result:
{NEWS=[{name:tag1, count:10}], SPORTS=[{name:tag2, count:20}, {name:tag3, count:40}]}


The list is still long, and the possibilities are endless. But since this is just an introduction, we will stop here. We will go through more advanced stuff later on.

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


Monday, August 31, 2015

Using OAuth to connect to Google APIs from a Java desktop application


Google uses OAuth for managing authentication and authorization to its APIs. While the flow of action comes naturally in a Web application, it may be confusing for a Desktop a application. The steps for using OAuth is as follow:

           1. Obtaining OAuth credentials from Google Developpers Console
           2. Request a Token
           3. Use Tokens to Authenticate your Requests
           4. Refresh the token when it expires.

While on a Web application you have the possiblity to use redirect and directly store your token on the current session, in a Desktop application you need enter the URL manually in a browser, retrieve the code, enter it, obtain the token and store it on disk.

Let's go through an example of access to Google Calendar API from a Swing application:

First of all, you need to obtain OAuth Client Credentials from Google Developers Console.

The flow is as follows:
- Use the credentials to request a code from Google OAuth server
- Open a browser and copy the code
- Enter the obtained code in the command line as requested by the application
- Obtain the token and store it on disk
- Use it as long as it is valid, else refresh it

The code below illustrates the process:
 /** Authorizes the installed application to access user's protected data. */
   private static Credential authorize() throws Exception {
    
     // load client secrets
     GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
         new InputStreamReader(GoogleCalendarManager.class.getResourceAsStream("/client_secret_2.json")));
    
     //If the client secrets/Id are not valid
     if (clientSecrets.getDetails().getClientId().startsWith("Enter")
         || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
       System.out.println(
           "Unable to authenticate, Please Enter a Client ID and Secret from https://code.google.com/apis/console/?api=calendar ");
       System.exit(1);
     }
     
     
     GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
         httpTransport, JSON_FACTORY, clientSecrets,
         Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory)
         .build();
       
     Credential credential;
     //First Time
     if(flow.getCredentialDataStore().isEmpty()) {
     
   GoogleAuthorizationCodeRequestUrl url =  flow.newAuthorizationUrl();
    url.setRedirectUri("urn:ietf:wg:oauth:2.0:oob");
     System.out.println("Please enter the URL in your browser: " +  url.build().toString());
     System.out.println("Please enter the code: ");
     BufferedReader br = 
                new BufferedReader(new InputStreamReader(System.in));

                String code;
                code = br.readLine();
  
  //System.out.println("received code " + code);
  

  AuthorizationCodeTokenRequest accessTokenRequest = flow.newTokenRequest(code);
  accessTokenRequest.setRedirectUri("urn:ietf:wg:oauth:2.0:oob");
  TokenResponse response = accessTokenRequest.execute();
  
     credential = flow.createAndStoreCredential(response, APPLICATION_NAME);
     }
     //After the first time
     else{
       credential = flow.loadCredential(USER_ID);
      
     }
     
     return credential;
   }



The "client_secret_2.json" is provided by Google OAuth and can be downloaded when the client secrets are set up.

Full example at: https://github.com/zak905/GoogleCalendarAPI


Monday, August 3, 2015

How to secure a Java desktop application using Apache Shiro


Apache Shiro is one of many available Java framework for securing your application. While most of them focus on Web applications, Shiro can be used to secure your Desktop application as well. Shiro focuses on simplicity and can be used even by newbies.

Let's suppose we have users credentials and roles stored in a database, and we want to use Shiro for managing login to the application. Shiro uses the concept of Realm to define the data object that  gives access to user credentials. Since we are accessing user credentials in a database, we will be using JdbcRealm. We need also to define the database queries that will be used to retrieve credentials and roles. Something like: 


//To be adapted to user context
    private static final String AUTHENTICATION_QUERY = "SELECT password FROM users WHERE username=?";
    private static final String ROLES_QUERY = "SELECT access_designation FROM access_level,users WHERE access_level.id=users.access_level_id and users.username = ?" ;


Another important aspect of Shiro is shiro.ini which is used for configuration :
# =============================================================================
 #  Realm configuration
 #
 # =============================================================================
 [main]
 jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
 jdbcRealm.permissionsLookupEnabled = false
 ds = yourpackage.MyDataSource
 jdbcRealm.dataSource=$ds
 securityManager.realms = $jdbcRealm
We need also to define our datasource, which tells Shiro about how to connect to the database.
import com.jolbox.bonecp.BoneCPConfig;
import com.jolbox.bonecp.BoneCPDataSource;

/**
 *
 * @author zakaria
 */
public class MyDataSource extends BoneCPDataSource {
    /** Data source class for retrieving authentication information **/
    public MyDataSource() {
	super();
    /* Change as needed */
	this.setDriverClass("org.sqlite.JDBC");
	this.setJdbcUrl("jdbc:sqlite:mymanagerdb");
	this.setUsername("");
	this.setPassword("");
	this.setDefaultAutoCommit(true);
    }

    /**
     * @param config
     */
    public MyDataSource(BoneCPConfig config) {
	super(config);
    }

}
We are set. We can now define our authentication class:

public class Authenticator {
    
    //To be adapted to user context
    private static final String AUTHENTICATION_QUERY = "SELECT password FROM users WHERE username=?";
    private static final String ROLES_QUERY = "SELECT access_designation FROM access_level,users WHERE access_level.id=users.access_level_id and users.username = ?" ;
    
    /*** Autenticates a user **/
    public Subject authenticate(String username, String pass) {

		Subject currentUser = null;
		try {

	   Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
			// the key "jdbcRealm" must be the same in the shiro.ini file.
JdbcRealm realm = (JdbcRealm) ((IniSecurityManagerFactory) factory).getBeans().get("jdbcRealm");
			realm.setAuthenticationQuery(AUTHENTICATION_QUERY);
			realm.setUserRolesQuery(ROLES_QUERY);
			
			SecurityUtils.setSecurityManager(securityManager);

			currentUser = SecurityUtils.getSubject();

			UsernamePasswordToken token = new UsernamePasswordToken(username, pass);
				
			currentUser.login(token);
				
		} catch (Exception e) {
			e.printStackTrace();
		}
		return currentUser;

	}

}

Finally, we can use our authenticator as needed:

public static void main(String[] args) throws Exception {
		
		String userName = "someUserName";
		String userName = "somePassword";

		Authenticator authenticator = new Authenticator();
        Subject currentUser = authenticator.authenticate(userName, password);
        if(currentUser.isAuthenticated()){
        	Session session = currentUser.getSession();

        	//Storing some attributes
        	session.setAttribute("Connected", "yes");


        	//Retrieving attributes later on 

            String attribute = session.getAttribute("Connected").toString();

            System.out.println("Connected : " + attribute);

        }
        else{
           System.out.println("Could not authenticate user");
        }
		
		

	}
Source code: https://github.com/zak905/ShiroSimpleAuthentication-

Wednesday, July 29, 2015

How to create a Restful application using Spring




Rest architecture has become a de facto standard for constructing APIs and consuming Web services. In the example below, we are going to create a simple Rest application step by step using Spring 4.

Requirements:

- Eclipse
- Maven
- Jackson (not necessary, but makes things easier)
- Spring
-Any web server ( Maven Jetty Plugin in our case).

Maven Dependencies can be found here: https://github.com/zak905/rest-spring-example/blob/master/pom.xml

Let's start by first creating our "web" application.

In Eclipse, we need to go to: File -> New  -> Maven -> Maven Project. Click on Next, and Choose Web application Archetype as shown below :


Next, we can enter our Group Id and Artifact Id. Click on Finish, and the application is created.

I assume that you are already familiar with MVC concepts such as Controllers.

The structure of the application is as follows:



After creating the application, we need to create our PoJo that will serve as our Rest Resource. Our object looks like:

public class Person {
 private String firstname;
 private String lastName;
 private int age;
 private String departement;
 
 
 public Person(){
  
  
 }

 public String getFirstname() {
  return firstname;
 }

 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }


 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }


 public String getDepartement() {
  return departement;
 }

 public void setDepartement(String departement) {
  this.departement = departement;
 }
 
}

Next, we need to create the controller that will serve our resource. In a Rest application, GET is used for read operations ( access the data), while POST is used for write operations (e.g create a new person in the database).

@Controller
@RequestMapping("/person")
public class PersonController {
	@RequestMapping(method= RequestMethod.GET)
	public @ResponseBody Person getPersons(){
		Person person = new Person();
		person.setFirstname("some first name");
		person.setLastName("some lastname");
		person.setAge(26);
		person.setDepartement("Accounting");
		return person;
	}
}

That's it. All we need to do now is to configure our servlet in web.xml, and then we can test our application. First, we create our "mvc-dispatcher-servlet.xml" in WEB-INF:



Then, we add the servlet definition in web.xml:



















Finally, we can run our application using Jetty. In Eclipse, right click on the project -> Run As -> Run Configurations. In Goals field, type: jetty:run. Now you can open your browser and go to: localhost:8080/person

Congratulation, you have successfully created a Rest style application.

Source Code : https://github.com/zak905/rest-spring-example