星期一, 5月 28, 2012

[Alfresco] Alfresco Namespace

Note: This list will expand / change between now and the next release.
NamespaceCommon PrefixDescription
http://www.alfresco.orgalfGeneral Alfresco Namespace
http://www.alfresco.org/model/dictionary/1.0dData Dictionary model
http://www.alfresco.org/model/system/1.0sysRepository system model
http://www.alfresco.org/model/content/1.0cmContent Domain model
http://www.alfresco.org/model/application/1.0appApplication model
http://www.alfresco.org/model/bpm/1.0bpmBusiness Process Model
http://www.alfresco.org/model/site/1.0stSite Model
http://www.alfresco.org/model/forum/1.0fmForum Model
http://www.alfresco.org/model/user/1.0usrUser model (in repository.jar)
http://www.alfresco.org/view/repository/1.0viewAlfresco Import / Export View
http://www.alfresco.org/model/action/1.0actAction service model
http://www.alfresco.org/model/rule/1.0ruleRule service model
http://www.alfresco.org/ws/service/authentication/1.0authAuthentication Web Service
http://www.alfresco.org/ws/service/repository/1.0repRepository Web Service
http://www.alfresco.org/ws/service/content/1.0contentContent Web Service
http://www.alfresco.org/ws/service/authoring/1.0authorAuthoring Web Service
http://www.alfresco.org/ws/service/classification/1.0clsClassification Web Service
http://www.alfresco.org/ws/cml/1.0cmlContent Manipulation Language
http://www.alfresco.org/ws/model/content/1.0cmWeb Service Content Domain Model
http://www.alfresco.org/ws/headers/1.0hdrSOAP Headers
http://www.alfresco.org/model/workflow/1.0wfWorkflow Model(link is to Alfresco simple workflow model, not generally extended)

[Eclipse] 設定JRE與Tomcat runtime

簡單記錄一下Eclipse設定JRE與Server Runtime擷圖XD

JRE Runtime
Step1: Windows-> Preference
Step2: Java-> Installed JREs


Server Runtime

Step1: Windows-> Preference
Step2: Server-> Runtime Environments
Step3: Add, 新增一個runtime server

Step4: 選擇新的runtime enviornment,範例為tomcat 7.0

Step5: 設定Tomcat安裝目錄
C:\Program Files\Apache Software Foundation\Tomcat 7.0



Step6: 完成,接下來編譯時選擇你要的執行環境即可


phpmyadmin 重新命名資料表

XD找好久
1.點選要修改的資料表
2.之後到瀏覽介面後,按上面的管理
3.資料表選項內,直接將資料表改名為的框框修改就好了

星期二, 5月 22, 2012

[Heroku] Java on Heroku

試玩了一下Heroku,發現自已從本地端的eclipse建Maven專案push上去Heroku後,
app都run不起來。
不過目前Heroku支援了四種template來幫助開發者在上面開發web app。
請參考這個網站:http://java.heroku.com/

•Web app with Spring and Tomcat
•Containerless web app with Embedded jetty
•Web app with Play! Framework
•RESTful API with JAX-RX

[Java] Maven + Eclipse 備忘錄

Maven是什麼?

Maven提供你的是建構環境,或說是建構環境的框架(Framework)。

Maven的主要精神有:


  • 慣例先於設定(Convention over configuration)


舉例來說,在Maven中認為,專案開發遵循應某些慣例,這些慣例像是固定目錄的名稱與架構、固定變數的名稱、固定的建構生命周期(Build lifecycle)等。Maven認為你不應花費時間在這些慣例的設定上,而要將精神放在更重要的工作上。


  • 集中管理相依性(Dependency management)


正如在 簡介 Apache Ivy 中提到的,程式庫的相依性管理是個頭痛的問題,Maven使用集中式管理,提供集中式的貯藏室(Central repository),你要在設定檔案宣告相依的程式庫等資訊,Maven會為你下載相關的檔案。

plugin 為基礎的架構

Maven 提供固定的建構生命周期,像是Default、Clean、Site等。在每個生命周期中,又會分作一些階段(Phase), 像是Default生命周期中,會有Validate、Compile、Test、Package、Integration test、Verify、Install、Deploy等階段,每個階段會有一些相繫結的plugin,Maven本身會有一些預設的plugin,你也 可以在設定檔中依需求宣告想使用的plugin,Maven會自動取得plugin。

專案物件模型(Project Object Model)


在Ant中使用build.xml來定義建構過程中的所有資訊,在Maven中與之對應的是pom.xml,不過pom.xml主要的目的是提供專案資訊,像是專案名稱、組織名稱、相依資訊等。


星期日, 5月 20, 2012

[RoR] 如何連接資料庫

Rails內建的資料庫是採用SQLite,資料庫的設定檔在此目錄下:config/database.yml


# SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000

建立一個Model
$>rails g model users account:string password:string

      invoke  active_record
      create    db/migrate/20120520124738_create_users.rb
      create    app/models/users.rb
      invoke    test_unit
      create      test/unit/users_test.rb
      create      test/fixtures/users.yml

使用migrate建立資料表

$> bundle exec rake db:migrate

==  CreateUsers: migrating ====================================================
-- create_table(:users)
   -> 0.0014s
==  CreateUsers: migrated (0.0015s) ===========================================

新增一個descript欄位到users表格

rails g migration add_descript_to_users
      invoke  active_record
      create    db/migrate/20120520125033_add_descript_to_users.rb


執行migrate將剛新增的欄位加入

$>bundle exec rake db:migrate
==  AddDescriptToUsers: migrating =============================================
==  AddDescriptToUsers: migrated (0.0000s) ====================================


TIP:Rails會知道哪些已經執行過migration,所以只會執行一次


Rake指令集
rake db:create # to create database
rake db:migrate # to create tables based on your migration







星期六, 5月 19, 2012

[RoR] 第一個RoR應用程式: HelloWorld

來個所有程式的第一步吧,HelloWorld

測試環境:
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11.3.0]
Rails 3.2.3
作業1:HelloWorld 起步

星期三, 5月 09, 2012

[Javascript] Prototype 繼承

記錄一些關於Prototype的讀後感:)


Prototype的好處?
Javascript可使用Prototype來擴充類別的方法,
可以增加其效能,可將全部已instances的物件,
全部加上新的方法。

為什麼要用jQuery.fn?
jQuery中的jQuery.fn ($.fn) 其實就是等於 jQuery.prototype,
意即:

$.fn = $.prototype

所以寫外掛的時候就能輕鬆擴充jQuery的函式庫了。

為什麼不直接用$.prototype?


主要在於早期的jQuery.fn裡的每個內容並不使用prototype來實作,
而是採繞行整個物件的方式,
因為物件內的屬性跟方法可能很多,導致速度很慢,
後續版本改用prototype來提升效能,
為避免已存在的外掛程式被破壞。
所以才有會$.fn = $.prototype的別名存在。

Reference:
用javascript的prototype來玩繼承

[jQuery API] Deferred Object

Deferred Object 最大的特色在於處理非同步的狀況時,所執行的 Callback function 可以指定多個,讓程式增加可讀性,舉一個簡單的例子來說明:


Deferred Object 的狀態可分成三種
1. Pending: Operation 處理中
2. Resolve: Operation 處理成功
3. Reject: Operation 處理失敗


Reference:
http://ithelp.ithome.com.tw/question/10090605

星期二, 5月 08, 2012

[jQuery plugin] 使用tinyscrollbar外掛做出iphone/ipad捲軸視窗效果

如果使用iPhone/iPad常常會看到視窗過長的捲軸效果,
現在Facebook也都有一樣的捲軸視窗,
使用tinyscrollbar可以簡單的完成這個效果。




[jQuery Plugin] imagesLoaded偵測圖檔已被讀取

需要偵測圖檔已被讀取完畢的話,可以使用imagesLoaded這個外掛:)

[jQuery API] 偵測元素大小被改變 Detect element resize

先前寫了一個FlickrLinkr小服務,在div添加tinyscrollbar的外掛, 但因為div裡面需要讀取圖檔,當未讀取完的時候,會導致tinyscrollbar的高度不正常(後面被讀取出來的圖檔被div擋住) 可以透過這個可以偵測元素resize的外掛來解決目前的問題:)

[RoR] Ruby on Rails 完整架構圖

RoR完整架構圖,讓你簡單了解RoR MVC架構




Reference:

星期四, 5月 03, 2012

[IIS7] URL rewrite for php

前幾天試著透過Fast CGI想在上面跑phpMyAdmin的專案結果不是很順利(可參考 這篇)
今天換個變通的想法,
利用IIS 7的rewrite的模組來進行轉址~
開始動手設定吧XD

星期三, 5月 02, 2012

UML 又來了 lol

免費的UML圖表工具
http://astah.net/

活動圖:

  • 活動圖是表示流程的大方向面
  • 不要落入描述活動的細節裡面,有細節可再細分第二張活動圖
  • 活動圖應保持易讀性與單純化

http://microbuddy.blogspot.com/2009/03/uml_25.html

循序圖:
http://codingjames.blogspot.com/2009/08/uml-sequence-diagram.html

星期一, 4月 30, 2012

[Ruby] Ruby autocomplete in VIM

http://www.cuberick.com/2008/10/ruby-autocomplete-in-vim.html

[IIS7] IIS7 執行 php專案以及phpMyAdmin

本篇記綠在IIS7上面執行php與phpMyAdmin的安裝心得。
最後可以正確在IIS7上架php的專案(可正常連接mysql),
但目前IIS7執行phpMyAdmin專案在載入mysql.dll模組會錯誤,尚無解Orz~

安裝環境: 
Win7


前置工作:
Appserv安裝apache, php, phpmyadmin


如何在IIS7上執行php設定步驟

接著打開IIS管理工具

Step1:選擇 處理常式對應

Step2:接著點擊 新增模組對應

Step3:
在 要求路徑中 輸入 *.php

類型下拉 選擇 FastCgiModule

執行檔選擇 php5安裝目錄下的 php-cgi.exe

接著名稱取個 PHP for FCGI 即可

點確定,接著將剩餘的步驟都點確定即可完成設定。

Step4:
接著,請到php5安裝目錄下,把php.ini-recommended 改為 php.ini

Step5:
重新啟動www服務,即可運作PHP

星期日, 4月 29, 2012

[jQuery API] Html encode decode

利用jQuery簡單的完成html的編碼跟解碼
function htmlEncode(value){
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}

Reference:
JavaScript/jQuery HTML Encoding

星期三, 4月 25, 2012

[Javascript] 偵測上傳檔案的MIME Type

在前端偵測上傳檔案的MIME Type,不過不實用,因為使用者可以改副檔名來欺騙你。

var mimeType = document.getElementById("filedata").files[0].type; // e.g. image/png

星期二, 4月 24, 2012

[jQuery Plugin] 處理過長文字外掛(Truncate long string in web)

常常遇到在web上要處理文字過長的問題!!
參考了jquery text truncate寫的範例程式:

/**
 * Visual string trimming Trimming with pixel of container
 * 
 * change log:
 * 2012/12/06 use text function to avoid special characters let system crash
 * @author ken tsai 2012/04/06
 */
;
(function($) {

 function htmlEncode(value) {
  
  try{
   return $('<div/>').text(value).html();
  }catch(err){
   $.console("htmlEncode:" + err);
   return valeu;
  }
 }

 function htmlDecode(value) {
  try{
   return $('<div/>').html(value).text();
  }catch(err){
   $.console("htmlDecode:" + err);
   return valeu;
  }
 
 }
 
 $.tirmWithPixel = {};
 
 $.tirmWithPixelHTML = function(options){
  
  var opts = $.extend($.fn.trimWithPixel.defaults, options);
  
  var text = opts.text;
  var pixelLimitWidth = opts.limitPixelLength;
  var tailPattern = opts.tail;
  
  var $container = $("<div/>");
  
  var content = $container.append(
    $.tirmWithPixel({
       text:text,
       limitPixelLength:pixelLimitWidth,
       tail:tailPattern}
    ).clone()).html();
  
  return content;
 };
 
 $.tirmWithPixel = function(options) {

  var opts = $.extend($.fn.trimWithPixel.defaults, options);
  
  var text = opts.text;
  var pixelLimitWidth = opts.limitPixelLength;
  var tailPattern = opts.tail;
  
  var $container = $("<span></span>");
  
  //if element don't add to body
  //you can't get width from current element
  $container.text(text).appendTo("body");
  
//  $.console("original:" + $container.text());
  
  $container.trimWithPixel({
          limitPixelLength:pixelLimitWidth,
          tail:tailPattern});
  
  var $copyContainer = $container.clone();
  
  //remove from body
  $container.remove();
  
//  $.console("trim:" + $container.text());
  
  return $container;
 };

 $.fn.trimWithPixel = function(options) {

  // combine options
  var opts = $.extend($.fn.trimWithPixel.defaults, options);
  var pixelLimitWidth = opts.limitPixelLength;
  var tailPattern = opts.tail;
  var callback = opts.callback;
  
  this.each(function(i, obj) {

   var $strContainer = $(this);// current element
   
   var cText = $strContainer.text();// original text of container(without html encode)
   var oText = cText;// record original text(with html encode)
   
   //$.console("oText:" + oText);
   
   var $vistualSpan = $("<span style='white-space:nowrap;'></span>");
   $vistualSpan.text(cText);
   
   //$.console("span context:" + $vistualSpan.html());
   $strContainer.html($vistualSpan);
   
   //$.console("$strContainer html:" + $strContainer.html());
   
   var spanWidth = $vistualSpan.width();
   
   //$.console("spanWidth:" + spanWidth);
   
   // elem width is more than limit pixel length
   if (spanWidth > pixelLimitWidth) {
    var max = 0;
    while ((spanWidth = $vistualSpan.width()) > pixelLimitWidth) {
    
     cText = cText.substring(0, cText.length - 1);
     
     $vistualSpan.text(cText);
     cText = $vistualSpan.text();
     
     //debug
     /*
     max++;
     if(max > 100){
      $.console("[trimWithPixel] Exceed max limitation..");
      return;
     }*/
      
    }

    cText = cText + tailPattern;
    
    if (callback && typeof(callback) === "function") {
     callback({oText:oText,cText:cText});
    }else{
     $strContainer.attr("title", oText);
     $strContainer.text(cText);// using text fun to unescape html
    }
   } else {
    
    // not trimming
    //$.console("not trimming");
    
    if (callback && typeof(callback) === "function") {  
     callback({oText:oText,cText:cText});
    }else{
     $strContainer.attr("title",oText);
     $strContainer.text(oText);// using text fun to unescape html tag
    }
   }
  });
 };

 // default options
 $.fn.trimWithPixel.defaults = {
  limitPixelLength : 125,
  tail : "..."
 };

})(jQuery);

[TOMCAT] TOMCAT在WIN7自動啟動


最近在WIN7安裝了TOMCAT7,每次WIN7開機的時候都會跳這個視窗。


原來是WIN7安全性的問題,將CONFIGURE TOMCAT的特殊權限等級內的系統管理員的身分執行此程式打勾即可

[Ruby] MacOSX 安裝Ruby

這篇文章記錄自已安裝Ruby環境的心得,
自已裝過一遍才會遇到不一樣的問題lol

系統環境:
Mac OSX 10.7.3

[SEO] Google Sitemap

Sitemap 範例
<urlset xmlns:image="http://www.sitemaps.org/schemas/sitemap-image/1.1" xmlns:video="http://www.sitemaps.org/schemas/sitemap-video/1.1" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url> 
    <loc>http://www.example.com/foo.html</loc> 
    <image:image>
       <image:loc>http://example.com/image.jpg</image:loc> 
    </image:image>
    <video:video>     
      <video:content_loc>http://www.example.com/video123.flv</video:content_loc>
      <video:player_loc allow_embed="yes" autoplay="ap=1">http://www.example.com/videoplayer.swf?video=123</video:player_loc>
      <video:thumbnail_loc>http://www.example.com/thumbs/123.jpg</video:thumbnail_loc>
      <video:title>適合夏季的燒烤排餐</video:title>  
      <video:description>完美排餐烹調秘訣</video:description>
    </video:video>
  </url>
</urlset>

Sitemap 標記定義

標記是否必要說明
必要包含與 Sitemap 所含網址相關的所有資訊。
必要包含與特定網址相關的所有資料。
必要指定網址。如果是圖片與影片,請指定到達網頁 (亦稱為播放網頁或參照網頁)。此網址必須是獨一無二的。
選擇性網址的最後更新日期,格式為 YYYY-MM-DDThh:mmTZD (時間值為選擇性)。
選擇性用於提示網頁大概多久更新一次。有效值如下:
  • always:表示網頁每次遭到存取時皆會變更。
  • hourly
  • daily
  • weekly
  • monthly
  • yearly
  • never:此值適用於封存的網址。
選擇性描述網站上某個網址相對於其他網址的優先順序。優先順序範圍介於 1.0 (非常重要) 到 0.1 (完全不重要) 之間。這項設定不會影響您的網站在 Google 搜尋結果的排名,因為這個值是相對性的,只能和您網站中的其他網頁比較,因此即使將某個網頁指定為高優先順序 (或將所有網址指定為相同的優先順序),也不會提升您的網站在搜尋結果中的排名。此外,如果您將所有網頁的優先順序設定為相同的值,則設定不會產生任何作用。

星期一, 4月 23, 2012

[jQuery API] $.data()

很多時候我們會將物件的屬性值繫結在元素的屬性上面(我從以前就習慣這樣lol)。
然後再透過$('selector').attr('key') 拿取,
不過這個方法會造成dom過長( 也會降低seo的內容代碼比。 ),
不過常常遇到需求變更時又要多一個屬性,感覺很不方便。

建議使用jQuery提供的$.data()方法來儲存你的資料
jQuery.data( element, key, value )
  • element - 必要的參數,這個屬性就是我們要塞入資料的節點。
  • key - 欲塞入資料的鍵值,往後取得資料使用。
  • value - 欲塞入的資料,可為任何的資料型態。

jQuery.data(div, "test", { first: 16, last: "pizza!" });
$("span:first").text(jQuery.data(div, "test").first);
$("span:last").text(jQuery.data(div, "test").last);


如果你已經確定要綁定在某個元素上的話請用$.data()效能會比較好。
另外這方$.data(),也可以用在非元素上的資料存儲
var usersList = {};//store user list with key/value
$.data(usersList,user.userName,user);//user is json object

要取得資料的話也蠻方便的
var userData = $.data(usersList,userName);//userName is key
var userRowindex = userData.rowIndex;//某一個屬性值


Reference:
$.fn.data 與 $.data效率比較 
jQuery.data()
利用 jQuery 的 data 方法取數值時的陷阱

星期日, 4月 22, 2012

[Window7] Create symboic link in Window7


如何在Window7建立Symbolic link,參考至How to create symbolic link in windows 7

C:\Windows\system32>mklink
Creates a symbolic link.
 
MKLINK [[/D] | [/H] | [/J]] Link Target
 
/D      Creates a directory symbolic link.  Default is a file
symbolic link.
/H      Creates a hard link instead of a symbolic link.
/J      Creates a Directory Junction.
Link    specifies the new symbolic link name.
Target  specifies the path (relative or absolute) that the new link
refers to.


Example:
To create a symbolic link named MyDocs from the root directory to the \Users\User1\Documents directory, type:
mklink /D \MyDocs \Users\User1\Documents

[RoR] RoR 初探


最近開發接觸的語言,擷錄Ruby on Rails 實戰聖經心得 XD


Ruby on rails(ROR)
Rails的哲學包括以下指導原則:
  • 不要重複自己(DRY: Don’t Repeat Yourself) – 撰寫出重複的程式碼是件壞事
  • 慣例勝於設計(Convention Over Configuration) – Rails會預設各種好的設定跟慣例,而不是要求你設定每一個細節到設定檔中。
  • REST是網站應用程式的最佳模式 – 使用Resources和標準的HTTP verbs(動詞)來組織你的應用程式是最快的方式(我們會在路徑一章詳細介紹這個強大的設計)

Rails是採用Ruby開發的網頁框架,David Heinemeier Hanson(DHH)在2004年發明,具有以下功能:
  • MVC(Model-View-Control)模式
  • 支援單元測試和整合測試
  • 支援Ajax和RESTful介面
  • ORM機制
  • 支援各種最新的業界標準像是HTML5、JQuery

星期六, 4月 21, 2012

[Java] TOMCAT 啟動執行 Serverlet


  1. Initialize your class in servlet's init() method. You may add  attribute to make sure your servlet is created at application startup and not on first access.
  2. Add ServletContextListener and use contextInitialized() callback method. UseServletContext#setAttribute to store created object for future use.

星期四, 4月 19, 2012

[jQuery API] ScrollTop 回傳值為0



遇到一個需求需要將body一開始先設style為display:none;

之後再適當時機的時候再將此屬性移除~

結果會導致IE8再擷取ScorllTop時回傳的值都為0,

原以為是ScorllTop api不支援IE8的問題,但結果是因為加了display:none;
在這篇討論中有人提到:http://api.jquery.com/scrollTop/
Warning: .scrollTop() will return 0 (and setting it to anything won't work) if the element, or a parent element, is set to "display:none;". I had to apply my .scrollTop() logic after the element was shown.

[jQuery plugin] element center

控制元素置中的center plugin,常用在跳出式的視窗,
如果遇到parent元素,設定style="display:none;"。
可能會造成置中不正常,可參考這篇:[jQuery API] ScrollTop 回傳值為0

星期二, 4月 17, 2012

IIS 主機標頭

要在IIS上分別不同的網站其實很簡單
有分3種
1. 用IP區分
2. 用PORT區分
3. 用主機標頭區分

這次介紹的是第三種, 用主機標頭區分
用主機標頭區分的方式需要跟DNS做配合
方法如下:
1. 進IIS主機, 在IIS上的"網站"按右鍵-->新增網站(EX.Web01)
2. 在此網站按右鍵-->內容-->網站-->進階-->編輯, 在主機標頭值那邊, 填上客戶要的網站名稱(EX.testa.com)
3. 重複1, 2步驟, 建另一個新的網站(Web02), 主機標頭值填上testb.com

4. 進DNS, 增加 testa.com, testb.com 兩個正項對應區域
5. 在testa.com上按右鍵-->新增主機-->增加一筆IP為IIS主機IP的資料, 名稱不用打(不用打代表使用父系網域名稱, 也就是testa.com)
6. 在testb.com上按右鍵-->新增主機-->增加一筆IP為IIS主機IP的資料, 名稱不用打(不用打代表使用父系網域名稱, 也就是testb.com)

設好之後, 進IIS按下"瀏覽", 就可以正常瀏覽之
(在本機也可以直接打網站名(ex.www.testa.com)去找到站台資料)



補充:

1. 用此法設定的網站, 要將client的dns指向同一台的dns, 閘道也要相同才能連到.
2. 網站使用SSL安全連線時, 就不能使用主機標頭值

星期三, 4月 11, 2012

[IIS 7] 500.21-無法辨識的模組

今天發生如主題所示的 500.21-無法辨識的模組的錯誤,
第一時間一定就請教G大神了,原來只是單純SERVER上未安裝.NETFramework 4.0。
另外這篇: 500.21-無法辨識的模組 的作者也發生同樣的問題。
主要是用命令提示字元來重新註冊就可以解決了。

路徑如下:
%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i

如果你想要自已寫批次檔來修正錯誤的話可以參考這篇
[Asp.Net] 重新註冊IIS .NET Framework
提供給同樣問題的朋友參考!!

[IIS 7] 解決 HTTP 404.2-Not found ISAPI和CGI限制方法

在將網站從IIS6移到IIS7後,
雖然已經重新安裝新的IIRF的模組
[IIS 7] IIS7 安裝 IIRF(Ionic's ISAPI Rewrite Filter),
不過還是造成了HTTP 404.2-Not found的錯誤訊息(本機看的時候)。
主要是ISAPI和CGI的限制內的.net 4.0模組未設置允許!!


重新設定為允許就可以正常Rewrite了。


Reference:
http://www.qiandabao.com/wdgz/938.html

[jQuery plugin] spinner button

好用的Spinner Button的元件 https://github.com/btburnett3/jquery.ui.spinner

[Javascript] 偵測是否為iphone/ipod/ipad瀏覽器

簡單的用Regex來判斷是否為iphone/ipad/ipod的瀏覽器!!
//偵測是否為ipad   
if(/iPad/i.test(navigator.userAgent) {   
    // dosomething
}   
//如果所有的裝置要一起改變可以這樣用   
if (/(iPhone|iPad|iPod)/i.test(navigator.userAgent)) {   
    // dosomething  
}; 

[jQuery plugin] Masked Input Plugin

強大的textbox欄位驗證元件:Masked Input Plugin

星期二, 4月 10, 2012

[jQuery] 改善你的jQuery效能

愈大型的網站該考慮網站的效能:
本篇記綠一些找到提升jQuery效能的文章:)
Improve your jquery 25 excellent

加速前端網頁效能的14條規則

[IIS 7] IIS7 安裝 IIRF(Ionic's ISAPI Rewrite Filter)

如果你的asp.net的舊網站從IIS6升級至IIS7時,
如果你有用到IIRF模組,可參考這篇文章。
Installing IIRF on IIS7

不過現在已經提供方便的.msi檔了,可以無痛設定XD
下載IIRF 這裡

[IIS 7] 總該面對IIS 7了吧!!

一直都懶得來摸IIS 7,都出來這麼久了,也是該面對的時候了lol
今天在試的過程中找到的一些學習資源。記綠在此方便以後參考。


IIS 7 基礎觀念:網站、應用程式、與虛擬目錄
【潛盾機】列出IIS上所有ASP.NET網站應用程式
M$ IIS7 邊做邊學系列
如何部署 Asp.Net 4.0 應用程式於 IIS 7 x64 WSS 3.0 下

星期一, 4月 02, 2012

[Javascript] 取得完整路徑的檔名

今天在測試input box的檔案路徑時,
發現不同瀏覽器的取出的值不太一致,Chrome的是完整路徑,FF跟IE都是檔名。
要取得檔案的話可以使用以下的javascript範例,
取自 "Javascript - How to extract filename from a file input control"


To split the string ({filepath}/{filename}) and get the file name you could use something like this:
str.split(/(\\|\/)/g).pop()
"The pop method removes the last element from an array and returns that value to the caller." MOZILLA DEVELOPER NETWORK
Example:
from: "/home/user/file.txt".split(/(\\|\/)/g).pop()
you get: "file.txt"


[AJAX] 解決AJAX呼叫後的上下頁按鈕問題


使用AJAX來存取資料後,常常會遇到上下頁沒有辦法記錄歷程。
以下是建議解決這個議題的各種套件。
最後選擇Asual address套件:
範例如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jQuery Address - Deep linking for the masses</title>
<script src="js/jquery-1.7.js"></script>
<script src="js/jquery.address-1.4.js"></script>
<script>

$(function(){
    
 $.address.change(function(event) {
     // do something depending on the event.value property, e.g.
     // $('#content').load(event.value + '.xml');
     console.log("address.change" + event.value);
 });
 
    $('a').click(function() {
     
     //record address
     var link = $(this).attr('href').replace(/^#/,'');;
     $.address.autoUpdate(false).value(link);
      
    });
});
</script>
</head>
<body>
<a href="#a" >a</a>
<a href="#b">b</a>
<a href="#c" >c</a>
</body>
</html>

此元件提供三種Callback Event,分別為change,externalChange,internalChange。
觀看你的使用情況,主要是externalChange可能你區別出是改變瀏覽器網址觸發的事件,非常好用,不過目前測試情況要多偵測出externalChange事件需要綁定每個link元素的click事件後加入

星期四, 3月 29, 2012

[Eclipse] 利用Eclipse建立Ant用的build.xml

本文說明如果用eclipse快速建立Ant的Build.xml檔

使用步驟:
1.在專案上按右鍵->Export

2.General->Ant Buildfiles


3. 選擇要匯出build.xml的專案


4.由於這個檔案是工具產生的,請依自已的需求做修改。

[Alfresco] How to create Java backed web script in alfresco (2)

痛過的經驗記錄一下。
看過上一篇的Java backed 架構圖之後,
得知我們需要完成四個Components,
分別是
1.XML descriptor document (Describing the web script)
2.Freemarker (Writing the response template-FTL)
3.Java class (Writing the web script controller)
4.Spring bean XML(Register the Java class in the Alfresco)

星期三, 3月 28, 2012

[jQuery plugin] Validator不透過 submit來觸發檢查欄位

今天遇到一個validator ui上的問題, 由於textbox加了combobox的plugin後,將它放入div裡包起來,會有異常的bug。 把原本驗證textbox拿到form的外面。 所以另外用一個元素來觸發驗證的動作!! 範例如下:


Triggers element validation programmatically.
 //because quota text box position is out of form
 $("#quota_input").change(function(){
  //do validation by changing value in the text box
  $("#filesizeForm").validate().element("#quotaType");
 });

[jQuery plugin] Images gallery

一些覺得不錯的Images gallery

jQuery masonry
http://masonry.desandro.com/demos/images.html

拍立得效果
http://www.microsoft.com/web/downloads/platform.aspx

[Java] 執行Shell script


想要使用java來執行Shell Script嗎?
透過Process就可以完成了,以下是tail指令的簡單範例,
記得reader要指定編碼,不然中文字會亂碼喔

Process processOnLinux = Runtime.getRuntime().exec("tail -500 " + USR_LOG);
reader = new BufferedInputStream(processOnLinux.getInputStream());
reader = new InputStreamReader(processOnLinux.getInputStream(), "UTF-8");

星期六, 3月 24, 2012

[SVN] VisualSVN

懶的了解SVN安裝繁雜的步驟的朋友(或跟我一樣裝了一直爆炸XD),
先直接安裝VisualSVN吧,完全無腦安全,省時省力:)

其他常用的功能:
將專案匯入資源庫(import project to VisualSVN) 參考這裡

weiteki-MacBook-Air:workspace ibigd$> svn import -m 'import message' your_project_name https://163.17.83.13/svn/your_repository/trunk/your_project_name


星期四, 3月 22, 2012

[Java] XProperties

如果你的Properties含有變數串接變數的話,
例如:
IP=192.168.0.1
URL=http:/{IP}/WebServer
可以使用這個擴展的XProperties


星期日, 3月 18, 2012

[TOMCAT] MAC OSX 安裝TOMCAT 7.0.x

平常在公司都是用WINDOWS的Eclipse開發JAVA,
希望在AIR也把環境設定,
這樣就不需要把公司的電腦(超重XD)常常帶來帶去。

安裝流程(參考這篇)

[SVN] Windows 安裝 SVN

今天試了很多SVN版本終於有RUN一個正常的組合XD
提供給有需要的人參考

OS:Windows 7
Appserv:appserv-win32-2.5.10.exe
Subversion:1.4.6

目前搭1.7.3~1.7.4這二個版本在設定完httpd.conf後,重啟Apach都會有無法執行
mod_dav_svn.so和mod_authz_svn.so這二個modules的錯誤。


 一、SVN安裝流程:



1.安裝Appserv 2.5.10
2.安裝SVN 1.4.6
3.Apache的httpd.conf設定

星期四, 3月 15, 2012

[Java] Jersey 清除 response cache

通常在IE瀏覽器常常會遇到亂Cache一通的問題,
Jersey提供Response物件來讓我們簡單的可以清除Cache。
好好利用cache也是一個節省頻寬跟效能的好方法。
如果有很多方法都需要清Cache的話,就考慮使用Filter的寫法比較方便。

@GET
 @Path("/{uid}")
 @Produces(MediaType.APPLICATION_JSON)
public Response getUser(
   @PathParam(value="uid") String uid){

//do sth

ResponseBuilder rb = Response.ok(respJSON.toString());
  CacheControl cc = new CacheControl();
     cc.setNoCache(true); 
     return rb.cacheControl(cc).build();

}

[Java] 實作Filter

Filter顧名思義就是過濾器,在JSP/Servlet中,Filter的功用就是在擔任Request與Response的過濾功能,當使用者的request發出至某資源時,您可以先對request作一些前置處理,例如進行身份驗證、過濾不安全的請求、監視統計請求的來源與出處等等,Filter的功能是雙向的,您也可以對JSP/Servlet的response進行過濾或進行某些處理,例如對輸出先進行壓縮、對XML的呈現進行轉換等等。

總而言之,Filter可以擔任瀏覽器與JSP/Servlet之間的一個中介處理者,一些request的前置處理動作又一些response的後置處理,都可以交由這個中介處理者來完成,當然Filter可以達到的功能,我們也可以直接撰寫在JSP/Servlet中,但如果有很多JSP/Servlet都需要相同的處理,例如某些網頁都需要統一的身份驗證方式時,與其在每一個網頁中都撰寫驗證的程式碼,我們不如直接撰寫Filter,讓它來統一進行處理。

最近在測試Web Cache的行為,發現寫在Filter裡面的header最後能在回應標頭看到你所設定的結果。 如果在一般JSP的頁面加上Meta的Tags或使用response.setHeader的方式,在回應標頭都無法看到你所設定的結果。 但二者的快取效果都是一樣的。

@Override
 public void doFilter(
   ServletRequest request, 
   ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  
  //HttpServletRequest hsresq = (HttpServletRequest) request;
  HttpServletResponse hsresp = (HttpServletResponse)response;
  
  //current request server url(Don't include host and sitename)
  //String currentURL = hsresq.getServletPath();
  hsresp.setHeader("Pragma","no-cache"); 
  hsresp.setHeader("Cache-Control","no-cache,no-store,must-revalidate"); 
  //prevents caching at the proxy server
  hsresp.setDateHeader("Expires", 0); 
  
  chain.doFilter(request, response);
 }

在web.xml設定只對jsp的頁面進行filter,
注意url-pattern設定成/*.jsp是錯誤的。

<filter>
  <filter-name>JSPNoCacheFilter</filter-name>
  <filter-class>filter.JSPNoCacheFilter</filter-class>
 </filter>
    <filter-mapping>
 <filter-name>JSPNoCacheFilter</filter-name>
     <url-pattern>*.jsp</url-pattern>
 </filter-mapping>
Reference:
JSP Servlet Filter-1

星期二, 3月 13, 2012

Web Cache Issue

簡單記綠一下看完一些Web Cache資料的心得,
方便以後快速學習。

使用Cache的理由

To reduce latency
To reduce network traffic

Web Caches的種類
Browser Caches:
Proxy Caches:
Gateway Caches: 如Content delivery networks (CDNs)

在你的網頁控制Caches


在網頁的Header加上HTML Meta Tags
PRAGMA HTTP HEADERS:
<meta http-equiv="Pragma" content="no-cache">

星期日, 3月 11, 2012

[Java] Jersey WADL

當Jerey愈用愈久之後,
如何產生這些URL資源的描述文件就是一件苦惱的事,
有需求的人可以參考這篇文章 Jersey and WADL(Web Application Description Language)
假設你已經有一個jersey的站台之後並完成WADL相關組態設定之後,
就可以呼叫http://localhost:9998/application.wadl來取得你的Restful應用程式的WADL


    
    
        
            
                
                    
                
            
        
    




要建立WADL可以參考以下二種方法

How to configure your webapp to provide extended WADL
This page describes what's necessary for getting an extended WADL generated within your running webapp.

How to generate extended WADL (without a webapp)
The generate-wadl sample shows how to generate (extended) WADL with maven(project management tool), without the need to start the webapp. This sample also has a README you might want to look at.

星期六, 3月 10, 2012

[Asp.net] 佈署.net framework 4.0發生錯誤

今天在IIS佈署新的Asp.net 4.0 site,
常常會發生Server unavaliable和伺服器應用程式無法使用這二個錯誤,
查到保哥這篇的實用教學ASP.NET 4.0 安裝在 IIS6 最常遇到的四個問題
原來造成錯誤的原因在於原本的IIS裡面已經有了其他.net framework 2.0的站台,
由於原來的2.0站台已經使用了DefaultAppPool,但新設的4.0站台預設也是使用DefaultAppPool,會導致先被執行的網站會搶到執行權,導致其他站台產生上述的錯誤。

保哥提供二種解法:
一:設定應用程式集區:
設定方法可以參考這篇文章:設定應用程式集區(AppPool)防止Server上的Web應用程式彼此干擾

二:將所有站台全部設成.net.framework 4.0

當然選擇第一個方法設定新的應用程式集區是最好的。比較不會費力。

星期四, 3月 08, 2012

[Alfresco] 模擬上傳大頭照發生錯誤


11:24:45,307  ERROR [node.integrity.IntegrityChecker] Found 1 integrity violations:
Invalid property value:
   Node: workspace://SpacesStore/f07b92c9-e188-4991-b55d-eef404d60eda
   Type: {http://www.alfresco.org/model/content/1.0}content
   Property: {http://www.alfresco.org/model/content/1.0}name
   Constraint: 02090038 Value '?????????????????????.png' is not valid as a file name.
This property must be a valid file name.

很明顯又是中文亂碼的問題,查了一下就是在Multipart/data-form的時候,
使用getbytes的方法時,未指定utf-8編碼,導致抓的預設編碼跟自已的VM環境不一致而產生的錯誤。

星期一, 3月 05, 2012

[Java] 在JDBC使用SQL IN

這篇文章Batching Select Statements in JDBC提供四種解法

擷錄前言:


In networking, one of the most expensive things you can do is make a server roundtrip. In JDBC, this corresponds to a database call. If you are doing inserts, updates or deletes, you can use the executeBatch() signature to cut down the number of trips to the server. Unfortunately, there is no such built-in mechanism for select queries.

Suppose you want to get the names for a given list of ids. Logically, we would want to do something like:

PreparedStatement stmt = conn.prepareStatement(
 "select id, name from users where id in (?)");
stmt.setString("1,2,3");
However, this will not work. JDBC only allows you to substitute a single literal value in the "?". You can't substitute things that are meant to become part of the SQL statement. This is necessary because if the SQL itself can change, the driver can't precompile the statement. It also has the nice side effect of preventing SQL injection attacks. Instead, you have four options for the implementation:
  1. Run the query separately for each id
  2. Build one query to do everything
  3. Use a stored procedure
  4. Select batching
最後選擇效能最快的一種。但尚未測試時間差多少倍。
StringBuilder inClause = new StringBuilder();
boolean firstValue = true;
for (int i=0; i < batchSize; i++) {
  inClause.append('?');
  if ( firstValue ) {
    firstValue = false;
  } else {
    inClause.append(',');
  }
}
PreparedStatement stmt = conn.prepareStatement(
    "select id, name from users where id in (" + inClause.toString() + ')');


for (int i=0; i < batchSize; i++) {
  stmt.setInt(i);  // or whatever values you are trying to query by
}


星期四, 3月 01, 2012

[jQuery plugin] 設定Cursor在Textbox的位置

最近在實作自動將Textbox前後空白字元清除的功能時,
遇到將tirm完的新字串重設回Textbox時,
Cursor的位置無法停留至文字的最後位置
網路上的範例也蠻多的,以下範例是改自參考的網址測試
IE 8,IE 9,Chrome,FF可正常運作。
有其他需求的話可參考jQuery的caret plugin

星期三, 2月 22, 2012

[Javascript] i18n問題: 可參數化的翻譯語句

先前在實作i18n上未考慮翻譯字串加上參數順序的問題
會導致不同語言翻譯下參數順序會被改變的問題!!
因此要改寫一下原本的printf方法!!

參數命名規則:  _%s<參數ID>_  , ID由1開始
參數命名範例:  Hello _%s1_ !!

星期二, 2月 21, 2012

[jQuery API] 事件委派(delegate)使用


最近又用到delegate來綁定事件,怕又忘記順便記一下。

//action binding
$(".manage_act").delegate(".doedit", "click", function () {
    //dosomething
});

每次頁面重新畫UI的時候必需先undelegate,不然會異常(重覆綁定事件)
//must reset previous delegate
$myGroup.undelegate("click");



[Java] PreparedStatement Order by 失效問題!!

使用PreparedStatement操作Order by指令無法得到排序的解法!!
參考Stackoverflow:PreparedStatement not returning ordered ResultSet 至一文。

範例:
透過PreparedStatement來執行以下sql子句

星期一, 2月 20, 2012

[Alfresco] How to create Java backed web script in alfresco (1)


基於以下理由所以選擇java-backed web script的作法:
1.accessing alfresco application services not available via JavaScript API
2.when the performance is absolutely critical
3.to get tighter control of the generated response.
4.when we need to access the Alfresco API
5.if we prefer stronger programming language like JAVA

透過上面的架構圖,我們可以知道需要準備四個元件
1.XML descriptor document (Describing the webscript controller)
2.Freemarker (Writing the response template-FTL)
3.Java class (Writing the webscript)
4.Spring bean XML(Register the Java class in the Alfresco)

接著準備來寫一個Java Backed Web Script吧~
[Alfresco] How to create Java backed web script in alfresco (2)

Reference:
Alfresco Help Java backed web script
Alfresco WiKi: Java backed web script samples
Alfresco Blog: Java-Backed Web Scripts
Web script article

星期三, 2月 15, 2012

[Mysql] left join to count rows

計算聯絡人清單的個數,
分別有contact_list與contact_list_member,
使用left join去計算每個聯絡群組的總個數!!
使用inner join會讓無成員的聯絡人群組無法找出來!!
記得group by cl.contact_list_id也是重點!!

SELECT cl.contact_list_id,cl.contact_list_name,cl.creator,cl.create_date,Count(m.contact_list_id) total FROM `contact_list` cl
left join contact_list_member m on m.contact_list_id = cl.contact_list_id
group by  cl.contact_list_id

如果要再加入條件限制!!

select * from
(
SELECT cl.contact_list_id,cl.contact_list_name,cl.creator,cl.create_date,Count(m.contact_list_id) total FROM `contact_list` cl left join contact_list_member m on m.contact_list_id = cl.contact_list_id
group by cl.contact_list_id
) new_contact_list
where total >1

星期二, 2月 14, 2012

[MS SQL] Paging 的語法

跟MSSQL的分頁指令蠻不一樣的,
在MySQL用limit的方法就可以簡單達成!!

$per_page=20;
$page=2;
$first_result=($page-1)*$per_page;
"select * from contacts limit $first_result, $per_page order by last_name;";

"select * from contacts order by last_name limit $first_result, $per_page ;";

//自已的範例加了order by

select * from contact_list where order by create_date limit 1,1

尚未考慮最佳解法!!

星期四, 2月 09, 2012

[Java] Httpurlconnection timeout issue

如何使用HttpUrlConnection的Request TIMEOUT例外處理?

故事是剛剛同事打電話來說,目前實作的REST CLIENT對於TIMEOUT的
Request無法有效擷取到例外事件處理!!
找到以下這篇討論也是解法:Java URLConnection Timeout


try{
URL url = new URL("http://www.myurl.com/sample.xml");
          URLConnection urlConn = url.openConnection();
          urlConn.setConnectTimeout(15000);
          urlConn.setReadTimeout(15000);
          urlConn.setAllowUserInteraction(false);         
          urlConn.setDoOutput(true);

          InputStream inStream = urlConn.getInputStream();
          InputSource input = new InputSource(inStream);
}catch(SocketTimeoutException e){

}catch(IOException e){
}


要自已設這二個參數然後在擷SocketTimeoutException
urlConn.setConnectTimeout(connectTimeout);
urlConn.setReadTimeout(socketTimeout);

另外一個方法擷至此文(JDK中的URLConnection參數詳解):
HttpURLConnection是基于HTTP協議的,其底層通過socket通信實現。如果不設置超時(timeout),在網絡異常的情況下,可能會導致程序僵死而不繼續往下執行。可以通過以下兩個語句來設置相應的超時 System.setProperty("sun.net.client.defaultConnectTimeout", 超時毫秒數字符串); System.setProperty("sun.net.client.defaultReadTimeout", 超時毫秒數字符串);
其中: sun.net.client.defaultConnectTimeout:連接主機的超時時間(單位:毫秒) sun.net.client.defaultReadTimeout:從主機讀取數據的超時時間(單位:毫秒)
例如: System.setProperty("sun.net.client.defaultConnectTimeout", "30000"); System.setProperty("sun.net.client.defaultReadTime
Java中可以使用HttpURLConnection來請求WEB資源。 HttpURLConnection對象不能直接構造,需要通過URL.openConnection()來獲得HttpURLConnection

明天再來修正一下寫的CODE~

[Java] Insert if not exist: 資料列不存在時才新增


重覆的連絡人清單就不要插入!!
重點在select * from (select 2,'ken') as tmpInsert記得要重新給一個別名,
不然編譯都會爆炸給你看lol

範例:
插入一個使用者ken到聯絡人清單索引為2的結果

insert into contact_list_member(contact_list_id,uid)
select * from (select 2,'ken') as tmpInsert
where not exists(select 1 from contact_list_member clm where clm .contact_list_id= 2 and  clm .uid='ken')


使用preparedstatement就會像下面那樣
//insert if not exist
   String insertMemberSql= 
    "insert into contact_list_member(contact_list_id,uid) select * from (select ?,?) as tmpInsert where not exists(select * from contact_list_member where contact_list_id=? and uid=?)";

Update 2012/03/08 今天在同事的測試下發現上面的語句在插入的值都一樣的時候所產生的duplicate column name bug,簡單的用新增使用者的範例來記綠一下 

範例:
以下語句要新增一個帳號跟密碼都是叫cindy,不一樣就不會有這個問題!!

insert into users(account,password) select* from (select 'cindy','cindy') as tmpInsert where not exists(select 1 from users where account = 'cindy')

 問題: 錯誤的原因在於我們要建立一個帳號跟密碼一樣的使用者,會造成表格出現重覆欄位名稱的問題(Duplicate column name 'cindy'錯誤)

 以下是產生這個錯誤的SQL片段

select* from (select 'cindy','cindy') as tmpInsert 解法

因tmpInsert已經含有重覆的column name了,因此我們需要指定tmpInsert內的column name,才不會讓表格內的欄位名稱重覆的異常

 select account ,password from (select 'cindy' as account ,'cindy' as password) as tmpInsert

上述語句會產生的tmpInsert資料表結果集

account  |  password
cindy     |  cindy

Reference: MySQL一個聰明的sql,當Record沒有的時候才增加
不存在时才插入数据

星期二, 2月 07, 2012

[Java] JDBC ResultSet/RowSet 取得查詢結果的總列數

常常需要得到查詢結果返回的總列數,
Java提供以下三種解法:

[Java] 必學!! 取得當前新增資料的索引值

當在MySQL使用AUTO_INCREMENT產生索引的值,如何取得新增的索引值呢?

MySQL提供了LAST_INSERT_ID()解決這個問題!!

SELECT LAST_INSERT_ID();


如果要用JDBC實作的話只需要加入Statement.RETURN_GENERATED_KEYS,
執行getGeneratedKeys()即可輕鬆取得!!

星期一, 2月 06, 2012

[Alfresco] Boolean type is in FTL

在ftl檔案遇到boolean欄位一開始所遇到的錯誤

{
"shareDpxStatus": <#if person.properties.shareDpxStatus??>${person.properties.shareDpxStatus}<#else>null
}


原來ftl檔不支援直接將boolean型態印出來,要先轉換成字串型態
解法如下:
{
"shareDpxStatus": <#if person.properties.shareDpxStatus??>${person.properties.shareDpxStatus?string("true","false")}<#else>null
}

星期日, 2月 05, 2012

[Java] JDBC Transaction

本篇說明如何在JDBC實作Transaction機制。

步驟一:MsSQL設定:
設定INNODB資料表

Tip:MySQL 對不同的 Table 可以選擇不同的 Implementation 方式,像是最早的 ISAM (ISAM 將在 MySQL 5.0 以後被移除),後來的 MyISAM (因為要做 Transaction 時要預留多一點空間來進行處理,因此如果不須使用 Transaction 時,直接建 Table 就會採用 MyISAM 的格式)、把 Table 存在記憶體中提升效能的 HEAP Table,以及有支援 Transaction 的 INNODB 格式。
步驟二:如何在Java code執行Transcation

其他你感興趣的文章

Related Posts with Thumbnails