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

星期日, 5月 15, 2011

[JQuery Plugin] AJAX Form using Jquery

使用jquery達到ajax form submit的需求。
請參考這個元件jQuery Form Plugin

javascript:
$(function(){ 
     // bind to the form's submit event 
  $("#formAJAX").ajaxForm({
    url: "http://localhost:8080/webproject/yourpage" ,
    beforeSubmit:  showRequest,
    type:      "get",
    dataType:  "json", 
    success:   showResponse
  });
 });
 
 //pre-submit callback 
 function showRequest(formData, jqForm, options) { 
   var queryString = $.param(formData); 
   alert(queryString);
   return true; 
 } 

 //post-submit callback 
 function showResponse(responseText, statusText, xhr, $form)  { 
  alert(responseText);//單純的Text
 } 



//發現用showResposne的時候,responseText才會被直接轉換成JSON Object function showResponse(responseText) html page:
<form id="formAJAX" >
<input id="doSubmit" type="submit" name="button" value="submit" />
</form>

[Javascript] 使用javascript取代所有比對的字串

在javascript的replace函式如果不使用正則表示式的格式的話,只能取代第一個符合的字串規則。
請參考以下這篇文章:

The JavaScript function for String Replace replaces the first occurrence in the string. The function is similar to the php function str_replace and takes two simple parameters. The first parameter is the pattern to find and the second parameter is the string to replace the pattern with when found. The javascript function does not Replace All...

str = str.replace(”find”,”replace”)

To ReplaceAll you have to do it a little differently. To replace all occurrences in the string, use the g modifier like this:
str = str.replace(/find/g,”replace”)

Reference:
JavaScript String Replace All

星期三, 5月 11, 2011

[JSP] JSP-防止瀏覽器快取網頁

今天工作處理IE8異常cache網頁導致ajax異常,多虧FIDDLER這個好用的http tool。

以下為參考的資料:

JSP技巧篇---防止瀏覽器快取網頁
(資料來源:Java Server Page 學習網 -- http://www.jsp.mlc.edu.tw )

瀏覽器為了加速使用者的瀏覽速度,常會將瀏覽過的網頁快取到硬碟,
下次瀏覽同一頁時,便去硬碟裡面去找,但現在的網頁常是動態的,
為了避免使用者抓到硬碟內過期的資料,JSP可用下面的方式來防止瀏
覽器快取住網頁,此方法便可保證使用者到這個網頁時始終都可看到
1.JSP語法

<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-cache");
//prevents caching at the proxy server
response.setDateHeader("Expires", 0);
%>

2.也可以用以下的HTML語法,可用在靜態網頁上
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">

201203/14更新
今天仔細測了一下,就算加了這些Header可以清Cache,但並非馬上就會更新。
需要多按幾次重新整理才會馬上更新!!

[Eclipse] 安裝Subclipse讓 Eclipse 加入 Subversion (SVN) 的版本控制功能

記錄如何安裝Subclipse這個好用的版本控制工具,安裝方法請參考下面連結。
讓 Eclipse 加入 Subversion (SVN) 的版本控制功能

Change log:2012/3/25

星期一, 5月 09, 2011

[JQuery Plugin] Checkbox 按鈕skin

想要在Web上面使用像iphone的enable按鈕嗎?
以下這個外掛可以達到你的需求!!


Jquery check box 
Lightweight custom styled checkbox implementaion for jQuery 1.2.x and 1.3.x.
How to use:
$("input:checkbox").checkbox({
  empty: 'images/empty.png'
 });
PS:支援checkbox的disabled、checked,會讓UI樣式不一樣。

增加按鈕是否被按下,請使用bind的方法
adds new checkbox events "check", "uncheck", "disable", "enable", ready to use in jQuery.bind() method

$("input:checkbox").bind('check',function(){
//被按了
});

http://widowmaker.kiev.ua/checkbox/

星期三, 5月 04, 2011

[Javascript] 字串處理 (String Operations)

Javascript 字串處理 (String Operations)

尋找字串(search)
stringObject.search(searchstring)
stringObject.search(尋找的字串)
大小寫必須相符

var str = "test String";
alert(str.search("Str"));
alert(str.search("str"));
輸出結果:5
輸出結果:-1


[Json] How to decode json

本文記錄json中文編碼/解碼的問題
如果要將編輯過的json中文字串,只要將\取代成%,再使用javascript的unescape function就可以解碼。
var encodejson = "\u8521\u5927\u75E3";
encodejson = encodejson.replace("\\","%");
document.write("json decode :" + unescape(encodejson) + "
");

var test = "蔡大痣";
document.write("test:" + test + "
");
document.write("to edcode from test:" + escape(test) + "
");
document.write("to decode from test:" + unescape(test) + "
");


輸出:

json decode :蔡大痣
test:蔡大痣
to edcode from test:%u8521%u5927%u75E3
to decode from test:蔡大痣

[JQuery Plugin] Apprise 對話視窗

跳出輸入方框視窗
input:true設定是否要顯示輸入框
r:為輸入的值
apprise("Change " + ctlName + " password?", {"verify" : true,"input":true}, function(r) {
    if (r) {
     console.log("user clicked Yes");
     if(typeof(r) == "string"){ 
      console.log("new password:" + r);
      $.changePassword({
       uid:ctlName,
       oldPassword:"admin",
       newPassword:r,
       callback:changePasswordEventHandler
      });
     }
    } else {
     console.log("user clicked No");
    }
   });
Reference:
Apprise
The attractive alert alternative for jQuery

星期二, 5月 03, 2011

[jQuery] 快快樂樂jQuery-常用基礎語法篇

本文記錄常用的Jquery語法:

綁定多個id事件
$("#id1,#id2,#id3").click(function(){..........}); 

取得select的值:
$("#targetlist option:selected").text();

使用selector eq(index)設定select某一option被選取:
$("#selectElem option:eq(1)").attr("selected","true");

input的disalbed控制:
//disabled
$('#target').attr("disabled", true); 
//enable
$('#target').removeAttr("disabled"); 

取得元素 tag name
var elemName = $("#target").attr("tagName");

判斷元素是否存在
if ( $("#target").length > 0 ) {

...
...

}

display:block or none
$("#target").css("display","block");
$("#target").css("display","none");

偵測鍵盤,keycode請參考這篇
$("#target").keydown(function(event){
     console.log(event.keyCode);
 });

判斷Checkbox是否被選取
$("#target").attr("checked");//checked: true, unchecked: false

取得radio按鈕的值
$("input[name=gender]:checked").val()

[Javascript] Math Functions

javascript 數學函式
Math.abs(a)     // the absolute value of a
Math.acos(a)    // arc cosine of a
Math.asin(a)    // arc sine of a
Math.atan(a)    // arc tangent of a
Math.atan2(a,b) // arc tangent of a/b
Math.ceil(a)    // integer closest to a and not less than a 無條件進位
Math.cos(a)     // cosine of a
Math.exp(a)     // exponent of a
Math.floor(a)   // integer closest to a, not greater than a 無條件捨去
Math.log(a)     // log of a base e
Math.max(a,b)   // the maximum of a and b
Math.min(a,b)   // the minimum of a and b
Math.pow(a,b)   // a to the power b
Math.random()   // pseudorandom number 0 to 1 (see random number examples)
Math.round(a)   // integer closest to a (see rounding examples) 四捨五入
Math.sin(a)     // sine of a
Math.sqrt(a)    // square root of a
Math.tan(a)     // tangent of a

[JQuery Plugin] Jeditable

本文介紹如何使用Jeditable來實作inline editing。
html source
<div id="talk_sth" >
What's on your mind?
</div>

javascript

$(function(){
//在加了event屬性後似乎會跟onblur事件有衝突。
 $("#talk_sth").editable(
   editableEventHandler, 
     {
        indicator : "",
           tooltip   : "Move mouseover to edit...",
            placeholder : "What's on your mind?",
           //event     : "mouseover",
           type      : "textarea",//編輯元素的樣式
//           submit    : "OK",//顯示ok按鈕
//           cancel    : "Cancel"//顯示cancel按鈕
           onblur : "submit"
     }

    );
});

//透過editableEventHandler處理post json data
function editableEventHandler(value, settings){
    console.log("update status:" + value);
    var endpoint = HOSTNAME + "/alfresco/service/slingshot/profile/userstatus?alf_ticket=" + TICKET;
    var requestBODY = "{'status':'" + value + "'}";
    var result = requestBODY;
    console.log(requestBODY);
    $.ajax({
     type: "POST",
     url: endpoint,
     contentType: "application/json",
     dataType: "json",
     processData: false,
     data: requestBODY, 
     success: function(data){
      alert(data);
     },
     error: function(){
      
     }
  }); 
    //important
    return value;
}
Reference:
Jeditable - Edit In Place Plugin For jQuery

[WordPress] query_post methods

query_posts('page_id=179'); //指定單頁 (page) 的文章編號
query_posts($query_string . "&order=ASC"); //用變數帶入並指定排序
query_posts("cat=-3"); // 3 這個類別編號的不顯式
query_posts('p=5'); //指定單篇文章 (post) 編號
query_posts('pagename=about'); //指定單頁 (page) 的文章主題
query_posts('pagename=parent/child'); //傳回單頁 (page) 的子類別
query_posts('cat=1'); //指顯示這個類別編號的文章
query_posts('category_name=product); //用類別名稱去撈出文章
query_posts('tag=cooking'); //用標籤來撈文章
query_posts('tag=bread,baking'); //可以多標籤來撈文章
posts_per_page=10 每個網頁顯示的文章數目;
query_posts('showposts=5&offset=1'); //秀出5則
query_posts('cat=3&year=2004'); //參數組合查詢

[Javascript] 正則式驗證圖片

常常會用到的javascript 正則式,以下為驗證上傳圖片格式。

$("#filedata").change(function(){
console.log($("#filedata").val());
var selectFile = $("#filedata").val();
var re = /^.*\.(jpg|png|gif|bmp)/;
if(selectFile.match(re) == null){
alert("File format is error.");
$("#updateAvatar").attr("disabled", true);

}else{
$("#updateAvatar").removeAttr("disabled");
}
});

Reference:
JavaScript Regex 的 字串比對(Match) 與 取代(Replace)
Regular Expression (RegExp) in JavaScript

[Json] Convert JSON Object to String javascript

you can user browser native function JSON.stringify to do this
var foo = {};
foo.bar = "new property";
foo.baz = 3;
var jsonString = JSON.stringify(foo);

星期六, 4月 30, 2011

[Java] 快快樂樂安裝Tomcat in Window

本文記錄如果在Window安裝Tomcat伺服器
1.下載tomcat 這裡,下載解壓放在你想放的目錄下
本文是統一放在Apache自動安裝的AppServ目錄下,以方便管理
Tip:現在還有提供Windows Service Installer方便Windows的用戶

2.安裝JAVA JDK 這裡
目前版本為Java 6

3.設定JAVA 環境變數
我的電腦->右鍵->內容-> 進階系統設定(Vista) ->進階 -> 環境變數

在PATH變數里的最後面貼上你JAVA安裝的路徑

;C:\Program Files\Java\jdk1.6.0_19
(注意每個變數前面要用分號隔開)

新增下列所有的環境變數值
變數名稱                                               變數值
JAVA_HOME                                        C:\Program Files\Java\jdk1.6.0_19\
CLASSPATH                                       C:\Program Files\Java\jdk1.6.0_19\lib
CATALINA_HOME                                C:\AppServ\apache-tomcat-6.0.32

註:第三個是選擇性設定

4.測試你的java環境
C:\Program Files\apache-tomcat-6.0.32\bin>java -version
java version "1.6.0_19"
Java(TM) SE Runtime Environment (build 1.6.0_19-b04)
Java HotSpot(TM) 64-Bit Server VM (build 16.2-b04, mixed mode)

5.啟動你的Tomcat

C:\Program Files\apache-tomcat-6.0.32\bin>startup.bat
關掉的話就是將命令提示字元(終端機)關掉即可

6.測試Tomcat
瀏覽器開啟http://127.0.0.1:8080/ 測試tomcat是否有啟動,讀到Tomcat首頁你就完成了 :)

星期六, 4月 23, 2011

[JAVA] 快快樂樂學JAVA JDBC 連接 MySQL

JDBC連接MySQL
使用JDBC連接資料庫存取資料時,必須執行以下三個步驟:

1.用DriverManager載入及註冊適當的JDBC驅動程式
Class.forName("com.mysql.jdbc.Driver");

如果發生Driver not found錯誤訊息改改用
Class.forName("com.mysql.jdbc.Driver").newInstance();

2.用JDBC URL定義驅動程式與資料來源之間的連結,並且建立一個連結物
//option1
String jdbcUrl = "jdbc:mysql://[hostname]:[port]/[dbname]?user=[username]&password=[pwd]";
Connection conn = DriverManager.getConnection(jdbcUrl);

//option2
String jdbcUrl = ""jdbc:mysql://[hostname]:[port]/[dbname]";
Connection conn = DriverManager.getConnection(jdbcUrl,"username","password");

3.建立一個sql陳述句,並利用它來執行SQL語法
Statement stmt = conn.createStatement();


執行陳述句有三種方法:

方法一:取回結果集

ResultSet rs = stmt.executeQuery("sql語法")

//取得每一列資訊
while(rs.next()){
//取得這筆資料的結果
rs.getString(1);
rs.getInt(2);
}


方法二:新增、更新、刪除等等使用

//updateRow為執行成功的列數
int updateRow = stmt.excuteUpdate("sql語法");
方法三:單純判斷執行有無成功使用,回傳boolean
bool success = stmt.execute("sql語法");


[JAVA] 快快樂樂學JAVA RESTful Service using Jersey

本文記錄如何在JAVA+TOMCAT下使用Jersey快速建立RESTful WebService :
感謝Owen血尿付出。

第一步:安裝Eclipse跟Tomcat 6.0.32
第二步:下載Jersey Library 1.6。官網http://jersey.java.net/
第三步:將下載的.jar檔放到Tomcat/lib
核心的lib asm-3.1.jar, jersey-core.jar, jersey-server.jar, jsr-311-api-1.0.jar



第四步:開啟Eclipse,新建一個Dynamic Web Project
第五步:修改專案內的YourProjectName/WebContent/WEB-INF/web.xml,新增以下內容

<servlet>
      <servlet-name>JerseyServlet</servlet-name>
      <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
      <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
      <servlet-name>JerseyServlet</servlet-name>
      <url-pattern>/services/*</url-pattern>
 </servlet-mapping>

第六步:第一個HelloWorld Restful API (支援GET / POST)

星期三, 4月 20, 2011

[Linux] 快快樂樂學Linux指令筆記

如何mount裝置內的共享資料夾

1.設定共用資料夾
裝置->共用資料夾->加入共用資料夾

2.在ubuntu建立一個暫存的目錄
$cd /home
$mkdir temp

3.掛載裝置:D_DRIVE為共用資料夾的名稱
#掛載的共享資料夾目錄名稱 ./要掛載的目錄
$sudo mount -t vboxsf D_DRIVE ./temp

4.卸載所有裝置
$umount -a
=====================================================================
Symbol Link

unlink 其實就跟 rm 一樣罷了,當要移除一個 symbolic link ,有時發現怎樣移不掉,一直說 "unkink: my_symbolic_link/ : is a directory" ,這個訊息就跟使用 rm 去移除一個目錄時的錯誤訊息!原來,在移除一個 symbolic link 時,要留意後面不能加個 "/" !這樣,若 symbolic link 是連到一個目錄時,等同於在對那個目錄做 rm 的動作,才會顯示 "is a directory" 訊息。這時可不能一氣之下用 rm -rf !可會將 link 到的目錄給移除掉的!要額外小心。

#目的地是一個檔案
$ ln -s target_file_path my_file_link
$ unlink my_file_link

目的地是一個目錄
$ln -s target_dir my_dir_link
例如:產生在當前目錄下的symbol link
$sudo ln -s /home/temp/mysite.war

$unlink my_dir_link/
$unlink: my_dir_link/: is a directory
$unlink my_dir_link

Done
=====================================================================
MYSQL

#安裝圖形化介面(ubuntu)
$sudo apt-get install mysql-admin

#連接資料庫
$mysql -u root -p

#離開資料庫
mysql>exit


=====================================================================
RM

#移除整個資料夾
$rm -rf 資料夾名

=====================================================================
ifconfig


#列出網路卡資訊
$ifconfig

#設定網路卡ip
$ifconfig eth10 192.168.0.112

=====================================================================
Apache Web Server


#開啟apcahe
$/etc/init.d/httpd start

#關閉apache
$/etc/init.d/httpd stop

#開機啟動檔路徑,可設定開機執行一些shell script指令
$vim /etc/rc.local

=====================================================================
VI

#搜尋
/ <搜尋的字串>

#強制執行存檔
:w ! tee %

#強制離開
:q!


#刪除一行(離開insert模式)
dd

#全刪除
dG



星期二, 4月 19, 2011

[JQuery] getting URL parameters values

/**
 * 
 * get request url parameters and values
 */
(function($) {
 $.extend({
    getUrlVars: function(){
      var vars = [], hash;
      var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
      for(var i = 0; i < hashes.length; i++)
      {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
      }
      return vars;
    },
    
    getUrlVar: function(name){
      return $.getUrlVars()[name];
    }
 });
})(jQuery);

Reference: Get URL parameters & values with jQuery

[JQuery Plugin] 自訂jQuery plugin 教學

記錄jQuery外掛的常見的寫作方法。

第一步:將下面的範例程式複製起來,
這是一個簡單將jQuery物件別名為$號的方法,
可以避免其他Javascript Framework別名衝突的問題!!

(function($) {

})(jQuery);


第一種:我偏好的方式 $.fn與$來擴充jQuery物件的方法
(function($) {
 
//呼叫此方法需要帶入指定的元素,可一定綁定多個元素
   $.fn.helloworld= function() {
        this.each(function(){
             alert('helloworld');
        });
        
    };
    
//不需元素即可呼叫(靜態函式)
    $.helloworld2 = function() {
       alert('helloworld 2');
    };
    
})(jQuery);



第二種:改用extend方法來擴充!!
什麼是extend方法請參考黑大的文章:jQuery extend 的用法

(function($) {
 $.extend({
   helloworld: function(){
    alert('helloworld');
   },
   goodbyeworld: function(){
    alert('goodbyeworld');
   }
 });
})(jQuery);


Reference:
網站製作學習誌 » [jQuery] 自製 jQuery Plugin – Part 1
網站製作學習誌 » [jQuery] 自製 jQuery Plugin – Part 2

星期一, 4月 18, 2011

[Alfresco] login using Jquery

/**
 * authentication
 */

$(function(){
 //dologin
 $("#login_submit").click(function(){
  var username = $("#username").val();
  var password = $("#password").val();
  if(username == "" || password == ""){
   alert("Invalid UserName or Password.");
  }else{
   //call resetful api
   
   var endpoint = "http://localhost:8080/alfresco/service/api/login?u=" + username + "&pw=" + password + "&format=json";
   alert(endpoint);
   $.ajax({
     type: "GET",
     headers: {
                 "Content-Type": "application/json"
     },
     url: endpoint,
     //contentType: "application/json",
     processData: false,
     //data: stringData,
     dataType: "jsonp",
     jsonp:"alf_callback",
     jsonpCallback:"jsonp_callback_login",
     statusCode: {
        404: function() {
          alert('page not found');
        },
     400: function() {
           alert('bad request');
         }
     }
   });
  }
 });
});

function jsonp_callback_login(data){
 alert(data.data.ticket);
}

[Alfresco] alf_ticket VS ticket url parameter

For all the pages under the path /faces/* and Web Scripts with the Web Client authenticator alfresco/wcservice/*, you have to use the ticket parameter.
For all the Web Scripts with a path alfresco/service/ you have to use the alf_ticket parameter and in this case you are using the HTTP Basic Authenticator.



Reference:
http://forums.alfresco.com/en/viewtopic.php?f=4&t=28524

[JQuery] AJAX cross-domain issues

Reference:
jQuery抓取跨網域外的資料(cross-domain) 運用JSONP

[Alfresco] Restful API cross-domain issues

Reference:
Web Scripts:JSON Callbacks



[MSSQL] 安裝錯誤解決方法

問題:升級到 SQL Server 2005 失敗,並出現「安裝程式無法連接到資料庫服務進行伺服器組態。」錯誤訊息。

問題:如果在升級到 SQL Server 2005 期間無法使用通訊埠 1433,則 SQL Server 安裝程式會傳回下列錯誤:

SQL Server 安裝程式無法連接到資料庫服務進行伺服器組態。

解決方案:若要繼續,請終止使用通訊埠 1433 的處理序,並繼續進行 SQL Server 2005 安裝程式:

從命令提示字元執行 netstat -o。
識別使用通訊埠 1433 的應用程式或處理序。
使用 [工作管理員] 來關閉應用程式或終止處理序以釋放通訊埠 1433。
繼續 SQL Server 2005 安裝程式。
如果使用上述步驟仍無法釋放通訊埠 1433,請使用下列其他步驟:

開啟 [控制台] 的 [新增或移除程式]。
選取 [Microsoft SQL Server 2005],再按一下 [變更]。
在 [元件選擇] 頁面上,按一下要升級的 SQL Server 執行個體的選項按鈕,然後按 [下一步]。
在 [功能維護] 頁面上,按一下 [Database Engine],然後按 [下一步]。
按一下 [繼續] 來繼續 SQL Server 2005 的升級作業。

Reference:
對 SQL Server Database Engine 的安裝進行疑難排解

星期四, 4月 14, 2011

md5 image file

string ImageFileName = null;
string StrImageName = null;
string UploadImageFolderPath = Server.MapPath("../Upload/Images/");
string ImageFileExtension;

if (ImageUpload.HasFile)
{
StrImageName = ImageUpload.FileName.ToString();
ImageFileExtension = System.IO.Path.GetExtension(StrImageName);

// GIVE A UNIQUE FILENAME(MD5) TO THE UPLOADED FILE:

MD5CryptoServiceProvider objMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(StrImageName);
bs = objMD5.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();

foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}

StrImageName = s.ToString();

ImageFileName = StrImageName + ImageFileExtension;

// As long as the Image-File-Name is exists in the folder then we are MD5ing again the imgage-file-name:

while (System.IO.File.Exists(UploadImageFolderPath + ImageFileName))
{
MD5CryptoServiceProvider objMD5While = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bsWhile = System.Text.Encoding.UTF8.GetBytes(StrImageName);
bsWhile = objMD5.ComputeHash(bsWhile);
System.Text.StringBuilder sWhile = new System.Text.StringBuilder();

foreach (byte bWhile in bsWhile)
{
sWhile.Append(bWhile.ToString("x2").ToLower());
}

StrImageName = sWhile.ToString();
ImageFileName = StrImageName + ImageFileExtension;
}

ImageUpload.PostedFile.SaveAs(UploadImageFolderPath + ImageFileName);
}

星期三, 4月 13, 2011

圖片檔案hash

string hash = null;
                using (System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
                {
                    System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg;
                    System.Drawing.Image myImage = System.Drawing.Image.FromFile(path + f.ToString());
                    myImage.Save(ms, format);

                    hash = Convert.ToBase64String(sha1.ComputeHash(ms.ToArray()));
                }

星期四, 4月 07, 2011

[ZK] Image setContent using Stream

Aimage stream設定範例
    
URL url = new URL(avatar);
            AImage aimg = new AImage("avatar",url.openStream());
            myPhoto.setContent(aimg);

[Alfresco] upload user avatar using resetful api

Build a uploadavatar.jsp page to test uploadavatar restful api.
The page content is shown as the below:

<form id="avatar" enctype="multipart/form-data"
action="http://ideas-cosa.dyndns.org/alfresco/service/slingshot/profile/uploadavatar?alf_ticket=TICKET_32178fa17bcf3b975e76129dccb78d646466e88d" method="post">
<input type="text" name="username" value="ken"/>
Select a file:
<input type="file" name="filedata" />
<input type="submit" name="button" value="upload" />
</form>

星期二, 4月 05, 2011

HTTP 檔案上傳機制解析 [精華]

HTTP 檔案上傳機制解析 [精華]

[Asp.Net] 重新註冊IIS .NET Framework

以下程式碼為簡單的範例:請自已修正安裝的.net framework路徑

REM This batch file addresses "Server unavailable" error
@echo off

REM "Changing to the Framework install directory"
cd /d C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

echo "Stopping IIS"
iisreset /stop
echo "----------------------"

echo "Stopping the ASP.NET state service if it is running"
net stop aspnet_state
echo "----------------------"

echo "Re-registering ASP.NET"
aspnet_regiis -i
echo "----------------------"

echo "Restarting IIS"
iisreset /start
echo "----------------------"

星期日, 3月 27, 2011

[ZK] How to download file in ZK

 public void onClick$downloadAgent(Event event){
  
  try {
   Filedownload.save("download/xxx.xls", "application/octet-stream");
  } catch (FileNotFoundException e) {
   System.out.println("FileNotFoundException:" + e.getMessage());
  }
  
 }

[Asp.Net] zip and unzip in asp.net using DotNetZip Library

If you want to create a zip in your asp.net.I suggests that you can use DotNetZip Libriay that is very easy to use.You can get more details in the following link :
DotNetZip Library


Create a downloadable zip within ASP.NET. This example creates a zip dynamically within an ASP.NET postback method, then downloads that zipfile to the requesting browser through Response.OutputStream. No zip archive is ever created on disk.

public void btnGo_Click (Object sender, EventArgs e)
{
  Response.Clear();
  Response.BufferOutput= false;  // for large files
  String ReadmeText= "This is a zip file dynamically generated at " + System.DateTime.Now.ToString("G");
  string filename = System.IO.Path.GetFileName(ListOfFiles.SelectedItem.Text) + ".zip";
  Response.ContentType = "application/zip";
  Response.AddHeader("content-disposition", "filename=" + filename);
  
  using (ZipFile zip = new ZipFile()) 
  {
    zip.AddFile(ListOfFiles.SelectedItem.Text, "files");
    zip.AddEntry("Readme.txt", "", ReadmeText);
    zip.Save(Response.OutputStream);
  }
  Response.Close();
}

星期二, 3月 22, 2011

[Alfresco] Create your first web script

if you want to create customize web script in Alfresco.
You will need to understand:
  • XML for expressing the Web Script description
    • <basename>.<httpmethod>.desc.xml
  • Optionally, JavaScript for writing Web Script behaviour
    • <basename>.<httpmethod>.js
  • Freemarker for rendering a Web Script response
    • <basename>.<httpmethod>.<format>.ftl

星期日, 3月 20, 2011

[XSLT] XSLT Note

XSLT(Extensible StyleSheet Language Transformations)
XSLT是一種把XML文件轉換成XHTML文件或是其他的XML文件的語言。
XPath則是可以操控XML文件的語言,XSLT大量的使用此技術。
XSLT文件是利用stylesheet當作root element的XML文件

Reference:
XSLT Tutorial

星期三, 3月 16, 2011

[ZK] How to pass parameter to another zul page

Today i want to pass parameter to another zul page so i find the solution for using "Executions.createComponents".



arg - java.util.Map(Refer to ZK:The User Guide)
The arg argument passed to the createComponents method in the
org.zkoss.zk.ui.Executions class. It might be null, depending on how
createComponents is called.

It is the same as self.desktop.execution.arg.
params.put("name", "John");
Executions.createComponents("/my.zul", null, params);

Then, in my.zul,

...

Notice that arg is available only when creating the components for the included page, say
my.zul. On the other hand, all events, including onCreate, are processed later. Thus, if you
want to access arg in the onCreate's listener, use the getArg method of the
org.zkoss.zk.ui.event.CreateEvent class.


Testing code is the below:
In the a.zul composer.
final Map<String, Object> map = new HashMap<String, Object>(0);
    map.put("userid",detailsUser.getUserName() );

    Window changepasswordWin = null; 
    changepasswordWin = (Window) Executions.createComponents(
      "/admin/change_password.zul", 
      null,
      map);

In teh b.zul composer.(change_password.zul)
Map<String, Object> args = null;
public void onCreate$changePasswordWin(Event e) throws Exception {
  System.out.println("--ChangePassword changePasswordWin--");
 
  CreateEvent ce = (CreateEvent) ((ForwardEvent) e).getOrigin();
  this.args = ce.getArg();
  System.out.println("pass userid:" + this.args.get("userid"));
  
  //do something
  //....

  System.out.println("--/ChangePassword changePasswordWin--");
 }

星期二, 3月 15, 2011

[ZK] Dynamic to add button and listen event

  Button btnModify = new Button("Modify Password");
                //parent is cell of row
  btnModify.setParent(cell);
  btnModify.setImage("/admin/images/btn/modify_key.png");
  btnModify.addEventListener("onClick", new EventListener() {
         public void onEvent(Event event) throws Exception {
          
           //to do something
          
          } 
   });

[ZK] Messagebox EventListener

捕捉Question Messagebox的事件

//popup messagebox
Messagebox.show("Are you sure?",
      "Question", Messagebox.OK | Messagebox.CANCEL,
      Messagebox.QUESTION, new EventListener() {
       public void onEvent(Event event) throws Exception {
        //if clicks ok to do something
        if (((Integer) event.getData()).intValue() == Messagebox.OK) {
         //to do something
        }
       }
      });

星期五, 3月 04, 2011

PHP ZEND Framwork

http://blog.corausir.org/website-design/ausir-1219
http://www.jaceju.net/blog/archives/category/web-development/php/zend-framework/page/2
http://blog.wu-boy.com/2009/03/24/1060

星期二, 3月 01, 2011

[ZK] ZK Eclipse Setting

From: ZK Essentials/Working with the Sample Applications/Setting Up the Applications Using Eclipse

In the fifth step:
"Once the download is complete, go to Window > Preferences > ZK > ZK Packages, click Add File/Directory to add the ZK package downloaded"

The default ZK Package versioin is 3.6.3, so downloaded the latest one which is zk-bin-5.0.5.zip from zk downloads. Then keep following the fifth step to select the downloaded file and then the latest version could be displayed as an option.

其他你感興趣的文章

Related Posts with Thumbnails