程式碼高𠅙

顯示具有 programming 標籤的文章。 顯示所有文章
顯示具有 programming 標籤的文章。 顯示所有文章

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);
    }
}

2012/09/14

你所想像不到的 Javascript

/**
 * 這是一篇我在 N 年前所寫的 Javascript 教材,近來隨著 Node.js 及 Mobile web 
 * 的熱潮興起,Javascript 又再度走紅,因此再把它重新發佈,希望能對用到的人
 * 有所幫助。
 */
 
這不是一篇教你如何在網頁中應用 JavaScript 的教材。這是一篇讓你明瞭看似簡單的 JavaScript,其實其核心語法功能強大。我將在這篇文章中說明 JavaScript 物件導向的特性,並說明如何透過這些特性,達到傳統程式語言 (C++/Java) 所難以完成的功能。
 
Written by Edward Hsieh/謝鎮澤
 
January 04, 2002 -- 1st Edition
January 04, 2009 -- 2nd Edition
 
Object and JavaScript
 
一般談到 Object-Oriented,皆會提到物件導向語言必須具有的三個特性,即封裝、繼承及多型。這三種特性中,若缺少了繼承的特性、則稱為 Object-Based。
 
Javascript 與其說是物件導向語言,倒不如說它是以物件為基礎的程式語言,但它極為動態的程式設計風格,卻能模擬出物件導向的特性。這種作法與大家所熟悉的,以類別 (class) 為基礎的靜態物件導向語言大不相同。
 
在 Javascript 中有五種基礎的物件型態,包含 undefined, object, boolean, number, 以及 string。以下的範例可供驗證這五種基礎型態:
 
alert (typeof(X));
alert (typeof(null));
alert (typeof(true));
alert (typeof(123));
alert (typeof('abc'));
 
除了上述五種基礎類型,使用者還可自訂型態,而這些自訂的型態,都是「以物件為基礎」的。
 
Create Objects in JavaScript
 
在 Javascript 中建立物件的方法相當簡單。直接看個例子:
 
var main = new Object;     // 建立新物件
main.x = 123; // 設定物件成員變數(屬性)之一
main["y"] = "XYZ"; // 設定物件成員變數(屬性)之二
alert(main["x"]); // 取得物件屬性並輸出
alert(main.y);    
 
可以看到在 JavaScript 中,main.x 與 main["x"] 這兩種語法是通用的。其實在其他語言中,這兩種表示法的語意並不相同。我稍後再作說明。
 
List All Members in an Object
 
這是 JavaScript 的必殺技,使用 JavaScript 的人務必要學會這個技巧。底下函式可以傳回一個物件的所有成員的字串表達式,包括物件中的屬性及方法。在物件導向程式設計中,這種技術叫 reflection。
 
function listMember(main) {
   var s = "";
   for( key in main ) // 使用 in 運算子列舉所有成員
   s += key + ": " + main[key] + "\n";
   return s;
}
 
範例碼中的 key 會對應到物件中的屬性名稱,如 "x" 或 "y",而 main[key] 則對應到屬性值。
 
說這項技巧是必殺技的原因是,你可以透過這項技巧,將物件封裝的黑箱打開來,看看裡面藏有什麼東西。我常用這項技巧來看看 IE 與 Mozilla 的 DOM 物件模型有何不同。試試看下面呼叫範例,就可以知道這項技巧的強大了:
 
var ary = [123, "abc"];
alert (listMember(ary));
alert (listMember(document.location));
 
Construct Object with Initial Value
 
要在建立物件的同時指定物件初始值,必須先透過 function 建立一個「原型物件」(或稱為 constructor),再透過 new 運算子建立新物件。例如以下程式碼會建立一個二維陣列的原型,再產生一個新的二維物件。
 
function Array2DVar(x,y) {     // 定義二維陣列原型
   this.length = x;
   this.x = x;        // x 維度長度
   this.y = y;        // y 維度長度
   for(var i = 0; i < this.length; i++)  // 初始各元素值為 null
   this[i] = new Array(y);    // this 代表物件本身
}
 
var a2dv = new Array2DVar(10, 10);   // 建立新的 10*10 的二維陣列
a2dv[1][3] = "ABC";       // 設定二維陣列元素值
a2dv[2][6] = "XYZ";
a2dv[9][9] = 1000;
 
alert( a2dv[1][3]);  // 取得二維陣列元素值,並顯示出來
alert( a2dv[2][6]);
alert( a2dv[9][9]);
 
Initial Array Object
 
在 JavaScript 中陣列也是物件 (其實近代多數語言中陣列也都是物件,只有像 C 或 Assembly 這類古老的語言才不把陣列看成物件),因此也可以用 constructor 的語法來建構。當然 JavaScript 還提供了 [] 語法,以更方便建構陣列,範例如下:
 
a = new Array("abc", "xyz", 1000); // constructor 語法,或
a = ["abc", "xyz", 1000]; // 陣列標準語法
 
陣列的元素可以是簡單的資料、其他物件,或是函數。舉個例子來在陣列裡面放函式:
 
b = [ // 使用函式作為陣列元素
   function () { alert("這個好玩!") },
   function () { alert("再按一次離開!") },
   function () { alert("再來一次!") },
   function () { alert("最後一次!") }
];
 
for (var i = 0; i < b.length ; i++)
   b[i]();
 
最後一個 for 迴圈是個有趣的應用。由於 b 陣列中現在存放的所有元素都是函式,因此我們可以對 b 的每個元素進行呼叫。
 
Object as Association Array
 
關連陣列 (Assocation Array) 又稱作 Map 或 Dictionary,是一種物件容器,其中可以放置許多的 key-value pair,以存取子物件。在 JavaScript 中,物件本身就可以作為關連陣列。以關連陣列的方式初始化物件的範例如下:
 
obj1 = {"a" : "Athens" , "b" : "Belgrade", "c" : "Cairo"};
alert(obj1["a"]); // 顯示 Athens
 
obj2 = {
   name: "Edward",
   showName: function() { alert(this.name); }  // 使用函式作為物件屬性
}
 
obj2.showName();  // 顯示 Edward
obj2.age = 23; // 屬性可以動態加入
 
其中 obj1 儲存了三個子元素,其鍵 (key) 為 "a", "b" 與 "c",而值 (value) 為 "Athens", "Belgrade" 與 "Cairo"。obj2 中 showName 鍵所對應的值為 function,因此 obj2.showName() 即為函式呼叫。
 
Object as Return Value
 
雖然 Javascript 的函式只能傳回一個變數,但你卻可以將傳回值設定為物件,達到傳回 1 個以上變數值的效果:
 
function a () {
   return [32, 17];
}
 
b = a();
alert( b ); // 或
alert(a());
 
function pixel () { return {"x": 32, "y":17}; }
 
point = pixel (); alert (point.x + "n" + point.y); // 或 alert (pixel().x + "n" + pixel().y);
 
Delegation Function Object
 
函式也是物件,只是其中包含的是程式的邏輯。這項特性可拿來作為委任式的程式設計,亦即使用委任函式當作另一函式的參數:
 
function doloop(begin, end, func) { // 這個函式是個 iterator
   for (var i = begin; i < end; i++) {
       func(i);
   }
}
 
function func1(i) { // 印出 ** n **
   document.writeln("** " + i + " **");
}
 
doloop(1, 10, func1); // 印出 1o 行 ** n **
 
doloop(20, 29, function(i) { // 印出 10 行 ## n ##
   document.writeln("## " + i + " ## ");
});
 
Object = Properties + Behaviors
 
古有明訓:程式 = 資料結構 + 演算法。而物件是建構程式的基本單位,自然的具有相同的性質。物件除了有屬性 (property),也可具有操作 (behavior),也就是函式。
 
假如我們要使用一維陣列來模擬二維陣列,那麼就無法使用 ary[x][y] 這種表示法來設定或取得陣列成員。不過我可以定義一個 set 方法來設定成員變數,而以 get 方法來取得成員變數值。原型函式定義如下:
 
function Array2D(x,y){      // 以一維陣列模擬二維陣列的原型物件
   this.length = x * y;      // 陣列總長
   this.x = x;         // x 維度長度
   this.y = y;         // y 維度長度
   for(var i = 0; i < this.length; i++)  // 初始各元素值為 null
       this[i] = null;
   this.get = function(x,y){      // 成員函式:取得陣列第 [x,y]個元素值
      return this[x*this.x + y];
   }
    
   this.set = function(x,y,value){  // 成員函式:設定陣列第 [x,y] 個元素值
   this[x*this.x + y] = value;
}
}
 
我們接著來使用它:
 
var a2d = new Array2D(10, 10);    // 建立新的「二維」陣列
 
a2d.set(1, 3, "ABC");   // 設定「二維」陣列元素值
a2d.set(2, 6, "XYZ");
a2d.set(9, 9, 1000);
 
alert( a2d.get(1,3) );  // 取得「二維」陣列元素值,並顯示出來
alert( a2d.get(2,6) );
alert( a2d.get(9,9) );   
 
Member Function Outside of Constructor
 
我們也可以將物件成員函式寫於原型物件之外。以下的 Array2D 物件與上一個範例中的 Array2D 物件有相同的作用,只不過這次是寫在原型物件之外。
 
function Array2D(x,y){      // 以一維陣列模擬二維陣列的原型物件
   this.length = x * y;      // 陣列總長
   this.x = x;         // x 維度長度
   this.y = y;         // y 維度長度
   for(var i = 0; i < this.length; i++)  // 初始各元素值為 null
       this[i] = null;
   this.get = Array2DGet; // 用這種方式把成員函式掛進來
   this.set = Array2DSet;
}
 
function Array2DGet(x,y){      // 成員函式:取得陣列第 [x,y] 個元素值
return this[x*this.x + y];
}
 
function Array2DSet(x,y,value){    // 成員函式:設定陣列第 [x,y] 個元素值
this[x*this.x + y] = value;
}
 
Dynamic Object Function
 
這裡說明如何為一個已定義物件,動態的加上其他操作的方法。
 
如果一物件已定義完成,而您也使用它來建立了新的物件,這時候您想為原型物件增加新的操作 (而不修改原型物件的原始碼),讓所有該物件的複本都能使用該操作,該如何達成呢?方法是使用物件的 prototype 屬性。以下這個例子,為 Array 這類 Object 在執行期加入一個 max 方法,以取得陣列元素之最大值 (修改自微軟 jscript.chm之範例):
 
function array_max(){      // 定義求取 Array 最大值之函式
   var i, max = this[0];
   for (i = 1; i < this.length; i++){
       if (max < this[i])
           max = this[i];
   }
   return max;
}
Array.prototype.max = array_max;   // 在 Array 原型中加入 max 函式
 
上面的程式碼,首先建立一個 array_max 方法,以求取陣列之最大元素。接著將這個方法設定給 Array 原型物件。
 
var x = new Array(1, 2, 3, 4, 5, 6);  // 透過 Array 建構子建立一陣列
                                 // 想求取 x 中某一元素之最大值
var y = x.max( );       // 取得 x 之最大元素
 
Dynamic Mix In
 
假如物件 source 有 mathod1, method2 兩個函式;而另一物件 target 有 methodA 及 methodB 兩個函式。現在我想把 source 的所有特性 (feature) 匯入到 target 中,我們可以撰寫一個 mixin 函式如下,來達到這裡所說的功能:
 
function mixin(target, source) {
   if( typeof source == "object")
       for( value in source )
           target[value] = source[value];
}
 
這個 mixin 函式可以動態的為 target 加上另一物件的所有操作。這種 Mix in 的功能可是 C++/Java 的 static type 語言所望塵莫及的。完整的應用範例如下:
 
function listMember(main) {
   var s = "";
   for( key in main ) // 使用 in 運算子列舉所有成員
       s += key + ": " + main[key] + "\n";
   return s;
}
 
function main(){              // main 之建構子
   this.name = "main";
   this.methodA = function() {};
   this.methodB = function() {};
}
var dynamic = {
   method1: function() {},
   method2: function() {}
}
function mixin(target, source) {
   if( typeof source == "object")
       for( value in source )
           target[value] = source[value];
}
obj = new main();
mixin(obj, dynamic);   // 匯入 dynamic 物件之所有功能
alert(listMember(obj));
 
Singleton Object
 
用 associate array 的語法來建立 singleton, 用 function contructor 的語法來建立可多重複製的原型物件
 
Inheritance Through Functions
 
function superClass() {
 this.supertest = superTest; //attach method superTest
}
 
function subClass() {
 this.inheritFrom = superClass;
 this.inheritFrom();
 this.subtest = subTest; //attach method subTest
}
 
function superTest() {
 return "superTest";
}
  
function subTest() {
 return "subTest";
}
 
 
var newClass = new subClass();
 
alert(newClass.subtest()); // yields "subTest"
alert(newClass.supertest()); // yields "superTest"