程式碼高𠅙

2014/06/18

Java: JSON Library

Below is a list of major JSON format processing libraries for java. Check it out.

  • JSON Processing
    • Summary
      • JSR 353: Java API for JSON Processing - Reference Implementation
    • Comment
      • the java version official implementation
  • JSON in Java (json.org)
    • Summary
      • json.org official implementation
    • Comment
      • The API requires you to load the entire document into a String. This is somewhat cumbersome to use and inefficient for large documents. But it's a DOM model so you can get a lot done with very little code. 
  • Jackson JSON Processor
    • Summary
      • High-performance JSON processor.
    • Comment
      • Jackson ones to be the fastest json processing library in the old age.
      • Has many features with modules approach.
      • Jackson has grown into a huge collection of data type processing library
  • Boon JSON
  • google-gson 
    • Summary
      • A Java library to convert JSON to Java objects and vice-versa
    • Feature
      • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
      • Allow pre-existing unmodifiable objects to be converted to and from JSON
      • Extensive support of Java Generics
      • Allow custom representations for objects
      • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
  • json-simple
    • Summary
      • JSON.simple is a simple Java toolkit for JSON. You can use JSON.simple to encode or decode JSON text. 
    • Feature
      • Full compliance with JSON specification (RFC4627) and reliable (see compliance testing)
      • Provides multiple functionalities such as encode, decode/parse and escape JSON text while keeping the library lightweight
      • Flexible, simple and easy to use by reusing Map and List interfaces
      • Supports streaming output of JSON text
      • Stoppable SAX-like interface for streaming input of JSON text (learn more)
      • Heap based parser
      • High performance (see performance testing)
      • No dependency on external libraries
      • Both of the source code and the binary are JDK1.2 compatible
    • Comment
  • genson - A fast & extensible Java <> Json library
    • Summary
      • Genson is an open-source library doing conversion from Java to Json and Json to Java. Genson targets people who want an extensible but also configurable, fast, scalable and easy to use library. 
    • Feature
      • Easy to use, fast, highly configurable, lightweight and all that into a single small jar!
      • Full databinding and streaming support for efficient read/write
      • Support for polymorphic types (able to deserialize to an unknown type)
      • Does not require a default no arg constructor and really passes the values not just null, encouraging immutability. It can even be used with factory methods instead of constructors!
      • Full support for generic types
      • Easy to filter/include properties without requiring the use of annotations or mixins
      • You can apply filtering or transformation logic at runtime on any bean using the BeaView mechanism
      • Genson provides a complete implementation of JSR 353
      • Starting with Genson 0.95 JAXB annotations and types are supported!
      • Automatic support for JSON in JAX-RS implementations
      • Serialization and Deserialization of maps with complex keys
    •  Comment
      • Looks good!
 Want to use XPath with JSON? see below.
  • Commons JXPath
    • Summary
      • The org.apache.commons.jxpath package defines a simple interpreter of an expression language called XPath. JXPath applies XPath expressions to graphs of objects of all kinds: JavaBeans, Maps, Servlet contexts, DOM etc, including mixtures thereof.  
  • json-path 
    • Summary
      • Java JsonPath implementation

2014/03/27

Java Practice: Shutdown Hook

今日 Daily Java Practice 如下,請問其中 runTime.addShutdownHook 的作用。

public class Main implements Runnable {
    public void run() {
        System.out.println("Shutting down");
    }

    public static void main(String[] arg) {
        Runtime runTime = Runtime.getRuntime();
        Main hook = new Main();
        runTime.addShutdownHook(new Thread(hook));
    }
}

2014/03/24

Java Practice: Enum

今天來玩玩 enum, 以下透過一程式,說明 enum 如何把物件導向程式的三個特質封裝、繼承跟多型完美的結合在一起。
善用 enum,可以大幅減少程式碼。
以下請說明:
  • 程式輸出訊息。
  • 為何輸出此訊息。
  • S, M, L, XL ... 與 Size 的關係,是類別跟實體的關係,還是父類別跟子類別的關係?

public class SizeIterator {
    public static void main(String[] args) {
        Size[] sizes = Size.values();
        for (Size s : sizes) {
            s.showName();
            s.showType();
        }
    }
}

enum Size {
    S {
        @Override
        public void showName(){
            System.out.println("I am too small to show to others!");
        }
    }, M, L, XL, XXL, XXXL;
    public void showName() {
        System.out.println(this.name());
    }
    public void showType() {
        System.out.println(this.getClass().getName());
    }
}

2014/03/19

Java Practice: Object Serialization

今天的 Java Practice 如下, 請服用:
  1. Coper 類別的功用為何?
  2. Coper:: <T> copyInstance(T obj) 方法使用了 Java Generic 的技巧,請解釋這裡採用型別參數的好處?
  3. main 方法中印出的兩個 User 物件,內容是否相同? 若有差異,原因為何?
abstract class Copier {
    @SuppressWarnings("unchecked")
    public static <T> copyInstance(T obj) throws IOException,
            ClassNotFoundException {
        ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
        ObjectOutputStream outStream = new ObjectOutputStream(outBytes);
        outStream.writeObject(obj);
        outStream.close();
        ByteArrayInputStream inBytes = new ByteArrayInputStream(outBytes
                .toByteArray());
        ObjectInputStream inStream = new ObjectInputStream(inBytes);
        T copied = (T) inStream.readObject();
        inStream.close();
        return copied;
    }
}

class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private Date date = new Date();
    private String username;

    private transient String password;

    public User(String name, String pwd) {
        username = name;
        password = pwd;
    }

    public String toString() {
        String pwd = (password == null) ? "(n/a)" : password;
        return "logon info: \n   username: " + username 
            + "\n   date: " + date
            + "\n   password: " + pwd;
    }
}

public class CopierTest {
    /**
     * @param args
     * @throws Exception
     * @throws IOException
     */
    public static void main(String[] args) throws Exception {
        User jack = new User("Jack", "magic");
        System.out.println(jack);
        User copyOfJack = Copier.copyInstance(jack);
        System.out.println(copyOfJack);
    }
}  

2014/03/18

Java Practice: Random


練習一下使用 Java Random 類別。
以下題目,請試著寫出最後 min, max 印出來的最可能數值。
public class MathRandomTest {
 public static void main(String[] args) {
    Random rand = new Random();
   
   int n = 10;
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
   
    for(int i = 0; i < 100; i ++){
      int r = rand.nextInt(n + 1);
      min = Math.min(min, r);
      max = Math.max(max, r);
    }
    System.out.printf("Min = %d, Max = %d", min, max);
 }
}  

2014/03/17

Java Practice: Generics

從今天開始,預計把發給敝公司新人的 Java Practice 題目,release 在此給大家參考。Java 的初學者可以試著練習看看,老手也可溫故知新喔!

首先是 Java Generics 之應用,請在 ________ 填入正確宣告,使程式可以正常運作:
class TwoTypeParas <T,V> {
    T ob1;
    V ob2;

    TwoTypeParas(T o1, V o2) {
        ob1 = o1;
        ob2 = o2;
    }

    void showTypes() {
        System.out.println("Type of T is " + ob1.getClass().getName());
        System.out.println("Type of V is " + ob2.getClass().getName());
    }

    T getob1() {
        return ob1;
    }

    V getob2() {
        return ob2;
    }
}

public class TwoTypeParaTest {
    public static void main(String args[]) {
        TwoTypeParas______ tgObj = new TwoTypeParas______(88, "Generics");
        tgObj.showTypes();

        int v = tgObj.getob1();
        System.out.println("value: " + v);

        String str = tgObj.getob2();
        System.out.println("value: " + str);
    }
}

2013/12/16

ETL 概念、應用及工具簡介

企業裡面常有資料處理、轉換或整合的需求。好的資料管理工具雖然不一定能讓你上天堂,不好的工具卻肯定會讓你住病房。「ETL 資料轉換作業」是「資料管理」中最基礎的應用,本篇就來說說 ETL 的基本概念,它有何應用,以及市場上常見的工具。

ETL 是什麼

  • ETL 代表資料由資料來源端擷取 (Extract) 出來,經過轉換 (Transform),再載入 (Load)到目的端的資料傳輸過程。
  • Extract -- 從各種不同的資料來源中,將資料擷取出來。傳統上資料來源是來自於交易型資料庫。
  • Transform -- 對資料進行適當的轉換,如型態轉換、字串相連、彙總運算等等。這個步驟在 ETL 中不一定要執行。
  •  Load -- 將資料載入目的端;目的端通常是為了報表產製及商業智慧分析而最佳化的資料倉儲。


 

 ETL 的應用情境

  • 同步不同資料庫的資料。
  • 資料清理,移除錯誤資料。
  • 將資料載入資料倉儲以便後續分析, 如進行 OLAP 或 Data Mining 之應用。

 

使用 ETL 工具的優勢

使用 ETL 工具最大的優勢,在於可把傳統上需要透過手工方式開發的資料轉換程式碼,轉為由 ETL 工具去進行設定或設計,如此可大量減低資料轉換作業的建置時間及成本。

目前大部分開發人員還是使用自行開發的指令,來處理資料的整合作業。要透過這種方式來建立商業智慧系統,需要開發人員需具備一定的專業能力,還要費時費力的進行開發及除錯。

對於資料庫管理人員而言,若不使用外部工具,要連通不同種類的資料來源並不簡單。況且一旦外部資料來源改變,或者要加入新的資料來源,那這種勞心勞力自行開發的工作又要整個重來一次。使用 ETL 工具,將能簡化這種繁複瑣碎的工作。而良好的資料轉換流程之圖形介面設計工具,甚至可將這類操作變成樂趣。

 

ETL 工具簡介

以下來說說一些業界比較常用的 ETL 工具:

Informatica PowerCenter

  • Informatica 公司所提供的同名商業化套裝資料整合軟體。
  • 建立於 1993 年,主要業務即為資料整合。
  • 依據 Gartner Dataquest 的報告,它在資料整合領域具有最高的市占率。
  • 它提供了大量的套件供企業進行系統整合,並能連接到大量的新一代或既有的資料來源。
  • 提供良好的作業設計及監控介面,功能強大,但人員必須經過訓練才能上手。
  • 單價昂貴,顧問服務費用高。
  • 無縫整合著名的「下推優化」ELT 方法,使用資料庫的服務資源來進行資料轉換作業,效能優良,可以應用於大規模的系統。

    Pentaho Kettle (PDI)

    • Pentaho 是一家商業化的公司,約始於 2001 年,他們基於 Java 開發了一套開源 BI 套件,使用者社群人數眾多。 其中包含了一個 ETL 軟體,稱為 Kettle (或稱為 Pentaho Data Integration/PDI)。
    • 透過中介資料趨動 (metadata-driven) 的方式來設計資料轉換流程,而其使用介面功能完善且易於操作。不需像 Informatica 那樣大的前期投入。
    • 其作業設計及轉換使用了兩種腳本文件:Transformation 和 Job。Transformation 進行資料的轉換作業,以 Javascript 撰寫,Job 則用來控制整個作業流程。
    • 具有作業分派的功能 (需要一個像 cron 的分派器),可以透過分散式部署建立 Pentaho 群集,並能運行部署在 slave servers 上的遠程任務。
    • 擁有資料品質管理功能,可以撰寫自定義的 SQL 查詢,Javascript,和正則表達式。 
    • 從 4.3 版開始,改採 Apache 授權。參考 Pentaho changes ETL license for big data push -- Kettle 4.3, available under the Apache License Version 2.0, can ingest, output, manipulate and report on data from Apache Cassandra, Hadoop HDFS, Hadoop MapReduce, Apache Hive, Apache HBase, MongoDB and Hadapt’s Adaptive Analytical Platform.

    Talend

    • Talend 是一個開源碼的資料整合軟體, 大概啟始於 2006 年 10 月。
    • 採用程式碼產生器的方式來建立資料轉換作業,它將產生的 Java 或 Perl 程式碼佈署於伺服器執行。
    • 其 GUI 操作介面是建立在 Eclipse RCP 平台之上。
    • 使用者社群人數沒有 Pentaho 多,但在國外有許多商業公司進行支援。像著名的 Jaspersoft (Jasper Report 開發者) ETL 工具就是採用 Talend ETL。

    Trinity

    • Netpro 公司所出產的商業化資料管理整合軟體。
    • 包含 Data Management (即 ETL)、JCS (作業控制系統,用來排程及分派作業),以及 Metadata (管理資料源與資料轉換作業會用到的資料庫、資料表及欄位資訊) 三個部分。
    • 其最新版支援 BigData Management, 能連接到 Hadoop HDFS, Hbase 等 BigData 資料儲存體,亦能執行 Pig 與 HiveQL 操作。
    • 提供以 Web 為基礎的操作介面,資料流程設計工具及作業執行監控工具都能透過 Java Web Start 即時自網頁上即時啟動,整體配套措施相當完善。
    • 採分散式多 Agent 架構,可以簡易的 scale-out.
    • 還包含 Data Profile, Impact Analysis, Data Protection 等各種資料管理軟體,實用性相當高。