星期一, 6月 27, 2011

[jQuery plugin] How to sorting JSON Array

原理是使用javascript的sort()函數,此函數也提供讓使用者自訂sort function。
詳細介紹可參考這篇:Sorting a JavaScript array using array.sort()

這裡列的範例取自於Sorting a JSON Array,將以下code貼到你的網頁上即可看結果了。
<script type="text/javascript">
    var arr = [
      { "ID": 135, "Name": "Fargo Chan", "Address": "34, Baker Street" },
      { "ID": 432, "Name": "Aaron Luke", "Address": "BLDG 1, J Street" },
      { "ID": 252, "Name": "Dilip Singh", "Address": "Hotel J, SE" }
    ];

      // Before Sorting
      document.write("<b>Before Sorting </b><br/>");         
      for (var n = 0; n < arr.length; n++) {
          document.write(arr[n].ID + ' ' + arr[n].Name + '<br>');
      }

    // ascending order
    function SortByID(x,y) {
      return x.ID - y.ID; 
    }


    function SortByName(x,y) {
      return ((x.Name == y.Name) ? 0 : ((x.Name > y.Name) ? 1 : -1 ));
    }

    // Call Sort By Name
    arr.sort(SortByName);

    document.write("<br/><b>After Sorting </b> <br/>");   
    for(var n=0;n<arr.length;n++){
      document.write(arr[n].ID + ' ' + arr[n].Name + '<br>');
    }

</script>


可重覆使用的範例:參考至How to sort a JSON array ?
Here's a more flexible version, which allows you to create reusable sort functions, and sort by any field
var sort_by = function(field, reverse, primer){

   reverse = (reverse) ? -1 : 1;

   return function(a,b){

       a = a[field];
       b = b[field];

       if (typeof(primer) != 'undefined'){
           a = primer(a);
           b = primer(b);
       }

       if (a<b) return reverse * -1;
       if (a>b) return reverse * 1;
       return 0;

   }
}

Now you can sort by any field at will

// Sort by price high to low
homes.sort(sort_by('price', true, parseInt));

// Sort by city, case-insensitive, A-Z
homes.sort(sort_by('city', false, function(a){return a.toUpperCase()}));



可以改寫成jQuery plugin的寫法:
(function($) {
 $.extend({
  sortBy : function(objects, field, reverse, fieldValueFunc) {
   //ASC or DESC
   //if reverse is true, data will be sorted using DESC
   reverse = (reverse) ? -1 : 1;
   //init sort func
   var sortFunc = function(elA, elB) {
    
    //get value by field name
    elA = elA[field];
    elB = elB[field];
    
    if (typeof (fieldValueFunc) != 'undefined') {
    
     elA = fieldValueFunc(elA);
     elB = fieldValueFunc(elB);
    }
    //return element comparison value
    if (elA < elB)
     return reverse * -1;
    if (elA > elB)
     return reverse * 1;   
    return 0;
   };
   //call sort() method using sortFunc
   objects.sort(sortFunc);
  }
 });

})(jQuery);

使用方式
$.sortBy(arr,"ID",false,parseInt);

[Java] Reading InputStream

如何使用Java 讀取InputStream資料。

//預設編碼為ANSI(ASCII)
  BufferedReader in = new BufferedReader(
          new InputStreamReader(inputStream));
  String currentLine = null;
  while((currentLine = in.readLine()) != null){
   System.out.println("currentLine" + currentLine);
  }

可指定編碼格式UTF-8
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream,"UTF-8"));

[Java] Base64 Encoder

1. 下載所需的Jar檔。(這裡我們是使用Apache的commons-codec套件)

2. import org.apache.commons.codec.binary.Base64;

3. 使用Base64 Class進行編碼與解碼
Base64 base64 = new Base64();
//使用Base64進行字串編碼
String encodeString = new String(base64.encode("This is source string.".getBytes()));
//輸出結果將為"VGhpcyBpcyBzb3VyY2Ugc3RyaW5nLg=="
System.out.println(encodeString);
//使用Base64進行字串解碼
String decodeString = new String(base64.decode(encodeString.getBytes()));
//輸出結果將為"This is source string."
System.out.println(decodeString);

Reference:
Java Base64 Encode & Decode(編碼和解碼)

[Java] Read Microsoft XLS using JDBC

import java.sql.*;

public class MainWindow {
 public static void main(String[] args) {
  try {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   Connection con= DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=d:/desktop/test.xls");
   Statement st=con.createStatement();
   ResultSet rs= st.executeQuery("select * from [Sheet1$]");//Sheet1是工作表名稱
   while(rs.next()){
    System.out.println(rs.getInt("id")+" "+rs.getString("name"));
   }
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 
  
 }

}

Reference:
Apache POI - Code Sample
Handle Excel files

星期一, 6月 13, 2011

regular expression 正則式筆記

蒐集常用的正則式,不定期更新。

Regex 所使用的符號彙整


記號說明
字元代表該字元, 例如輸入 a 就代表那個地方應該出現 a 這個字元
^限制字串必須出現於行首, 例如 ^a 表這串字必須以 a 開頭; 如果 a 出現在其它地方, 都不算數
$限制字串必須出現於行末, 例如 a$ 表這串字必須以 a 結尾; 如果 a 出現在其它地方, 都不算數
\將特殊字元還原成字面意義的字元, 例如 \( 代表 ( 這個符號, \\ 代表 \ 這個符號; 這種表示法適用於 (, ), [, ] 等在 Regex 有特殊意義的字元
^某字元以外的任何字元, 必須包在中括號裡面。例如 [^a] 表示 a 除外的任何字元或符號, [^a\t] 表示 a 和 tab 除外的任何字元或符號
-字元集合中可使用 - 來指定字元的區間, 必須包在中括號裡面。例如 [a-z] 表示從 a 到 z 的英文小寫字元, [1-3] 表示從 1 到 3 這三個數字之一
+其前的字元或字元集合出現一次或一次以上, 例如 a+
?其前的字元或字元集合可出現一次或不出現, 例如 a?
*其前的字元或字元集合可出現任何次數或不出現, 例如 a*
(...) 用以括住一群字元,且將之視成一個集合, 通常用來集合表示多個檢核式
{n}重複 n 次
{n,m}重複 n 到 m 次
{n,}至少重複 n 次
[]其中之一字元可出現可不出現,例如 [abc] 表示不論出現 a 或 b 或 c 都算符合
|代表「或」, 例如 (Sun|Mon|Tue|Wed|Thu|Fri|Sat), (日|一|二|三|四|五|六) ; 必須以左右括號括住
. (句點符號)代表除了換行符號 (\n) 以外的任一字元。如果要包括換行符號,請使用 [\s\S]
\w (\W)代表任何英文(以外的) 字元 - 請注意, 數字字元也被承認
\s (\S)代表空白 (以外的) 字元
\d (\D)代表數字 (以外的) 字元
\b (\B)代表位於文字邊界的 (以外的) 字元, 例如 \bA 可以檢核出 AB, A\b 可以檢核出 BA, \bAA\b 可以檢核出 AA
\r代表換行字元 (或稱 CR, Carriage Return)
\n代表換行字元 (或稱 LF, Line Feed; 通常和 \r 一同出現, 所以一般以 \r\n 代表換行, 但根據我的測試, 無論使用 \r 或 \n 或 \r\n 都會得到相同的結果, 但唯獨不能寫成 \n\r, 但建議使用 \r?\n)
\t代表 TAB 字元 (或稱 HT, Horizontal Tab)
\(代表左括號
\)代表右括號
\x以十六進位字元碼代表某個字元; 例如 [\x21-\x7E] 可代表所有看得到的字元 ([\x20-\x7E] 則包括空白字元)。不過注意 \x 之後要使用兩個數字, 不足兩個數字者請補 0, 例如 \x01
\1, \2...(Backreference Constructs) 表示出現過的群組; 例如 "(\d)(\D)" 樣式中有兩個群組, 若使用 "(\d)(\D)\1" 可檢出 "2A3"; 若使用 "(\d)(\D)\2+" 則可檢出 "2AB"; 餘此類推
\k同上, 但適用於命名的群組; 例如 "(?\d)(?\D)\k" 亦可檢出 "2A3"
\p{Lu} (\P{Lu})檢出大寫(非大寫)的字母, 例如 (?-i:\p{Lu}) 可檢出字串中所有大寫字母, 而 (?-i:\P{Lu}) 可檢出所有非大寫 (包括數字、空白等) 的字母


找出所有非特殊字元
[^\W_]+

找出特殊字元
[\W_]+

找出HTML Tag
<([\s\S]+)?>

驗證是否符合a-z A-Z 0-9 中文字
[a-zA-Z0-9\u4e00-\u9fa5]+

Reference:
過濾特殊字元
[入門][Regex] Regular Expression 詳論
正则表达式:英文、中文、数字、下划线

星期二, 6月 07, 2011

[Java] Upload file using Jersey

目前使用Jersey接收上傳檔案只能使用HttpServletRequest來接收上傳成功!!
尚未解決使用@FormDataParam無法上傳的錯誤!!待解
 //目前會HTTP Status 415 - Unsupported Media Type大爆炸
 @POST
 @Path("/simpleupload2")
 @Consumes(MediaType.MULTIPART_FORM_DATA)
 public void simpleUpload2(
   @FormDataParam("username") final  String username,
   @FormDataParam("filedata") final  InputStream file,
   @FormDataParam("filedata") final  FormDataContentDisposition disposition){
  
  System.out.println("username:" + username);
 }

以下範例是使用Apache FileUpload Module 來取得上傳的檔案物件
@POST
 @Path("/simpleupload")
 @Consumes(MediaType.MULTIPART_FORM_DATA)
 public void simpleUpload(
   //@Context UriInfo ui,
   @Context HttpServletRequest request
  ){

  String fileRepository = "D:\\";
  if (ServletFileUpload.isMultipartContent(request)) {
   FileItemFactory factory = new DiskFileItemFactory();
   ServletFileUpload upload = new ServletFileUpload(factory);
   List<FileItem> items = null;
   try {
    items = upload.parseRequest(request);
   } catch (FileUploadException e) {
    e.printStackTrace();
   }
   if (items != null) {
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
     FileItem item = iter.next();
     if (!item.isFormField() && item.getSize() > 0) {
      System.out.println("File is found.");
      String fileName = processFileName(item.getName());
      try {
       String savePath = fileRepository + fileName;
       System.out.println("savePath:" + savePath);
       item.write(new File(savePath));
      } catch (Exception e) {
       e.printStackTrace();
      }
     }else{
      System.out.println("getFieldName:" + item.getFieldName());
      System.out.println(item.getString());
     }
    }
   }
  }
 }

Reference:
Multiple file upload using RESTful web service (Jersey)

星期一, 6月 06, 2011

[Java] UnicodeFormatter

/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 


import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;

public class UnicodeFormatter  {

   static public String byteToHex(byte b) {
      // Returns hex String representation of byte b
      char hexDigit[] = {
         '0', '1', '2', '3', '4', '5', '6', '7',
         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
      };
      char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
      return new String(array);
   }

   static public String charToHex(char c) {
      // Returns hex String representation of char c
      byte hi = (byte) (c >>> 8);
      byte lo = (byte) (c & 0xff);
      return byteToHex(hi) + byteToHex(lo);
   }
}

星期三, 6月 01, 2011

[Java] Fake UTF-16

static public String CoverterUtf8ToFakeUtf16(String utf8String) throws UnsupportedEncodingException {
    
    byte[] inputBytes = utf8String.getBytes("UTF-8");
    printBytes(inputBytes,"input bytes:");
    
    ArrayList list = new ArrayList();
    //convert input bytes to utf-16
    for(int i=0;i<inputBytes.length;i++){
     list.add(new Byte("00"));
     list.add(inputBytes[i]);
    }
    
    byte[] returnByte = new  byte[list.size()];
    for(int i=0;i<returnByte.length;i++){
     returnByte[i] = (Byte)list.get(i);
    }
    
    returnByte = new String(returnByte, Charset.forName("UTF-16")).getBytes("UTF-8");
    printBytes(returnByte,"return bytes:");
    
    String fakeUtf16 = new String(returnByte,Charset.forName("UTF-8"));
    printBytes(fakeUtf16.getBytes("UTF-8"),"fakeUtf16 bytes:");
    
    return fakeUtf16;
   }

Testing
public void fakeUtf16(InputStream requestBodyStream ) throws UnsupportedEncodingException {
String requestBODY = RequestBODY.get(requestBodyStream,Charset.forName("utf-8"));
System.out.println("requestBODY:" + requestBODY);
String fakeUtf16 = UnicodeFormatter.CoverterUtf8ToFakeUtf16(requestBODY);
System.out.println("fakeUtf16:" + fakeUtf16);
}
Console 輸出訊息
--fakeUtf16--
charset:UTF-8
requestBODY:中
input bytes:[0] = 0xe4
input bytes:[1] = 0xb8
input bytes:[2] = 0xad
return bytes:[0] = 0xc3
return bytes:[1] = 0xa4
return bytes:[2] = 0xc2
return bytes:[3] = 0xb8
return bytes:[4] = 0xc2
return bytes:[5] = 0xad
fakeUtf16 bytes:[0] = 0xc3
fakeUtf16 bytes:[1] = 0xa4
fakeUtf16 bytes:[2] = 0xc2
fakeUtf16 bytes:[3] = 0xb8
fakeUtf16 bytes:[4] = 0xc2
fakeUtf16 bytes:[5] = 0xad
fakeUtf16:中
fakeUtf16:[0] = 0xfe
fakeUtf16:[1] = 0xff
fakeUtf16:[2] = 0x00
fakeUtf16:[3] = 0xe4
fakeUtf16:[4] = 0x00
fakeUtf16:[5] = 0xb8
fakeUtf16:[6] = 0x00
fakeUtf16:[7] = 0xad
--/fakeUtf16--