Friday, November 18, 2016

Write a method get sum of two element which closest to Zero

Here is the code in Javascript:



/*
 * Please implement this method to return the sum of the two elements closest to zere. If there are two elements equally close to zero like -2 and 2.
 * consider the positive element to be "closer" to zero than the negative one.
 * 
 *
 */

function sumOfTwoElementsClosestToZero(arr) {
    var length = arr.length;
    var first = arr[0];
    var second = arr[0];

    for (var i = 0; i < length; i++) {
        if (arr[i] == 0) {
            continue;
        }
        if (abs(first) > abs(arr[i]) || (abs(first) == abs(arr[i]) && arr[i] > 0)) {
            first = arr[i];
        }
    }

    for (var i = 0; i < length; i++) {
        if (arr[i] == 0) {
            continue;
        }
        if (abs(arr[i]) > abs(first) && (abs(second) > abs(arr[i]) || abs(second) == abs(arr[i]) && arr[i] > 0)) {
            second = arr[i];
        }
    }

    return (second + first);
}

function abs(num) {
    return num < 0 ? -num : num;
}


console.log("test 1 : " + (sumOfTwoElementsClosestToZero([7, 8, 3, 4, 2, 8, -3, 4, -2, -100]) == 5));
console.log("test 2 : " + (sumOfTwoElementsClosestToZero([7, 8, -3, 4, 2, 8, -3, 4, -2, -100]) == -1));
console.log("test 3 : " + (sumOfTwoElementsClosestToZero([7, 8, 3, 4, -1, 8, -3, 4, -2, -100]) == -3));
console.log("test 4 : " + (sumOfTwoElementsClosestToZero([7, 8, 3, 4, 2, 8, -3, 4, -2, -100]) == 5));
console.log("test 5 : " + (sumOfTwoElementsClosestToZero([-3, -2, -1, 1, 0, 2]) == 3));

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

Hello,

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:


package com.blogspot.ducnguyen.dev.json.example;

import com.google.gson.Gson;
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,
 year:2016
}

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:

"2016-10-16T04:06:15.481Z"

or 

1476590721627

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, modelValue.day));
      });

      // 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:

Controller:


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 >  
   </div>  
   <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 >  
   </div>  
   <br />  
   <br />  
   <button class="btn btn-primary" ng-click="setDate($event)"> setDate </button>  
   <textarea cols="14" rows="7">  
   {{ivyDate|json}}  
    </textarea>  
   <hr>  
  </form>  
 </body>  

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



package my.example.java.base64;

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

/**
 *
 * @author nvduc
 */
public class Base64Test {

    public Base64Test() {
    }

    @Test
    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

Thursday, September 29, 2016

CSS - Centering element

Hello,

Here is CSS using for centering element


 <html>  
 <head>  
 <style>  
   /*display table cell*/  
  .container1{  
  width: 200px;  
  height: 200px;  
  border : 1px solid red;  
  display : table-cell;  
  vertical-align: middle;  
  }  
  .content1{  
  border:1px solid blue;  
  }  
  /*CSS3 with transform*/  
  .container2{  
  margin-top:50px;  
  width: 200px;  
  height: 200px;  
  border : 1px solid red;  
  position:relative;  
  }  
  .content2{  
  border:1px solid blue;  
  position: absolute;  
  top: 50%;  
  transform: translate(0, -50%);  
  }  
  /*CSS3 with transform*/  
  .container3{  
  margin-top:50px;  
  width: 200px;  
  height: 200px;  
  border : 1px solid red;  
  display: flex;  
  align-items: center;  
  }  
  .content3{  
  border:1px solid blue;  
  }  
 </style>  
 </head>  
 <body>  
  <h2>  
 Centering vertical with table style:</h2>  
 <div class="container1">  
  <div class="content1">  
   1. This small paragraph is vertically centered.<br />  
  </div>  
 </div>  
 <h2>  
 Centering vertical CSS3 :</h2>  
 <div class="container2">  
  <div class="content2">  
   2. This small paragraph is vertically centered.<br />  
  </div>  
 </div>  
 <h2>  
 Centering vertical using Flex :</h2>  
 <div class="container3">  
  <div class="content3">  
   3. This small paragraph is vertically centered.<br />  
  </div>  
 </div>  
 </body>  
 </html>  
You can find the live demo here Plunker

Wednesday, September 21, 2016

Java - Create image inside a rectangle

Here is an example put image into a rectangle, with calculation to keep full width of image:


package my.example.image;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

import javax.imageio.ImageIO;

public class ImageInRectange {

    public static void main(String[] args) throws IOException {
        createImageInRectagle(512, 1024, new File("./src/main/resources/chelsea.png"));
    }

    public static File createImageInRectagle(int width, int height, File image) throws IOException {
        Image originImage = ImageIO.read(image);
        int oImgWidth = originImage.getWidth(null);
        int oImgHeight = originImage.getHeight(null);
        float imageRatio = (float) oImgHeight / oImgWidth;
        float rectangleRatio = (float) width / height;

        BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        BufferedImage bufferedImage = ImageIO.read(image);
        Graphics g2 = combined.getGraphics();
        Point p = new Point(0, 0);
        if (Math.abs(imageRatio - rectangleRatio) < 0.05) {
            bufferedImage = scale(bufferedImage, width, height);
            p.x = 0;
            p.y = 0;
        } else {
            int minEdge = width < height ? width : height;
            if (oImgHeight > oImgWidth) {
                float diff = (float) oImgHeight / minEdge;
                int newWidth = Math.round(oImgWidth / diff);
                bufferedImage = scale(bufferedImage, newWidth, minEdge);
                if (minEdge == height) {
                    p.x = Math.abs((width - newWidth) / 2);
                    p.y = 0;
                } else {
                    p.x = 0;
                    p.y = Math.abs((height - minEdge) / 2);
                }
            } else {
                float diff = (float) oImgWidth / minEdge;
                int newHeight = Math.round(oImgHeight / diff);
                bufferedImage = scale(bufferedImage, minEdge, newHeight);
                if (minEdge == height) {
                    p.x = Math.abs((width - minEdge) / 2);
                    p.y = 0;
                } else {
                    p.x = 0;
                    p.y = Math.abs((height - newHeight) / 2);
                }
            }
        }
        g2.drawImage(bufferedImage, p.x, p.y, null);
        g2.dispose();
        File tempImage = Paths.get("target", "ok.png").toFile();
        ImageIO.write(combined, "png", tempImage);
        return tempImage;
    }

    public static BufferedImage scale(BufferedImage imgb, int newWidth, int newHeight) {
        Image image;
        image = imgb.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
        return toBufferedImage(image);
    }

    public static BufferedImage toBufferedImage(Image img) {
        if (img instanceof BufferedImage) {
            return (BufferedImage) img;
        }
        BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D bGr = bimage.createGraphics();
        bGr.drawImage(img, 0, 0, null);
        bGr.dispose();
        return bimage;
    }
}

You can find source code on Github

Wednesday, September 14, 2016

APACHE PDFBOX EXAMPLE WITH MAVEN

Here is an example of create a Maven project using Netbean.

In this example, I used Apache PDFBox as an example of using maven for managing Java library

1. We create a new project using Netbean:



New Maven project with Netbean

Input the artifactId and package name


2. Add code


Declare maven dependenies


    4.0.0
    com.blogspot.ducnguyen.dev
    pdfbox-example
    1.0-SNAPSHOT
    jar
    
        UTF-8
        1.7
        1.7
    
    
        
        
            org.apache.pdfbox
            pdfbox
            2.0.0
        
    



Add Java Code:
package com.blogspot.ducnguyen.dev.pdfbox.example;

import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

/**
 *
 * @author nvduc
 */
public class Main {
    public static void main(String[] args) throws IOException
    {
        long timestamp = System.currentTimeMillis();
        String filename = "test-"+timestamp+".pdf";
        String message = "Hello World at : "+ timestamp;
        
        PDDocument doc = new PDDocument();
        try
        {
            PDPage page = new PDPage();
            doc.addPage(page);
            
            PDFont font = PDType1Font.HELVETICA_BOLD;

            PDPageContentStream contents = new PDPageContentStream(doc, page);
            contents.beginText();
            contents.setFont(font, 12);
            contents.newLineAtOffset(100, 700);
            contents.showText(message);
            contents.endText();
            contents.close();
            
            doc.save(filename);
        }
        finally
        {
            doc.close();
        }
    }
}



3. Running


Before running, we must build project, When we build, maven will get pdfbox library from maven repository

Build project in NetBean



Right click on Main.java file, Choose Run File

We can check the result in Files view

Result after choose Run File

You can check the source code on Github