星期六, 11月 26, 2011

[jQuery Plugin] jQuery Validator: Dynamic message

剛好有需求要動態變更錯誤提示訊息,以下範例是目前的寫法請參考, 關鍵的行數為this.settings.messages[element.name]

星期四, 11月 24, 2011

Special Characters Supported for Passwords

Name of the CharacterCharacter
at sign@
percent sign%
plus sign+
backslash\
slash/
single quotation mark'
exclamation point!
number sign#
dollar sign$
caret^
question mark?
colon:
comma.
left parenthesis(
right parenthesis)
left brace{
right brace}
left bracket[
right bracket]
tilde~
grave accent
This character is also known as the backquote character.
The grave accent cannot be reproduced in this document.
hyphen-
underscore_

Reference:

星期日, 11月 20, 2011

URL decode/encode 觀念題

做網頁傳遞中文時常會用到URL decode/encode,
混亂的 URLEncode 說明了為什麼要使用URLEncode,
有興趣可以去讀一下。

[[Javascript 茶包筆記]] 小數點運算

JavaScript 要取到小數點下的指定位數,要四捨五入時有內建的toFixed()函數可使用,

例:
var num = new Number(13.3714);
document.write(num.toFixed());
document.write(num.toFixed(1));
document.write(num.toFixed(3));
document.write(num.toFixed(10));

結果:
13
13.4
13.371
13.3714000000

星期四, 11月 03, 2011

[Javascript] URL decode encode

使用Javascript來做URL編碼,請依需求來評估使用哪一種方法!!

Javascript escape, encodeURI, encodeURIComponent Encode後的結果,整理如下表:(請參考這裡)
文字類型英文數字中文Unescaped charactersReserved charactersScore
原始字串AZaz01-_.!~*'();,/?:@&=+$#
escape後AZaz01%u5803-_.%21%7E*%27%28%29%3B%2C/%3F%3A@%26%3D+%24%23
encodeURI後AZaz01%E5%A0%83-_.!~*'();,/?:@&=+$#
encodeURI
Component後
AZaz01%E5%A0%83-_.!~*'()%3B%2C%2F%3F%3A%40%26%3D%2B%24%2

星期三, 10月 19, 2011

[jQuery Plugin] jQuery File Upload FAQ

這篇主要記錄自已使用jQuery File Upload的一些問題,如果要基本的使用方法請參考這篇:


Q1: 上傳成功時發生Empty file upload result的情況
A1:V5 的伺服端接收上傳成功的訊息後,需回傳一個JSON Array,即時只有一個上傳檔案。例如:{["uploadfilename":"helloworld.jg"]}

Q2:使用Jsp無法順利jQuery樣版無法順利套用
A2:解法在這篇討論

Uploaded filename and size is not displayed in JSP???
The plugin template use the same syntax of Expression Language (EL) used by jsp and so ${name} and ${sizef} variables are evaluated in jsp and replaced with "" and "" . To avoid this you have to replace ${name} and ${sizef} with ${"${name}"} ${"${sizef}"}.

Q3: Firefox 4 fails when uploading empty file

 can confirm this issue with the basic File Upload plugin and Firefox 5.
However this seems to be a bug in the implementation of the FormData/XHR implementation of Firefox/Gecko.
Feel free to submit a bug report here: https://bugzilla.mozilla.org
IE跟Chrome上傳0KB檔案都是正常的。

Q4: How to cancel upload queues?
 $("#yourbutton").click(function (e) {
  //invoking a click event on all the upload row cancel buttons.
  $(".cancel button").click();
 });

星期二, 10月 04, 2011

[jQuery Plugin] jQuery Templates 樣版

由於AJAX技術愈來愈多人使用,搭配回傳的JSON格式產生UI已經是非常普遍的做法,
但如果搭配樣版的觀念來動態Bind資料,想必是更省事,最近使用的jQuery-File-Upload元件,
也使用樣版來產生UI。

以下是一些學習連結:
jQuery Templates Plugin筆記1by黑暗執行緒 

[JSP] JSP頁面引用bigd-5編碼的Javascript

想不到也有人遇到過同樣的問題XD~


Reference:[Tips] 在 utf-8 頁面 使用 big5 的 Javascript 檔之前在上線網站的時候, Clark 遇到在 utf-8 的網頁下要include big5 的 js 的問題,當時出現的問題是由於big5 的 js 檔中有中文字,include 到 utf-8 的 page 上時就造成 javascript error 或文字變成亂碼,當時趕著上線,所以就選擇將原來的 js 另存一份成為 utf-8 格式的 js 。就這樣使用了到現在將近一年,最近正在改這個 js 檔時發現為什麼不延用一份共用的 js ,而去另外自已建一份呢?一測試之下終於回想到當初的原因。由於在這陣子 Clark 也處理過類似問題,得到的結論是,在語法中下 charset="big5" 就可以讓 browser 不依照該 page 的 encoding 去做解譯,所以顯示的結果就正常了!

經過修改,顯示一切正常,其他Browser也沒有發現問題,上線!

星期一, 10月 03, 2011

[Tomcat] Linux系列關掉所有java程式後啟動tomcat流程

本篇記綠同事的流程XD

//首先砍掉所有運行的java程式
>pkill -9 java

//查詢java的程序還在不在,有的話會列process id。
>pgrep java

//使用替代pgrep java類似的指令
>ps aus | grep java

//開啟tomcat
>./startup.sh

星期一, 9月 26, 2011

[Java,Tomcat] 第一次使用DBCP就上手

本篇文章記錄安裝Tomcat的DBCP(Data Base Connection Pool)過程

測試環境:
Apache Tomcat/6.0.29
JVM1.6.0_21-b06
Connector/J 5.1.5 (the official JDBC Driver)mysql-connector-java-5.1.5-bin.jar

星期五, 9月 23, 2011

[jQuery plugin] jQuery Validator addMethod always return false

今天在做驗證帳號是否已存在的時遇到的問題。 當觸發驗證規則時,由於是非同步的呼叫,會造成Validator總是會回傳驗證失敗。 只要將jQuery 預設的ajax方法,多帶入async:false即可。


$.validator.addMethod( "conflictaccount" , function(value,element){ console.log("account:" + value); var isValidate = true; $.checkUserAccount( { async:false,//avoid value of return is false endpoint : HOSTNAME, ticket : TICKET, uid: value, callback:function(data){ if(data.verify){ //confilct account // console.log("confilct"); isValidate = false; }else{ // console.log("Not Conflict"); isValidate = true; } } }); // console.log("isValidate:" + isValidate); return isValidate; });

 註:$.checkUserAccount裡面是call $ajax的方法。

星期四, 9月 08, 2011

[Linux] Tomcat logs

Tip:/APP/TOMCAT安裝目錄

使用Putty查看Tomcat logs


1.進入logs directory
$cd /APP/TOMCAT/logs

2.監看logs
#持續刷新logs,缺點看的數量會被putty的視窗限制住
$tail -f catalina.out

or

#-n 加行數查看
$tail -n 1000 catalina.out

or

#加上grep搜尋
$tail -n 1000 catalina.out | grep 搜尋的字

清空所有Logs
$echo > catalina.out

星期二, 9月 06, 2011

[Eclipse] 設定字型大小

Eclipse設定字型大小也太難找了吧Orz
步驟:
Preferences->General->Appearance->Colors and Fonts->Basic->Text Font(達陣了Q_Q)



星期日, 9月 04, 2011

[PHP] Appserv 重新設定port

當你的windows上已經讓IIS佔用80 port之後,
就正常無法運行Apache(TOMCAT預設是佔用8080)。


所以必需重新設定Apache使用的port。
步驟如下:

第一步:俢改httpd.conf
打開AppServ > Apache2.2 > conf > httpd.conf 
修改Listen的80
#Listen 12.34.56.78:80
Listen 80 



第二步:重新啟動Apache
改後去程式集 Appserv Control Server by Service > Apache Restart

[PHP] Facebook login 整合

整理一些有關於facebook的整合相關文章:

http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/
PHP SDK & Graph API base Facebook Connect Tutorial
[教學] Facebook API PHP SDK 基本篇. Facebook API PHP SDK Basic introduce.
Facebook Connect 搭配 API 提供帳號管控教學

星期五, 9月 02, 2011

[jQuery] 錯誤元素呼叫.html()引起的"對方法或內容存取發出未預期的呼叫"

今天在做多國語言切換的時候遇到的怪異bug
起因原來是呼叫.html取代語言檔字串時,目標元素不存在。
 <b>頁面配置:
</b> <label class="profile_add_title" for="name">Name</label> <input id="organization" name="organization" type="text" class="profile_input" />

//如果元素不支援.html方法時,會導致呼叫方法錯誤
$("#organization").prev().html(global_company_name);

星期一, 8月 22, 2011

[Eclipse] 關掉Java Script Validator

Eclipse一直跳出Javascript Validator擾民的訊息,可以從點選專案後按Properties->Builders->JavaScript Validator(uncheck)就可以了!!


星期一, 8月 08, 2011

Hp pavilion tx 1000 drivers for win7

最近幫朋友重灌Hp pavilion tx 1000筆電,由於是老電腦找Drivers就特別麻煩,
有需要的參考看看,不過目前的FN鍵跟觸控面版還是Driver不了。

星期日, 8月 07, 2011

[Java] System.properties


From System Properties you can find information about the operating system, the user, and the version of Java.
The property names (keys) and values are stored in a Properties structure. (See Properties). A Properties object can also be used to store your own program properties in a file.


Reference:
Java: System Properties

星期五, 8月 05, 2011

[Java] Servlet file upload filename encoding (中文亂碼)

解決中文檔名亂碼問題:在init ServletFileUpload呼叫setHeaderEncoding指定編碼為utf-8,
就能正確取出中文了

ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
List items = null;
   try {
    items = upload.parseRequest(request);
//    System.out.println("item is added.");
   } catch (FileUploadException e) {
    System.out.println("FileUploadException:" + e.getMessage());
   }
   if (items != null) {
//    System.out.println("items count:" + items.size());
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
                                  FileItem item = iter.next();
                                  String filename = item.getName();
                                }
                        }
Reference:
servlet file upload filename encoding

星期四, 7月 28, 2011

[C#] HttpWebRequest request limitation

最近實作多執行緒上傳檔案的測試工具時,
發現不管執行幾個執行緒同時只會有二個連線數存在。
這是.net預設的連線數,透過以下設定即可。
ServicePointManager.DefaultConnectionLimit = 10;
網路上有人建議最大連線數不要超過1024,最好的效果是512。
另外也可以從app.config來設定最大連線數

硬碟單位換算


單位換算問題:適用於各語言的實作XD
10 MB = 10485760 Bytes

Explanation: 10 MB = 10*1024 KB = 10*1024*1024 Bytes = 10485760 Bytes

As we have,

1 KB = 1024 Bytes

1 MB = 1024 KB


Read more: 

星期二, 7月 19, 2011

[jQuery Plugin] 第一次用jQuery Validator就上手

常用到的客戶端的表單欄位驗證,在此簡單記錄一下:
本測試使用v1.8.1

[Java] Resize Image as JPG

簡單的影像Resize程式

public class ResizeImage {

 static public byte[] resizeImageAsJPG(byte[] pImageData, int pMaxWidth)
   throws IOException {

  // Create an ImageIcon from the input image byte[]
  ImageIcon imageIcon = new ImageIcon(pImageData);
  int width = imageIcon.getIconWidth();
  int height = imageIcon.getIconHeight();

  // If the image is larger than the max width, we need to resize it
  if (pMaxWidth > 0 && width > pMaxWidth) {
   // Determine the shrink ratio
   double ratio = (double) pMaxWidth / imageIcon.getIconWidth();
   height = (int) (imageIcon.getIconHeight() * ratio);
   width = pMaxWidth;
  }

  // Create a new empty image buffer to "draw" the resized image into
  BufferedImage bufferedResizedImage = new BufferedImage(width, height,BufferedImage.SCALE_SMOOTH);
  // Create a Graphics object to do the "drawing"
  Graphics2D g2d = bufferedResizedImage.createGraphics();
  g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC);
  // Draw the resized image
  g2d.drawImage(imageIcon.getImage(), 0, 0, width, height, null);
  g2d.dispose();
  // Now our buffered image is ready
  // Encode it as a JPEG
  ByteArrayOutputStream encoderOutputStream = new ByteArrayOutputStream();
  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(encoderOutputStream);
  encoder.encode(bufferedResizedImage);
  byte[] resizedImageByteArray = encoderOutputStream.toByteArray();
  return resizedImageByteArray;
 }
}

[jQuery] File upload using AJAX form

最近使用jQuery Form Plug & jQuery File Upload上傳檔案,如果將Server Response的content-type設定application/json的話,因為元件上傳使用iframe來達到ajax form的效果,因此在Firefox和IE瀏覽器會跳出下載的Dialog。如果要回傳json格式來交換資料的話,只能將content-type設定text/plain或text/html,等接到ajax callback事件後,再將json的字串利用JSON.parser()轉換到json object即可。


後紀:使用text/plain會被多加pre element進去

Reference:Frequently Asked Questions
Internet Explorer prompting to download a file after the upload completes

The file upload plugin makes use of an Iframe Transport module for browsers like Microsoft Internet Explorer and Opera, which do not yet supportXHR file uploads.
Iframe based uploads require a Content-type of text/plain or text/html for the JSON response - they will show an undesired download dialog if the iframe response is set to application/json.
Please have a look at the Content-Type Negotiation section of the Setup instructions.

星期五, 7月 15, 2011

[C#] Settings

To Write and Persist User Settings at Run Time
  1. Access the user setting and assign it a new value, as shown in the following example:
    Properties.Settings.Default.myColor = Color.AliceBlue;
    
  2. If you want to persist changes to user settings between application sessions, call the Savemethod, as shown in the following code:
    Properties.Settings.Default.Save();

星期一, 7月 11, 2011

[Java] Keytool 相關蒐集

[Java] 實作HTTPS Request

最近的專案為了確保網路資料傳輸的安全性,使用了SSL來加密,
原本實作的RESTful Client(Java HttpsURLConnection)模擬request時,伺服器回應了以下錯誤:

javax.servlet.ServletException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:418)
 com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
 com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

Google了一下找到了這篇文章:

星期一, 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"));

星期四, 6月 23, 2011

[Java] Logging

Reference:
Java Gossip: Logging 的層級
Logger使用方法[JAVA]

[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--

其他你感興趣的文章

Related Posts with Thumbnails