Sunday, October 30, 2016

How to start using DerbyDB with Netbean?

Why we need to use DerbyDB, fisrt of all , it is shipped a long with Java JDK,

If you first learn Java and want to learn How Java work with Database,

We can use DerbyDB, Because we dont need to install a new DB that reason.

Another reason, I am wonder, how to use all tools shipped by Java JDK,

First Open Netbean,

Check Derby database configuration

Check configuration of JavaDB Choose location of JavaDB installed on your machine, normally the

DerbyDB was shipped along with JDK

 Right click on JavaDB --> Choose create new DB

After create DB success, a new database connection automatically created by Netbean,

Click on connect to

Netbean will automatically startup DerbyDB and Connect to that data.

 Now database is ready for futher more steps.

Saturday, October 22, 2016

Serialization and Deserialization JSON in JAVA with GSON


Today I will give an example of using GSON to Serialization and Deserialization JSON in JAVA

When we work with JSON, there are some tasks we usually do,

  1. Parse Object to JSON and vice versa
  2. Parse Collection to JSON and vice versa
  3. And sometime we need to create an JSON object with dynamic field, In my example I used Map to do it.We also need to Deserialization and JSON object with dynamic field to Java Object

Here is some code example:


import java.awt.Point;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

 * @author ducnguyen
public class Main {

    private static Gson gson = new Gson();

    public static void main(String[] args) {
        System.out.println("Serialization and Deserialization an OBJECT");
        Point p1 = new Point(2, 1);
        String json1 = gson.toJson(p1);
        System.out.println("p1 -> json1 : " + json1);
        Point p2 = gson.fromJson(json1, Point.class);
        System.out.println("json1 -> p2 : " + p2.toString());

        System.out.println("Serialization and Deserialization a LIST");
        List l1 = Arrays.asList(new Point(2, 1), new Point(3, 4));
        String json2 = gson.toJson(l1);
        System.out.println("l1 -> json2 : " + json1);
        List l2 = gson.fromJson(json2, List.class);
        System.out.println("json2 -> l2 : " + l2.toString());

        System.out.println("Create object fields with MAP");
        Map jsonObject = new HashMap<>();
        jsonObject.put("integer", 100);
        jsonObject.put("string", "hello world");
        jsonObject.put("boolean", Boolean.TRUE);
        String json3 = gson.toJson(jsonObject);
        System.out.println("jsonObject -> json3 : " + json3);
        System.out.println("Deserialization MAP");
        Map jsonObject2 = gson.fromJson(json3, Map.class);
        System.out.println("json3 -> jsonObject2 : "+ jsonObject2.toString());



Here is output of the code:

Serialization and Deserialization an OBJECT
p1 -> json1 : {"x":2,"y":1}
json1 -> p2 : java.awt.Point[x=2,y=1]
Serialization and Deserialization a LIST
l1 -> json2 : {"x":2,"y":1}
json2 -> l2 : [{x=2.0, y=1.0}, {x=3.0, y=4.0}]
Create object fields with MAP
jsonObject -> json3 : {"integer":100,"string":"hello world","boolean":true}
Deserialization MAP
json3 -> jsonObject2 : {integer=100.0, string=hello world, boolean=true}

You can download source code here

Saturday, October 15, 2016

AngularJS - formatter and parser example

When I work with an old project built use AxonIvy ,

I got an issue with date format

In that project, If I want to send a date from Web application using AngularJS to Server Side.

I need to send a date with format

For example:
 day: 31,
 month: 12,

Also the Server will return the same format for date fields.

For the client side, I use an AngluarJs UI Angular-Strap ,
Which provided very nice widgets.

Unfortunately, bsDate picker only work with common dateformat like ISO , UTC or Timestamp
which look likes:




In order to make Ivy Date work, I create a new directive :

app.directive('ivyDate', function() {
  return {
    require: 'ngModel',
    priority: 1,
    link: function(scope, elem, attrs, ngModelCtrl) {
      // formats text going to user (from model to view)
      ngModelCtrl.$formatters.push(function(value) {
        var modelValue = scope[attrs['ngModel']];
        return new Date(Date.UTC(modelValue.year, modelValue.month - 1,;

      // formats text from the user (from view to model)
      ngModelCtrl.$parsers.push(function(value) {
        var date = new Date(value);
        return {
          day: date.getUTCDate(),
          year: date.getFullYear(),
          month: date.getMonth() + 1

So this directive with get date object from Server and display it as normal date to View

And everytime the View change, it will return a date with Server format to Model

One of the most important thing in my code is priority,

I set priority to 1 to ensure my $formatter function with run before the $formatter of bsDatePicks, After take my time to investigate that my formatter always run after the formatter of bsDatePicker, and bsDatePicker can only work with date in common format.

Here is remainng code:


var app = angular.module('mgcrea.ngStrapDocs', ['ngAnimate', 'ngSanitize', 'mgcrea.ngStrap']);
app.controller('MainCtrl', function($scope, $timeout) {
  $scope.simpleDate= new Date();
  $scope.ivyDate= {
    day: 30,
    month: 11,
    year: 2016
  $scope.setDate = function() {
    $scope.ivyDate= {
      day: 30,
      month: 11,
      year: 2015

HTML - View:

 <body ng-controller="MainCtrl">  
  <form name="datepickerForm" class="form-inline" role="form">  
   <div class="form-group" ng-class="{'has-error': datepickerForm.date2.$invalid}">  
    <label class="control-label"><i class="fa fa-calendar"></i> Normal Date <small></small></label>  
    <input type="text" class="form-control" ng-model="simpleDate" data-date-format="yyyy-MM-dd" data-date-type="number" data-min-date="02/10/86" data-autoclose="1" name="date2" bs-datepicker >  
   <hr />  
   <br />  
   <!-- Custom example -->  
   <div class="form-group" ng-class="{'has-error': datepickerForm.date2.$invalid}">  
    <label class="control-label"><i class="fa fa-calendar"></i> Ivy Date <small></small></label>  
    <input type="text" class="form-control" ng-model="ivyDate" data-date-format="yyyy-MM-dd" data-date-type="number" data-min-date="02/10/86" data-autoclose="1" name="date2" ivy-date bs-datepicker >  
   <br />  
   <br />  
   <button class="btn btn-primary" ng-click="setDate($event)"> setDate </button>  
   <textarea cols="14" rows="7">  

Here is live demo on Plunker

Wednesday, October 5, 2016

Java8 - Working with Base64

In JDK8, It is supported Base64 decode/encoding,

Here is an example of using Base64


import java.util.Base64;
import org.junit.Assert;
import org.junit.Test;

 * @author nvduc
public class Base64Test {

    public Base64Test() {

    public void test() {
        String origin = "Hello World";
        String base64 = new String(Base64.getEncoder().encode(origin.getBytes()));
        String fromBase64 = new String(Base64.getDecoder().decode(base64));
        System.out.println("text Encoded : " + base64);
        System.out.println("text Decoded : " + fromBase64);
        Assert.assertEquals(origin, fromBase64);

You can find this example code on Github