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: