星期五, 5月 06, 2011

Restful Web Service 定義

記錄Restful相關教學文章。

Reference:
Rest and restful web service
Restful wiki
什麼是REST跟RESTFul?

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



其他你感興趣的文章

Related Posts with Thumbnails