星期四, 4月 11, 2013

[Java] Filter Url-Pattern 筆記

久久用一下常常會忘記怎麼正確的設定Filter Url-Pattern,
趁著昨天需要用到,筆記一遍。

第一種解法(舊方法):
http://fecbob.pixnet.net/blog/post/38258307-tomcat-default-servlet-%E7%9A%84url-pattern

filter-mapping在web.xml中定義的順序相同。
在web.xml檔中,以下語法用於定義映射:
  1.  以」/’開頭和以」/*」結尾的是用來做路徑映射的。
  2.  以首碼」*.」開頭的是用來做擴展映射的。
  3. 「/」 是用來定義default servlet映射的。
  4.  剩下的都是用來定義詳細映射的。比如: /aa/bb/cc.action


所以,為什麼定義」/*.action」這樣一個看起來很正常的匹配會錯?因為這個匹配即屬於路徑映射,也屬於擴展映射,導致容器無法判斷。

第二種解法:
http://k2java.blogspot.in/2011/04/servlet-filter-mapping-exclude-pattern.html

透過設定init-parm的方式帶入忽略的URL,並透過Regex來處理

Servlet filter mapping exclude pattern

Once you apply a filter to a URL pattern:
<filter-mapping>
    <filter-name>theFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
/*
there's no option in web.xml to exclude a more specific pattern such as: /public/*.

But you can put the exclusion logic in the filter itself:


<filter>
    <filter-name>theFilter</filter-name>
    <filter-class>org.demo.CustomServletFilter</filter-class>
    <init-param>
 <param-name>excludePatterns</param-name>
 <param-value>public/*</param-value>
    </init-param>
</filter>
org.demo.CustomServletFilter excludePatterns public/*

And in the filter code:
public void init(FilterConfig cfg) throws ServletException {
 this.excludePatterns = cfg.getInitParameter("excludePatterns");
 .
 .
 .
}

public void doFilter(ServletRequest request,
           ServletResponse response,
    FilterChain chain) 
 throws IOException, ServletException {
 String url = request.getRequestURL().toString();
 if (matchExcludePatterns(url)) {
     chain.doFilter(request, response);
     return;
 }
 .
 .
 .
}

[Eclispe] eGIT 建立一個repository

建立一個location repo的擷圖,如果要直接丟到Github上的話,請參考這個



星期二, 4月 02, 2013

[Eclipse] 使用eGIT取回Github上面的專案

前言:
由於平常都使用eclispe開發,所以直接安裝git plugin來存取Github的repo是比較方便的,
感覺把一些sample code放在這,比放在blog上好維護多了xd
所以記錄一下如何從github取回專案 :D

前置處理:
1.請先安裝Egit pluign:

Help->Install New Software
EGit - http://download.eclipse.org/egit/updates
記得二個都打勾!!

星期六, 3月 30, 2013

[jQuery plugin] 通知訊息外掛測試

今天試了二個有關訊息通知的外掛,分別是noty跟notify


http://needim.github.com/noty/ (還是github上2012的前十名 :D)
noty的功能比較強大,不過你要怎麼客制化訊息的位置都非常方便。
此外還有queue的功能。


http://redeyeoperations.com/plugins/Notify/
Notify相較之下就比較簡便了,訊息只能秀在最上方,
也沒有queue的功能,如果你有訊息可能會一直出現時,
原本的區塊就會被取代了。


星期一, 3月 25, 2013

[Eclipse] 搜尋取代大量字串

今天需要將一個東西重新命名一下,但整個專案很多地方有引用,需要一個快速取代的方法。
記錄一下eclipse的操作xd,


1.先搜尋要取代的字,指定搜尋範圍






2.接著在搜尋的結果集按右鍵,就可以看到replace all嚕

星期二, 3月 19, 2013

[jQuery] 如何觸發超連結click動作

今天在模擬使用File API下載檔案,需要一個觸發超連結引發下載的動作,筆記一下。
//dom api
document.getElementById('dllink').click(); 
//jquery api
$("#dllink")[0].click();

[Java] Java Javascript/CSS Asset pipeline

將js有效的模組化具有許多維護上的好處,但缺點但js模組多的時候,頁面載入的時間也就愈長,雖然能在產品前將所有的js打包成一份(用linux指令),但感覺流程上並不適用目前的專案。

目前找到pack-tag這個開源軟體,試用過後感覺非常試合導入專案中,不會影響目前Developer的開發,只需替換掉原本的script標籤,並支援javascript minify。

pack-tag

A JSP Taglib for delivering minified, combined and gzip-compressed resources (JavaScript and CSS).

https://github.com/galan/packtag



[jQuery plugin] 不透過submit觸發jquery validation驗證

jquery validation真是不可或缺的好物,每次用往往有很多用法都會忘記。
趁熱筆記一下。
如果想要不透過submit來觸發驗證的話,可以透過.valid()這個方法。
除了整個form全部驗證之外,也可驗證表單內某一要驗證的元件


$("#myform").validate();
$("a.check").click(function() {
    alert("Valid: " + $("#myform").valid());
    return false;
});

Reference: How do I use jQuery Validate directly, without the submit button?

星期三, 3月 13, 2013

[jQuery API] 偵測關閉網頁使用者點選ok或cancel

為了避免使用者在網頁處理中關閉網頁的話,可以綁定onbeforeunload事件來偵測,
但更進一步的應用,可能需要了解使用者到底是按ok還是cancel!!
找到以下這篇所用到的解法,有需要的人可以參考看看。

Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?
The code within the first setTimeout method has a delay of 1ms. This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript interpreter will continue by directly calling thereturn statement, which in turn triggers the browsers modal dialog. This will block the UI queue and the code from the first setTimeout is not executed, until the modal is closed. If the user pressed cancel, it will trigger another setTimeout which fires in about one second. If the user confirmed with ok, the user will redirect and the second setTimeout is never fired.

$(function(){ 
 
 $(window).bind("beforeunload", function(e) {
  setTimeout(function() {
  
            setTimeout(function() {
                $("body").css('background-color', 'red').html("User click cancel button");
            }, 1000);
        },1);
        return 'are you sure';
 });
 
 //按ok處理
 $(window).unload( function () { 
  console.log('bye bye :)');
  
 } );
 
});

星期日, 3月 10, 2013

[Java] Regex驗證不符合的windows檔案名稱

威猛的範例,參考stackoverfolw這篇討論:
 http://stackoverflow.com/questions/6730009/validate-a-file-name-on-windows
public static boolean isValidName(String text)
{
    Pattern pattern = Pattern.compile(
        "# Match a valid Windows filename (unspecified file system).          \n" +
        "^                                # Anchor to start of string.        \n" +
        "(?!                              # Assert filename is not: CON, PRN, \n" +
        "  (?:                            # AUX, NUL, COM1, COM2, COM3, COM4, \n" +
        "    CON|PRN|AUX|NUL|             # COM5, COM6, COM7, COM8, COM9,     \n" +
        "    COM[1-9]|LPT[1-9]            # LPT1, LPT2, LPT3, LPT4, LPT5,     \n" +
        "  )                              # LPT6, LPT7, LPT8, and LPT9...     \n" +
        "  (?:\\.[^.]*)?                  # followed by optional extension    \n" +
        "  $                              # and end of string                 \n" +
        ")                                # End negative lookahead assertion. \n" +
        "[^<>:\"/\\\\|?*\\x00-\\x1F]*     # Zero or more valid filename chars.\n" +
        "[^<>:\"/\\\\|?*\\x00-\\x1F\\ .]  # Last char is not a space or dot.  \n" +
        "$                                # Anchor to end of string.            ", 
        Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS);
    Matcher matcher = pattern.matcher(text);
    boolean isMatch = matcher.matches();
    return isMatch;
}

星期五, 3月 08, 2013

[jQuery plugin] Clearable textbox

想要提供使用者方便清空textbox的plugin嗎
找到一個符合這個需求的clear textbox plugin

http://viralpatel.net/blogs/clearable-textbox-jquery/

Demo site:
http://viralpatel.net/blogs/demo/jquery/clearable-textboxes/

星期二, 3月 05, 2013

[Javascript] Date.parse在safari NaN解決方法


最近在Safari使用Date.parse的NaN問題,不過以下這個解法,少算了時分秒。
The behavior of the Date.parse method is implementation dependent, on ECMAScript 5, this method can parse ISO8601 formatted dates, but I would recommend you to make the parsing manually.
Some time ago I've made a simple function, that can handle a format specifier argument:
function parseDate(input, format) {
  format = format || 'yyyy-mm-dd'; // default format
  var parts = input.match(/(\d+)/g), 
      i = 0, fmt = {};
  // extract date-part indexes from the format
  format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = i++; });

  return new Date(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']]);
}

parseDate('06.21.2010', 'mm.dd.yyyy');
parseDate('21.06.2010', 'dd.mm.yyyy');
parseDate('2010/06/21', 'yyyy/mm/dd');
parseDate('2010-06-21');
Also you could detect the ECMAScript 5 behavior to parse ISO formatted dates, you can check if theDate.prototype.toISOString is available, e.g.:
if (typeof Date.prototype.toISOString == "function") {
  // ES5 ISO date parsing available
}

星期日, 2月 24, 2013

[Alfresco] 在java backed取得post request body

先前已經用過javascript webscript取的post request body
這次要改用javabacked的方式取得。
範例如下:

public void execute(WebScriptRequest req, WebScriptResponse response) {
     
 
     
     InputStream inputBody = req.getContent().getInputStream();
     String requestBody = RequestBODY.get(inputBody,Charset.forName("utf-8"));

//requestBody:{"parentUUID":"23d97062-5310-4b80-864a-a2232238fd11","uuids":[]}

     System.out.println("requestBody:" + requestBody);

}

星期五, 2月 22, 2013

[Alfresco] 下載Zip

原本的alfresco不支援下載多個檔案與資料夾,可以透過自已實作java backed的方式實現。
以下是找到的範例,不過用的alfresco似乎跟我的不一樣:)
http://code.google.com/p/alfresco-application-samples/

[jQuery plugin] 浮水印+驗證器

浮水印加在inputbox是常見的功能需求,但有時候需要與驗證器整合。

function notWatermark(value, element){
        return value != 'enter text...';
    }

    $.validator.addMethod("notWatermark", notWatermark, "Field cannot be empty.");

    $('#SearchForm').validate({
        rules: {
            SomeField: {
                required: true,
                notWatermark: true
            }
         },

Reference:jQuery Watermarked input and validation

星期二, 2月 19, 2013

[jQuery plugin] 多檔下載

目前專案有需求要達到多檔下載的需求,目前看過mega雲端儲存的作法個人是比較喜歡。
以下是找到現成的外掛

multiDownload
http://biesiad.github.com/multiDownload/

jQuery File Download Plugin for Ajax like, feature rich file downloads
http://johnculviner.com/post/2012/03/22/Ajax-like-feature-rich-file-downloads-with-jQuery-File-Download.aspx

模擬頻寬限制軟體

有時候需要模擬客戶端超級爛的網路頻寬的議題XD
Slowyapp可以幫我們快速的完成這件事。

不過只支援Mac OS
http://slowyapp.com/

[jQuery plugin] Text Edit 文字編輯器元件

http://markitup.jaysalvat.com/home/

星期一, 2月 18, 2013

[Javascript] Regex group

實作拖拉上傳資料夾時,
需判斷客戶端使用的瀏覽器是否支援。
使用了regex group的功能,做個group的使用筆記。
chrome version :24.0.1312.57
var browserVersionFullNumber = $.getBrowserVersion();
 var myRegexp = /([\d]+)/g;
 var match = myRegexp.exec(browserVersionFullNumber);
 browserVersion = match[1];  // abc


星期三, 2月 06, 2013

[Alfresco] 檢查當前節點下的路徑是否存在


今天想要提升一下目前上傳元件的功能,需要支援拖拉資料夾的上傳。
昨天已經成功上傳所有目錄檔案,只差建資料夾的整合。

需要一個api來自動建立不存在的資料夾!!,之前已經有實作直接建資料夾的webscript。
目前需要一個如何判斷一個資料夾是否存在的方法。
以下是簡單的範例

星期二, 2月 05, 2013

[jQuery] jQuery countdown

在使用jquery countdown的時候,發生IE8不能正常執行。 發生在轉換Date Object時,Date.parse轉換的格式會因不同的瀏覽器吃的string格式會不一樣。

var expiredDate = $(obj).text();
     $.console("pre expiredDate:" + expiredDate);
     
     expiredDate = expiredDate.replace(/-/g,"/");
     $.console("expiredDate:" + expiredDate);
     
     var bmExpiredDate = new Date(Date.parse(expiredDate)); 
     
     $.console(bmExpiredDate);
    
輸出的結果:

日誌: pre expiredDate:2013-02-17 11:18:31
日誌: expiredDate:2013/02/17 11:18:31
日誌: Sun Feb 17 11:18:31 UTC+0800 2013

 Reference: JavaScript and Dates, What a Mess!

星期一, 2月 04, 2013

[jQuery] 上傳資料夾

目前Chrome瀏覽器在21版以後支援使用者上傳資料夾

多檔上傳
var dropzone = document.getElementById('dropzone');

dropzone.ondrop = function(e) {
  var length = e.dataTransfer.files.length;
  for (var i = 0; i < length; i++) {
    var file = e.dataTransfer.files[i];
    ... // do whatever you want
  }
};

上傳資料夾

dropzone.ondrop = function(e) {
  var length = e.dataTransfer.items.length;
  for (var i = 0; i < length; i++) {
    var entry = e.dataTransfer.items[i].webkitGetAsEntry();
    if (entry.isFile) {
      ... // do whatever you want
    } else if (entry.isDirectory) {
      ... // do whatever you want
    }
  }
};

Notice that a big difference here is that you can treat a dropped object as Entry (FileEntry or DirectoryEntry) by using new function called getAsEntry (webkitGetAsEntry).
After obtaining access to the Entry object, you can use standard file handling methods that were introduced in the FileSystem API specification. For example, this example shows how you can detect if a dropped object is a file or a directory by examining the .isFile(or the .isDirectory) field.

[Testing] modern IE

http://www.modern.ie/virtualization-tools

星期三, 1月 30, 2013

[Alfresco] Tomcat/temp 的上傳暫存檔無法清除

alfresco:3.4.5 深埋很久的bug,用javascript webscript/java backed都會產生暫存檔無法清除的問題 有找到一些討論的訊息 https://issues.alfresco.com/jira/browse/ALF-2363

 =====
 Alfresco QA Team added a comment - 19-May-10 03:23 PM Validated against 3.3.0 beta 39. 
Temp files are removed according to tempFileCleanerTrigger settings in scheduled-jobs-context.xml.

 =====

 alfresco會透過tempFileCleanerTrigger 來清除檔案,相關設定在scheduled-jobs-context.xml。 設定檔路徑在以下/usr/local/TOMCAT/webapps/alfresco/WEB-INF/classes/alfresco

星期五, 1月 25, 2013

[JSP] jsp session getAttribute跟setAttribute都爆炸了 XD

機器上測試用OpenJDK做的session操作整個爆掉(不能取/不能建session)。
都會噴以下二個exception:
setAttribute: Session already invalidated
getAttribute: Session already invalidated

以下是成功於正常的Oracle JDK成功操作session的測試碼,移到新的環境就會爆掉XD

//try{

 HttpSession httpsession = request.getSession(false);
 
 if(httpsession == null){
  System.out.println("HttpSession null");
 }else{
  System.out.println("HttpSession:" + httpsession.getId());
 }
 
  if(httpsession.getAttribute("test") == null){
 
   //throw getAttribute: Session already invalidated
 //if(session.getAttribute("test") == null) { 
   System.out.println("Session not found");
   
   try{
    
    System.out.println("Start to craete session");
    
    //request.getSession(true).setAttribute("test", "HelloSession");
    //session.setAttribute("test", "HelloSession");
    //httpsession.setAttribute("test", "HelloSession");
    
    HttpSession newSession = request.getSession(true);
    if(newSession.isNew()){
     System.out.println("isNew session id:" + newSession.getId());
    }else{
     System.out.println("old session id:" + newSession.getId());
    }
   
    newSession.setAttribute("test", "HelloSession");
    
    System.out.println("Suceed to craete session");
  
    
   }catch(IllegalStateException illeagalStateEx){
    System.out.println("Fail to craete session:" 
          + illeagalStateEx.getMessage());
   }
   
  }else{
   
   System.out.println("Session found");
   
   String sessionValue = 
     (String)httpsession.getAttribute("test");
   
   System.out.println("sessionValue:" + sessionValue);
   
  }
//}catch(Exception ex){
 
 //System.out.println("Global Exception:" + ex.getMessage());

//}

星期一, 1月 21, 2013

[jQuery API] beforeunload 偵測頁面關閉或刷新

有時候你需要偵測使用者刷新或關閉頁面進行一些處理,可以使用beforeunload事件。 //refesh page event
 $(window).bind("beforeunload", function() {
   return "Are you sure?";
 });

When you add return false, a confirmation dialog shows up, delaying the page unload. Meanwhile, the AJAX request finishes. When no return statement is included, the page will immediately unloads, terminating all active connections (and breaking your AJAX request). 

目前測試發現如果使用者按上一頁的話雖會執行這個事件,但卻會造成正在執行的連線中斷(例如:上傳) 不過眼尖發現這個confirm dialog的按鈕其實長的不一樣XD 


[jQuery API] 取得$元素的內容

有時候取要取得目前jquery物件的html是什麼, 目前找到以下解法,如果有其他方法就跪求了XD
var $container = $("<div/>");
var content = $container.append($TargetElem).clone()).html();

[TOMCAT] 設定 session逾期時間

如何設定tomcat的 session逾期時間
單位:分鐘!!
 <session-config>
    <session-timeout>5</session-timeout>
  </session-config>
如果要設定成秒數的話要另外實作,根據下述的資料參考
http://www.velocityreviews.com/forums/t146162-tomcat-5-0-config-timeout-in-seconds.html

That's a strange question. Why do you want to do it?
Anyway, no, it's not possible. Not directly at least. You will have to
implement a session listener and call setMaxInactiveInterval on every
new session. There you can specify the interval in seconds

星期三, 1月 16, 2013

[jQuery plugin] jQuery File Upload

用了一陣子的jQuery File Upload,發現在FF使用小於2MB的檔案,Progress bar無法正常的讀取file bytes XD

See also:
https://github.com/blueimp/jQuery-File-Upload/issues/1905

星期五, 1月 11, 2013

[jQuery plugin] 秒 轉換 為時:分:秒格式

找到的秒數轉時分秒格式的範例
jQuery.fn.time_from_seconds = function() {
    return this.each(function() {
        var t = parseInt($(this).text(), 10);
        $(this).data('original', t);
        var h = Math.floor(t / 3600);
        t %= 3600;
        var m = Math.floor(t / 60);
        var s = Math.floor(t % 60);
        $(this).text((h > 0 ? h + ' hour' + ((h > 1) ? 's ' : ' ') : '') +
                     (m > 0 ? m + ' minute' + ((m > 1) ? 's ' : ' ') : '') +
                     s + ' second' + ((s > 1) ? 's' : ''));
    });
};
加強一下可以支援多國語言
/**
 * Time from seconds
 * Refer from 
 * @author ken tsai
 * @date 2013/1/13
 **/
;(function($) {
 
 $.fn.time_from_seconds = function() {
     return this.each(function() {
         var t = parseInt($(this).text(), 10);
         $(this).data('original', t);
         $(this).text($.timeFromSeconds(t));
     });
 };
 
 $.timeFromSeconds = function(t){
  
    var h = Math.floor(t / 3600);
       t %= 3600;
       var m = Math.floor(t / 60);
       var s = Math.floor(t % 60);
       
//       var conv = (h > 0 ? h + ' hour' + ((h > 1) ? 's ' : ' ') : '') +
//       (m > 0 ? m + ' minute' + ((m > 1) ? 's ' : ' ') : '') +
//       s + ' second' + ((s > 1) ? 's' : '');
       var hour = "", minute = "", second = "";
       if($.timeFromSeconds.defaults.plural){
        hour = (h > 0 ? h + " " + $.timeFromSeconds.defaults.hours + ((h > 1) ? "s " : " ") : " ");
        minute =  (m > 0 ? m + " " + $.timeFromSeconds.defaults.minutes + ((m > 1) ? "s " : " "):" ");
        second =  (s > 0 ? s + " " + $.timeFromSeconds.defaults.seconds + ((s > 1) ? "s " : " "): " ");
       }else{
        hour = (h > 0 ? h + " " + $.timeFromSeconds.defaults.hours: " ");
        minute =  (m > 0 ? m + " " + $.timeFromSeconds.defaults.minutes: " ");
        second =  (s > 0 ? s + " " + $.timeFromSeconds.defaults.seconds: " ");
       }
       return hour + minute + second;
 };

 $.timeFromSeconds.setDefaults = function(defaults){
  $.timeFromSeconds.defaults = defaults;
 };
 
 $.timeFromSeconds.defaults = {
  hours:"hour",
  minutes:"minute",
  seconds:"second",
  plural:true
 };
 
 
})(jQuery);

星期一, 12月 31, 2012

[jQuery UI] autocomplete 控制項

試很久才正常的自動完成控制項, 一開始用keyup的事件綁定後,向後端拿資料,再初始化自動完成控制項, 但就是會有異常的情況,包含後端包出來的JSON的客製的,別頁又可以正常work。 最後終於試了正常的方向,在這記錄一下,以免下次要用又搞很久Orz。 測試版本為jquery ui 1.9.1版
 $( "#user" ).autocomplete({
            source: function( request, response ) {
                $.ajax({
                    url: iANGEL + "manageuser/search/" + $("#user").val(),
     cache: false,
     type:"GET",
     dataType:"json",
                    success: function( data ) {
      //check response data 
      if(data.user_data.status == 200){
       response($.map( data.user_data.result, function( item ) {
        return item;
      
       }));
      }
                       
                    }
                });
            },
   select:function(event,ui){
    $.console("[AUTOCOMPLETE] select");
    //$.console(ui.item);
    $(this).val( ui.item.User_NickName).attr("data",ui.item.User_ID);
    return false;
   }
        }).data( "autocomplete" )._renderItem = function( ul, item ) {
       //$.console(item);
       
       return $( "<li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.User_NickName + "</a>" )
        .appendTo(ul);
  };

星期五, 12月 21, 2012

[jQuery] 頁面刷新處理 (F5鍵)

找了一些偵側頁面被觸發刷新的檢查的二個範例 第一種是補捉按鍵的keycode但是如果按瀏覽器的重新整理無法偵測
$(document).bind("keypress keydown keyup", function(e) {
 
   if(e.which === 116) {
         
         return false;
      }
      if(e.which === 82 && e.ctrlKey) {
       
      
          return false;
      }
 
 });
第二種是比較好的方法,連上一頁跟下一頁都能一起觸發
$(window).bind('beforeunload', function() {

    return "Are u sure to reload?";
});

星期四, 12月 20, 2012

[jQuery API] ajaxPrefilter

//before ajax request handler
<>
$.ajaxPrefilter(function( options, originalOptions, jqXHR ){
  $.console("[ajaxPrefilter] ajax url:" + options.url);  

 });

星期日, 12月 16, 2012

[Javascript] 日期計算的應用


常常會用到又會忘記的日期格式運算。
找了一些文章說用format("yyyy-MM-dd")可以格式化但一直爆炸XD
找到的應用會直接更新在這篇。



//取得現在的日期
var currentTime = new Date(); 
//往前推30天
currentTime.setDate(currentTime.getDate() + (-30));
//第一天跟最後一天
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

 
//格式化yyyy/mm/dd
function dateFormat(date){
  var d  = date.getDate();
  var day = (d < 10) ? '0' + d : d;
  var m = date.getMonth() + 1;
  var month = (m < 10) ? '0' + m : m;
  var yy = date.getYear();
  var year = (yy < 1000) ? yy + 1900 : yy;
  
  var finalDate = year + "-" + m + "-" + d;
  return finalDate;
};

//日期相差的天數
function getDiffDays(endDate){
 var date1 = new Date();
  var date2 = new Date(Date.parse(endDate.replace("-", "/")));
  var date3 = date2.getTime() - date1.getTime();//時間差的毫秒数  
  var days = Math.floor(date3/(24*3600*1000));//相差天數
  return days;
};

星期一, 12月 10, 2012

[Javascript] Detect flash version

偵測客戶端目前有沒有裝Flash的外掛。

I agree with Max Stewart. SWFObject is the way to go. I'd like to supplement his answer with a code example. This ought to to get you started:
if(swfobject.hasFlashPlayerVersion("9.0.115"))
{
    alert("You have the minimum required flash version (or newer)");
}
else
{
    alert("You do not have the minimum required flash version");
}
Replace "9.0.115" with whatever minimum flash version you need. I chose 9.0.115 as an example because that's the version that added h.264 support.
If the visitor does not have flash, it will report a flash version of "0.0.0", so if you just want to know if they have flash at all, use:
if(swfobject.hasFlashPlayerVersion("1"))
{
    alert("You have flash!");
}
else
{
    alert("You do not flash :-(");
}

星期日, 12月 09, 2012

[Javascript] setTimeout

經常會使用的setTimeout方法,做個筆記

設定Timeout,預設只會執行一次,毫秒為單位

setTimeout(function() { myFunc(); }, 4000)

重覆執行setTimeout

function myFunc(){
  setTimeout(function(){ myFunc();},4000)
}

取消setTimeout

var timerID = setTimeout(function(){ myFunc();},4000)
clearTimeout(timerID );


設定條件停止


function myFunc(){
if(flag == true){
  setTimeout(function(){ myFunc();},4000)
}
}

星期四, 11月 29, 2012

[Javascript] 檢查IE Document Mode

客戶遇到ie無法正確指定文件模式的問題。 只要在ui加上<meta http-equiv="X-UA-Compatible" content="IE=edge">,即可。 不過要避免在它之前有其他script執行(網民建議)。 不過今天在客戶那邊處理的時候,之前把content內多加了一個IE=edge,chrome=1,會導致無法正確告訴ie使用最新的文件模式檢視(content)。 以下的語法可以偵測目前用戶的文件模式。
function checkIEDocumentMode(){
 
 if (window.navigator.appName == "Microsoft Internet Explorer")
 {
    if (document.documentMode){
     USERAGENT = document.documentMode;
    } // IE8
    else // IE 5-7
    {
     USERAGENT = 5; // Assume quirks mode unless proven otherwise
       if (document.compatMode)
       {
          if (document.compatMode == "CSS1Compat")
           USERAGENT = 7; // standards mode
       }
    }
    // the USERAGENT variable now contains the document compatibility mode.
    $.console("checkIEDocumentMode:" + USERAGENT);
    //var $metaTag = $("");
    //$metaTag.appendTo("head");
    //content="IE=Value" value types:5、6、7、8、9、10、EmulateIE7、EmulateIE8、Edge
 }
}

星期五, 11月 23, 2012

[jQuery] 價錢格式化

想要讓你網站顯示的數字讓使用者更容易閱讀嗎?
可以使用jquery price format 來快速完成唷
http://jquerypriceformat.com/


星期日, 11月 18, 2012

[Java] Hashmap Race condition

最近發生了一個hashmap的嚴重bug,跟同事查了才知道這是Java hashmap常見的問題之一。
由此可見大家都是java的菜鳥XD,
發生原因在於hashmap當滿了之後,如果有多個threads同時對他put或get就會產生Race Condition。
所以可以採用Java Synchronized來處理。參考這位大大的心得:[Java] Synchronized 心得
總共有三種方法可以使用

[jQuery plugin] ajaxForm 與 validator 整合範例

時常會需要利用到jquery form與 validator 二個元件整合的應用。 把範例記錄一下 :D 範例網址:
注意在submithandler事件裡面要改用ajaxSubmit的方法而不是ajaxForm。

http://jquery.bassistance.de/validate/demo/ajaxSubmit-intergration-demo.html

jQuery(function() {
  // show a simple loading indicator
  var loader = jQuery('
loading...
') .css({position: "relative", top: "1em", left: "25em", display: "inline"}) .appendTo("body") .hide(); jQuery().ajaxStart(function() { loader.show(); }).ajaxStop(function() { loader.hide(); }).ajaxError(function(a, b, e) { throw e; }); var v = jQuery("#form").validate({ submitHandler: function(form) { jQuery(form).ajaxSubmit({ target: "#result" }); } }); jQuery("#reset").click(function() { v.resetForm(); }); });

星期二, 11月 13, 2012

[Alfresco] User Quota Issue

如何讓alfresco的quota即時更新, alfresco的工程師說可透過Java backend的ContentUsageService.getUserUsage(userName) 或 覆寫userUsageCollapseJob
https://forums.alfresco.com/en/viewtopic.php?f=27&t=43431
You should be able to get the up-to-date user usage via ContentUsageService.getUserUsage(userName) or else you could consider overriding the userUsageCollapseJob to run more often (eg. every minute instead of every 5 minutes).

If you're running Enterprise 3.4.6 and need more help with this issue then please contact Alfresco Support (if you haven't already).

Regards,
Jan

Ref:
Interface ContentUsageService

星期一, 11月 12, 2012

[Java] GZIP Filter 與 404 錯誤頁面的臭蟲

起因:
GZIPFilter壓縮遇到不存在的網頁會爆炸,如下所示:


這個網頁無法使用

http://serverip/test.jspddd 的網頁可能暫時無法使用或被永久移至新網址。
錯誤 330 (net::ERR_CONTENT_DECODING_FAILED): 未知的錯誤。


2012/11/13
目前尚未找到解法,不過透過HttpServletResponseWrapper目前竟然無法成功拿到各網頁的content,唯有在最後一層的Filter呼叫啊HttpServletResponseWrapper才有辦法拿到



Reference:
What is the simplest way to display httpServletResponse.sendError(403, “My Message”) status from JSTL
How to make a filter to detect if the user requested a not found page?

[Hadoop] WordCount Sample


記錄一下第一次跑Hadoop WordCount Job的過程 :)

1. 建立HDFS資料夾
#全部的資料夾會自動建立
hduser@hadoop-master:/usr/local/hadoop$hadoop dfs -mkdir /home/hduser/wordcount

2. 匯入要分析的文件資料(local-dir)到HDFS資料夾

$hadoop dfs -copyFromLocal
#匯入
hduser@hadoop-master:/usr/local/hadoop$hadoop dfs -copyFromLocal /home/hduser/wordcount /home/hduser/wordcount

#查看匯入的資料
hduser@hadoop-master:/usr/local/hadoop$ hadoop dfs -ls /home/hduser/wordcount
Warning: $HADOOP_HOME is deprecated.

[Hadoop] WordCount

在寫Hadoop job的時候,如果你有分package的話,
匯出.jar的時候請記得選取Main Class進入點,如下所示

然後再執行job的時候就不會說找不到了
hadoop@client:~/wordcount$ hadoop jar exercise.wordco.jar WordCo /user/hadoop/wordcount/pg5000.txt /user/hadoop/wordcount/output



星期五, 11月 09, 2012

Chrome: Uncaught SyntaxError: Unexpected end of input


Chrome: Uncaught SyntaxError: Unexpected end of input

今天遇到一個找很久的BUG,
本來以為是JS裡面的{}沒對好,結果是網頁上的超連結的javascript:void(0)設錯了==
少打了void後面的(0)
這個手殘的錯誤似乎出現好幾次了XD


[jQuery plugin] 如何reset from

jquery validator常常submit完要重新清除,常用到的語法。
在此記錄一下。

$(form)[0].reset();

[jQuery plugin] validator fileupload


記錄如何驗證上傳元素,只要加上accept,filesize即可。

 fileToUpload:{ 
accept: "png|jpe?g|gif",
filesize: 1048576
 }

[jQuery plugin] Validator 如何在選擇元素select驗證

常常會用到的validator於選擇元素上的驗證,原來也是加個required就好,記一下 XD

$("#bankForm").validate({
   rules:{
    
     citys:{
     required:true
     }
                     
});
最後發現請選擇的option的value要記得設"",不然會無法動作。

                               
                           

星期六, 11月 03, 2012

[Javascript] 檢查json的key是否存在



太常用到了,記錄一下。使用hasOwnProperty就可以輕鬆解決嚕 wow

You don't need jQuery for this, just JavaScript. You can do it a few ways:
  • typeof d.failed- returns the type ('undefined', 'Number', etc)
  • d.hasOwnProperty('failed')- just in case it's inherited
  • 'failed' in d- check if it was ever set (even to undefined)

星期四, 11月 01, 2012

[Alfresco] Upload Avatar Javascript API


//js

/**
 * User Profile Avatar Upload method
 *
 * @method POST
 * @param username {string}
 *        filedata {file}
 */

function main()
{
   try
   {
      var filename = null;
      var content = null;
      var username = null;

      // locate file attributes
      for each (field in formdata.fields)
      {
         if (field.name == "filedata" && field.isFile)
         {
            filename = field.filename;
            content = field.content;
         }
         else if (field.name == "username")
         {
            username = field.value;
         }
      }

      // ensure all mandatory attributes have been located
      if (filename == undefined || content == undefined)
      {
         status.code = 400;
         status.message = "Uploaded file cannot be located in request";
         status.redirect = true;
         return;
      }
      if (username == null || username.length == 0)
      {
         status.code = 500;
         status.message = "Username parameter not supplied.";
         status.redirect = true;
         return;
      }

      var user = people.getPerson(username);
      // ensure we found a valid user and that it is the current user or we are an admin
      if (user == null ||
          (people.isAdmin(person) == false && user.properties.userName != person.properties.userName))
      {
         status.code = 500;
         status.message = "Failed to locate user to modify or permission denied.";
         status.redirect = true;
         return;
      }

      // ensure cm:person has 'cm:preferences' aspect applied - as we want to add the avatar as
      // the child node of the 'cm:preferenceImage' association
      if (!user.hasAspect("cm:preferences"))
      {
         user.addAspect("cm:preferences");
      }

      // remove old image child node if we already have one
      var assocs = user.childAssocs["cm:preferenceImage"];
      if (assocs != null && assocs.length == 1)
      {
         assocs[0].remove();
      }

      // create the new image node
      var image = user.createNode(filename, "cm:content", "cm:preferenceImage");
      image.properties.content.write(content);
      image.properties.content.guessMimetype(filename);
      image.properties.content.encoding = "UTF-8";
      image.save();

      // wire up 'cm:avatar' target association - backward compatible with JSF web-client avatar
      assocs = user.associations["cm:avatar"];
      if (assocs != null && assocs.length == 1)
      {
         user.removeAssociation(assocs[0], "cm:avatar");
      }
      user.createAssociation(image, "cm:avatar");

      // save ref to be returned
      model.image = image;
   }
   catch (e)
   {
      var x = e;
      status.code = 500;
      status.message = "Unexpected error occured during upload of new content.";
      if(x.message && x.message.indexOf("org.alfresco.service.cmr.usage.ContentQuotaException") == 0)
      {
         status.code = 413;
         status.message = x.message;
      }
      status.redirect = true;
      return;
   }
}

main();



//description

  Avatar Upload
  Upload avatar file content and apply to person preferences
 
  user
  required
  /slingshot/profile/uploadavatar



//template
{
<#if person.childAssocs["cm:preferenceImage"]??>
"avatar": "${person.childAssocs["cm:preferenceImage"][0].downloadUrl}"
</#if>
<#if person.associations["cm:avatar"]??>
<#if person.associations["cm:avatar"][0].childAssocs["rn:rendition"]??>
,"avatarthumb": "${person.associations["cm:avatar"][0].childAssocs["rn:rendition"][0].downloadUrl}"
</#if>
</#if>
}

星期三, 10月 24, 2012

[Java] 取得Image的byte[]

今天廠商在哭爸圖片解析度太低,只好先把JPEG壓縮拿掉。
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(encoderOutputStream);
encoder.encode(bufferedResizedImage);
查了一下如何把BufferedImage轉成Byte[]存在db,或你其他的需求。
BufferedImage originalImage = ImageIO.read(new File("c:\\image\\mypic.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( originalImage, "jpg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
這篇文章好心整理了java中的幾個處理方法,有空可以看看。
High-Quality Image Resize with Java

星期日, 10月 21, 2012

[Javascript] Callback function

Callback在寫oop的javascript中非常好用, 找到了一篇非常容易理解的好文章。
Callback Functions in JavaScript
function mySandwich(param1, param2, callback) {
    alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
    if (callback && typeof(callback) === "function") {
        callback();
    }
}

mySandwich('ham', 'cheese', 'vegetables');

星期六, 10月 20, 2012

[jQuery] ajax 異常錯誤

昨天遇到一個很奇怪的AJAX呼叫錯誤, 最後發現觸發的元素內的javascript:void(0)打錯了,導致JS異常=.= 找了一陣子才找到,真是扯XD

星期二, 10月 16, 2012

[JSON] 取得json keys 列表

原本都用陣列來儲存列表,這次遇到用keys來表示原本陣列的數量<
for (var key in repaymentlist) 
  {
   if (repaymentlist.hasOwnProperty(key))
   {
    $.console(repaymentlist[key]);
    
   }
  }

星期四, 10月 11, 2012

[Javascript] 取得物件的類別名稱

如果取得你自訂類別的名稱

function getClassName(obj) {
if (typeof obj != "object" || obj === null) return false;
return /(\w+)\(/.exec(obj.constructor.toString())[1];
}

星期三, 9月 26, 2012

[jQuery] ie8 元素id與js變數產生衝突

今天程式發生了一個IE8 bug,因使用js來做前端的i18n,但同事有把元素的id取得跟i18n js的變數一樣,導致js錯誤發生。

 HTML
<span id=”stupid_ie_8”></span>

//i18n key
stup_ie_8 = “IE好弱”;

//script
$(“#stupid_ie_8”).html(stup_ie_8);

星期二, 9月 25, 2012

[jQuery] append function error in IE8

今天被fire一個bug,有關於append元素的時候,畫面沒有被顯示。
主要是append的元素結構沒有正常的結尾,ie8無法自動修正。

一般html頁面元素沒有正常結尾也會空白

星期三, 9月 19, 2012

[jQuery API] 拍賣倒數計時器 min seconds: 倒數十下

現在所有團購網都流行的倒數計時器方法,參考至某團購網站XD

$(function() {
    setInterval(function () {
  var m = parseInt($('#mis').text());
  //console.log("start m:" + m);
  if (isNaN(m)) {
   $('#mis').text('0');
  } else {
   m=m+10;
   //console.log("m:" + m);
   if (m>=10) { 
    m=m-1;   
    if(m>=10)
    {
     $('#mis').text(m-10);
    }
    else
    {
     $('#mis').text(m);
    }
   } 
  }
 }, 100);//setInterval
 });  

星期六, 9月 15, 2012

[jQuery plugin] jquery Validator表單驗證器 番外篇(進階一點的需求吧XD)

Validator真是好物呀,先前有整理一個入學篇,覺得篇福愈來愈長了,
遇到的新問題就記在這篇吧!!

Q.如何指定要特地驗證某一個欄位
有時候你只想要透過別的動作來檢查某個欄位,可以使用valid方法,回傳值為1:驗證通過,0:驗證失敗

var validateForMoney = $("#borrowMoney").valid()//1:ok,0:false
$.console("validateForMoney:" + validateForMoney);
var validateForRate = $("#borrowRate").valid();
$.console("validateForRate:" + validateForRate);

Q.取得全部驗證失敗的欄位有哪些?
//透過numberOfInvalids方法就會回傳數字了,$validatedPostBorrow是我驗證器的變數
$.console("invalid fields:" + $validatedPostBorrow.numberOfInvalids());


Reference:
jQuery Validate Plugin - Trigger validation of single field

星期二, 9月 04, 2012

[jQuery plugin] 來個倒數計時器吧

倒數計時器能增加使用者有感的提示XD常用到拍賣商品上的特效。
找了幾個現成的元件
請參考以下這篇網誌的20以上的jQuery countdown plugins (有擷圖)
http://www.tripwiremagazine.com/2012/05/jquery-countdown-scripts.html

星期一, 9月 03, 2012

[jQuery API] 實作Facebook的捲軸拉到底更新資訊 Facebook like scroll bar detection

如何使用jQuery偵測捲軸的位置!! 實作Facebook like的更新狀態列記錄
$(function () {
             var $win = $(window);

             $win.scroll(function () {
                 if ($win.scrollTop() == 0)
                     alert('Scrolled to Page Top');
                 else if ($win.height() + $win.scrollTop()
                                == $(document).height()) {
                     alert('Scrolled to Page Bottom');
                 }
             });
         });


Here's some explanation:

$(window).height() - returns height of browser viewport

$(document).height() - returns height of HTML document

$(window).scrollTop() – returns the current vertical position of the scroll bar.

So if the scroll bar is at the very top, the value of $(window).scrollTop() will be Zero. Similarly if the value of the browser viewport + vertical position of scroll bar = document height, then the user has scrolled to the bottom of the page.

寫成外掛的方式來看看!!

星期四, 8月 30, 2012

[Javascript] Closure Compiler

在使用yui compressor時遇到編譯失敗的問題,可透過Google closure compiler:http://closure-compiler.appspot.com/home找到檔案為何無法正確編譯(但js與css能正常於網站執行),錯誤的問題不外乎是語法不嚴僅,如使用到保留字等等。


[Regex] 找出不包含特定字的結果 don't contain specified word


http://www.anydotcom.com/test/search.cfm?metric=blah&selector=size&value=1
http://www.anydotcom.com/test/search.cfm?metric=blah2&selector=style&value=1
http://www.anydotcom.com/test/search.cfm?metric=blah3&selector=size&value=1
http://www.anydotcom.com/test/details.cfm?metric=blah&selector=size&value=1

找出不包含details.cfm這個字的
(^((?!details.cfm).)*$)

Reference:

星期日, 8月 05, 2012

[Java] Jersey @DefaultValue

有時候你的參數是選項輸入的,即可使用 @DefaultValue
public String getOwnerQuoteList(
   
   @PathParam(value="OWP_ID") String OWP_ID,
   @DefaultValue("1") @QueryParam(value="page") int pageIndex,
   @DefaultValue("10") @QueryParam(value="size") int pageSize,
   @DefaultValue("dateline")@QueryParam(value="sort") String sort,
   @DefaultValue("false") @QueryParam(value="asc") boolean asc) throws JSONException{

}

星期六, 8月 04, 2012

[jQuery] $.ajax 讀取影像

似乎不需要弄$.ajax也可以達到這個需求XD

var img = $("#imgElem").attr('src', 'http://somedomain.com/image.jpg')
                      .load(function() {
                         if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                             alert('broken image!');
                         } else {
                             $("#something").append(img);
                         }
                      });

Reference:

星期三, 8月 01, 2012

[Java] 快快樂樂使用 Jersey MVC 架構

先前利用jersey都只有在controller端直接將JSON物件轉成字串輸出,
jersey也提供MVC的方式來支援JSP來做template(View)
讓畫ui結構更直覺多了。

其他你感興趣的文章

Related Posts with Thumbnails