星期二, 7月 31, 2012

[jQuery plugin] Pagination

分頁元件產生 :),採用的為以下這個jquery pagination
http://www.d-scribe.de/webtools/jquery-pagination/demo/demo_options.htm

範例:
$("#pageContainer").pagination(
      total,
      {
       items_per_page:PAGESIZE,
       num_display_entries:10,
       num_edge_entries:2,
       link_to:"javascript:void(0)",
       prev_text:"上一頁",
       next_text:"下一頁",
       callback:function(currentPage,container){
});

其他的分頁
http://blog.ajaxmasters.com/jquery-pagination-plugin/ 
http://tympanus.net/codrops/2009/11/17/jpaginate-a-fancy-jquery-pagination-plugin/

[Javascript] Validate E-mail

驗證信箱格式,讚的次數蠻高的,參考至這篇討論 Validate email address in Javascript?
function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\
".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 
其他驗證語法 ^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$

星期一, 7月 30, 2012

[Jersey] Client Post

Form post

MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
ClientResponse response = webResource.type("application/x-www-form-urlencoded").post(ClientResponse.class, formData);

Post JSON
需要注意在post json要這樣使用webResource.type(MediaType.APPLICATION_JSON).post(), 否則會回傳 415 Unsupported media type
public String isExist(
   String parentUUID,
   String objName,
   String alf_ticket){
  
  String response = null;
  
  String apiURL = this.getEndpoint() + "/repo/object/check?ticket=" + alf_ticket;
  
  this.client = Client.create();
  
  //input body
  JSONObject jsonBody = new JSONObject();
  try {
   jsonBody.put("parentUUID", parentUUID);
   jsonBody.put("objName", objName);
  } catch (JSONException e) {
   System.out.println("[RepositoryObject] Fail to create json");
  }
  
  //create resource
  this.webResource = this.client.resource(apiURL);
//  this.webResource.type("application/json");
  
  //do post
  this.clientResp =  webResource.type(MediaType.APPLICATION_JSON).post(
    ClientResponse.class,jsonBody.toString());
  
  //get string of response
  response = this.clientResp.getEntity(String.class);
  
  System.out.println("[RepositoryObject] status:" + this.clientResp.getStatus());
  System.out.println("[RepositoryObject] response:" + response);
  
  return response;
 }

星期四, 7月 19, 2012

[jQuery plugin] $.address 快速連按上下頁按鈕

最近實作記錄讓ajax執行後能記錄行為到瀏覽器的上下頁按鈕, 因而選擇了$.address plugin。 原本運作上蠻正常的,不過在Firefox上面快速的連按上或下一頁按鈕時,會造成整個ui畫出來不對的現在。 因為firefox ajax request順序時間差不一致造成,因此在URL Change Event加入Queue即可解決。

 $.address.externalChange(function(event){
//  $.console("[address externalChange] event value:" + event.value);
  var controller = event.pathNames[0];
    var parameter = event.pathNames[1];
    if(!isNullOrUndefiend(controller)){
//     $.console("[address externalChange] Trigger currentFolder:" + currentFolder);
     //2012/07/19
     //When click back button quickly on firefox, 
     //must use queue to avoid duplicated data binding  
     $(this).queue(function(){
      addressEventHandler(controller,parameter);
      $(this).dequeue();
     });
    }else{
     $.console("[address externalChange] Controller not found");
    }
 }); 

Tip:有時候外掛會無法取得externalChange event.value的值,目前還沒找出正確原因。目前直接用變更外部連結的方法處理。
window.location.href = "yourpage.jsp#ControllerName/ + "Parameters";

星期三, 7月 18, 2012

[jQuery API] 指定多重條件的selector (Multiple Attribute Selector)

有時候需要透過多個條件濾掉不需要的元素,
順便記錄一下,方便好查:)
[]區開就好,以下範例是指綁定No equal的


$("#manage_title").find("div[class!=manage_avatar][class!=manage_action]").click(function(){

});


Reference:
http://api.jquery.com/multiple-attribute-selector/

星期日, 7月 15, 2012

[jQuery api] Stop ajax

如何停止執行中的ajax的request,在執行ajax呼叫後,會回傳一個instance,再透過abort即可停用。


var request = $.ajax({
    type: 'POST',
    url: 'someurl',
    success: function(result){}
});
然後再把request abort即可
request.abort();

[jQuery plugin] Validator 驗證多個Radio跟checkbox範例

今天遇到要檢查多個checkbox至少要選一下就順便記錄一下。
只要將你的checkbox內的name屬性設為 <你取的名字>[]
如下範例 candidate_usr[],記得要加上陣列的符號[]

 $("#candidateForm").validate({
    rules:{
     'candidate_usr[]':{
      required:true
     }
    },
    messages:{
     'candidate_usr[]':{
      required: "請至少選擇一名委託者"
     }
    },
    submitHandler: function(form) {
     //get candicates 
     var $checkboxes 
      = $("#candidateForm").find("input:checkbox:checked").each(
       function(i,cbObj){
        var selectedExpertID = $(cbObj).val();
        $.console("selected id:" + selectedExpertID);
       });
    
    }
  });

Reference:
http://jquery.bassistance.de/validate/demo/radio-checkbox-select-demo.html

星期一, 7月 02, 2012

[Alfresco] 實作alfreso javabacked 上傳心得 How to upload file using java backed web script

本文記錄使用Java API實作上傳的測試心得
上網找到的取得HttpServletRequest 都不適用於alfresco 3.4.5版本

// NOTE: This web script must be executed in a HTTP Servlet environment
//        if (!(req instanceof WebScriptServletRequest)) {
//                throw new WebScriptException(
//                                "Content retrieval must be executed in HTTP Servlet environment");
//        }
     
// HttpServletRequest httpReq = ((WebScriptServletRequest)req).getHttpServletRequest();

發生錯誤如下: ClassCastException


protected Map<string, object> executeImpl(
   WebScriptRequest req,
   Status status, 
   Cache cache) {
WrappingWebScriptRequest wrappingWebScriptRequest = (WrappingWebScriptRequest) req;
  WebScriptRequest webScriptRequest = wrappingWebScriptRequest.getNext(); 
  WebScriptServletRequest servletRequest = (WebScriptServletRequest) webScriptRequest;
  FormField uploadFile = servletRequest.getFileField("file");
  //file field     
  uploadFileName = uploadFile.getFilename();
     uploadMIMEType = uploadFile.getMimetype();
     uploadContent = uploadFile.getInputStream();
     System.out.println("[form data] filename:" + uploadFileName);
     System.out.println("[form data] mimetype:" + uploadMIMEType);
//do something
}

用以下這段程式就能正常取得上傳檔案了,先前的中文問題出在client指定錯誤編碼了,繞了一大圈竟然是手誤呀!!
  

//how to get WebScriptServletRequest
  WrappingWebScriptRequest wrappingWebScriptRequest = (WrappingWebScriptRequest) req;
  WebScriptRequest webScriptRequest = wrappingWebScriptRequest.getNext(); 
  WebScriptServletRequest servletRequest = (WebScriptServletRequest) webScriptRequest;
  
  //get data form form
  FormData formData = (FormData)servletRequest.parseContent();
  FormData.FormField[] formFields = formData.getFields();
  int fieldsLen = formFields.length;
  for(int i=0;i

如果要做更複雜的行為不在這篇的討論範例 :)

星期三, 6月 27, 2012

[Alfresco ] How to update content with ContentWriter class

此問題欲解決要利用ContentWriter變更Node的內容, 不是指新增版本的方式,目前尚未用到,待驗證 :)
ContentWriter contentWriter = contentService.getWriter(nodeCurrentLogFile, ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype("text/plain");
FileChannel fileChannel = contentWriter.getFileChannel(false);
ByteBuffer bf = ByteBuffer.wrap(logLine.getBytes());
fileChannel.position(contentWriter.getSize());
fileChannel.write(bf);
fileChannel.force(false);
fileChannel.close();

星期一, 6月 25, 2012

[Alfresco] Java Foundation API

記錄一下Alfresco low level的java API學習資源 :)


Content repository services

Content repository services are the fundamental services for working with content in Alfresco. Content repository services are written in Java.
Content repository services are built on the storage and query engines. As with the engines, the same infrastructure is shared. The concept of users and groups is introduced into these services, such as recording the author of content, who has content locked or access to content. Implementation of the standards-defined services is packaged into the Alfresco content repository.
Out-of-the-box content repository services provide capabilities to:
  • Organize and manage content
  • Control versions
  • Record changes and updates
  • Enforce security
  • Model content types
  • Search for information in the repository



Search Service
http://wiki.alfresco.com/wiki/Search#Search_Parameters
https://wiki.alfresco.com/wiki/Search_Documentation#Lucene_Language
How to exceed Lucene Limit Search?

[Java] Jersey Client

本文記錄如何使用Jersey client API
Reference:
https://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with

星期二, 6月 19, 2012

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

這個範例在Google都找的到,沒做多大的修改。
重點是記錄Spring Bean XML的差異性。
Spring Bean XML 
重點在於property標籤設定,如果你參考了foundation的api請記得把他加進來!!,
所以這個範例要使用了Repository,請設定rel=repositoryHelper。
 <bean
         id="webscript.org.example.simplejavadir.get"
         class="org.example.SimpleJavaDir"
         parent="webscript">
                <property name="repository" ref="repositoryHelper"/>
        </bean>

Java backed controller
透過xml的設定, 就可以透過 public void setRepository(Repository repository) {}直接呼叫alfresco的核心api了。
package org.example;
import java.util.HashMap;
import java.util.Map;

import org.alfresco.repo.model.Repository;
import org.alfresco.service.cmr.repository.NodeRef;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.webscripts.Cache;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptException;
import org.springframework.extensions.webscripts.WebScriptRequest;

public class SimpleJavaDir extends DeclarativeWebScript {
 
 private Repository repository;
 
    private static Log s_logger = LogFactory.getLog(SimpleJavaDir.class);


 public void setRepository(Repository repository) {
  this.repository = repository;
 }

 @Override
 protected Map<string, object>  executeImpl(WebScriptRequest req,
   Status status, Cache cache) {

  s_logger.debug("SimpleJavaDir entry");
  
  // extract folder listing arguments from URI
  String verboseArg = req.getParameter("verbose");
  Boolean verbose = Boolean.parseBoolean(verboseArg);
  Map<string, string>  templateArgs = req.getServiceMatch().getTemplateVars();
  String folderPath = templateArgs.get("folderpath");
  String nodePath = "workspace/SpacesStore/" + folderPath;

//  @param1 one of "node", "path", or "avmpath"
  NodeRef folder = repository.findNodeRef("path", nodePath.split("/"));
  // validate that folder has been found
  if (folder == null) {  
   throw new WebScriptException(Status.STATUS_NOT_FOUND, "Folder "
     + folderPath + " not found");
   //you will see the followning messages in your server
//    ERROR [extensions.webscripts.AbstractRuntime] Exception from executeScript - redirecting to status template error: 05190001 Folder Company Homes not found

  }
  
  // construct model for response template to render
   Map<string, object> model = new HashMap<string, object>();
  model.put("verbose", verbose);
  model.put("folder", folder);
  model.put("nodePath", nodePath);
  return model;
 }
}


星期日, 6月 10, 2012

[Java] Zxing create a QRCode

http://www.cnblogs.com/tompandas/archive/2012/04/10/2440513.html
http://code.google.com/p/zxing/downloads/list

[phpmyadmin] stored procedure and trigger

查看目前已建立的stored procedure
show procedure status

查看目前已建立的stored procedure


select * from information_schema.routines where routine_type = 'procedure'


查看指定資料庫內已有的stored procedure


select * from information_schema.routines where routine_type = 'procedure' and routine_schema = 'your_db'

新建stored procedure


  1. Open phpMyadmin.
  2. Select a database to work with.
  3. Open the SQL tab.
  4. Select all of the SQL statements between the DELIMITER statements in your stored procedure script. Do not include the DELIMITER statements! Here’s what my example script should look like:
    DROP PROCEDURE IF EXISTS spFoo $$
    CREATE PROCEDURE spFoo ()
    BEGIN
     SELECT 'Foo' FROM DUAL;
    END $$
    
  5. In the delimiter field, just below the SQL editor’s text area, enter $$ as your delimiter.

Reference:
如何使用MySQL的Stored Procedure與Trigger
Using phpMyAdmin to Create Stored Procedures

星期日, 6月 03, 2012

[Java] Jersey Session

Session控制
@Path("/helloworld")
public class HelloWorld {

    @GET
    @Produces("text/plain")
    public String hello(@Context HttpServletRequest req) {

        HttpSession session= req.getSession(true);
        Object foo = session.getAttribute("foo");
        if (foo!=null) {
                System.out.println(foo.toString());
        } else {
                foo = "bar";
                session.setAttribute("foo", "bar");
        }
        return foo.toString();


    }
}

[Java] java.lang.UnsupportedClassVersionError: example/Hello : Unsupported major.minor version 51.0 (unable to load class example.Hello)

今天在local編譯完java後,丟到機器後就爆炸了。
是JDK版本不一樣導致XD,記錄一下這個痛!!

java.lang.UnsupportedClassVersionError: example/Hello : Unsupported major.minor version 51.0 (unable to load class example.Hello)

Major Class Versions of Various JDK
Following are the major version of class file format in standard JDK environment.

JDK 1.1 = 45
JDK 1.2 = 46
JDK 1.3 = 47
JDK 1.4 = 48
JDK 1.5 = 49
JDK 1.6 = 50

[Java] org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]

案例:
本地端(mac)的JRE使用1.7的64bit版本,build出來的程式在機器上都爆炸XD
目前先把elicpse的環境設回1.6的版本就可以在server正常跑了。
有遇到一樣情形的朋友一定要先確定Java的版本到底有沒有一致

專案按右鍵選擇Properties設定
JAVA BUILD PATH 設定


JAVA COMPILER 設定

其他你感興趣的文章

Related Posts with Thumbnails