Total Pageviews

2011/09/23

There are no resources that can be added or removed from the server


Today I simply would like to deploy my ear file to WAS (Web Application Server) as usual. 


But it fail to find my EAR file:
 

I spent more than two hours to find its root cause and solution. But it's still in vain.
Finally, I decide to give up. I just switch to another workspace and check out source code from SubVersion, then it's going to normal. I don't know why!
 

2011/09/22

2011/09/21

2011/09/17

net.sf.json.JSONException: org.apache.openjpa.lib.util.ParseException

Scenario
當使用者輸入異常代號,系統要自動帶出違章編號徵銷管理代號應納金額已納金額等欄位。

 


Problem
在Controller,我們會去呼叫後端service class,根據使用者所輸入的異常代號進行搜尋,帶回符合條件的entity(i.e. NIGT900),但是在轉成JSONObject的時候,出現下列錯誤訊息:
net.sf.json.JSONException: org.apache.openjpa.lib.util.ParseException: Errors occurred while creating property descriptors for the following properties: [RefreshFromDataCache, CacheMarshallers, jdbc.QuerySQLCache, jdbc.CollectionId, AccessIntent].
at net.sf.json.JSONObject._fromBean(JSONObject.java:987) ~[json-lib-2.3-jdk15.jar:na]


Root Cause
由於回傳的entity(i.e. NIGT900)有一個資料型態為Timestamp的欄位,導致會出現此錯誤



Solution
利用JsonConfig將timeStamp欄位exclude掉

Result



2011/09/15

How to Organize Imports Automatically in Eclipse

Problem
When using Eclipse, I find myself typing Ctrl+Shift+O several times, to organize imports (usually imports which are no longer required, generating warnings).



Solution
Preferences->Java->Editor->Save Actions->Check "Perform the selected actions on save" --> Check "Organize Imports"



See....after save action had been trigger, it will organize imports automatically
 

2011/09/10

tutorials point

一個還不錯的技術學習網站: http://www.tutorialspoint.com/index.htm


2011/09/09

JPA Annotation @JoinColumn / @JoinColumns 應用

Scenario
我們在利用JPA(Java Persistence API)的時候,code generator會自動幫table之間有關連的部份產生出來,但是在實際應用上,有可能table之間沒有關連性,但是卻需要來做join抓取資料的需求。


此時就要自行在該entity上宣告變數與join的欄位。若是single column的狀況下,可以採用@JoinColumn,若是composite column的話,可以採用@JoinColumns


Demo
NIGT001與NIGT007雖然沒有relationship,但是在實際應用上,常會做JOIN,彼此透過single column來做Join





在原本的NIGT001增加nigt007此attribute,並產生setter/getter methods,註明兩張table之間的relationship,name的部份是NIGT001的欄位,referencedColumnName的部份是NIGT007的欄位名稱,此二table彼此是透過上述欄位來進行join
 




NIGT001與NIGT022雖然沒有relationship,但是在實際應用上,常會做JOIN,彼此透過composite column來做Join





在原本的NIGT001增加nigt022此attribute,並產生setter/getter methods,註明兩張table之間的relationship,name的部份是NIGT001的欄位,referencedColumnName的部份是NIGT022的欄位名稱,此二table彼此是透過上述欄位來進行join




Checkbox/Radio Button filters with jQuery

Scenario
當使用者輸入查詢條件,並按下查詢按鈕,系統會自動將符合條件的資料呈現於data grid中,使用者選擇某筆資料,點選查詢

當使用者點選查詢後,系統會將資料庫的資料帶入dialog中:
 
系統會根據欄位值來決定radio button要預設選擇哪一個,以及決定checkbox是否要打勾


 Radio button



原本的寫法:


採用filter的寫法:


Checkbox

 原本的寫法:

 採用filter的寫法:


有關filter的文件,請參考:http://api.jquery.com/filter/





2011/09/08

net.sf.json.JSONException: There is a cycle in the hierarchy!


Problem
I apply JPA(Java Persistence API) to do search via primary key, then it return an object to me. And I would like to covert this object to JSONObject, it show this error message.

1
2
3
4
5
6
7
net.sf.json.JSONException: There is a cycle in the hierarchy! 
at net.sf.json.util.CycleDetectionStrategy$StrictCycleDetectionStrategy.handleRepeatedReferenceAsObject(CycleDetectionStrategy.java:97) 
at net.sf.json.JSONObject._fromBean(JSONObject.java:674)
at net.sf.json.JSONObject.fromObject(JSONObject.java:181) 
at net.sf.json.JSONArray._processValue(JSONArray.java:2381) 
at net.sf.json.JSONArray.processValue(JSONArray.java:2412) Truncated. 
see log file for complete stacktrace


The code snippet as shown below


Root Cause
Because the entity you return has many-to-one relationship, so you need to filter them out.

Solution



Reference: http://json-lib.sourceforge.net/snippets.html

2011/09/07

How to Automatically Add Javadoc and File Headers to Your Source Code

Problem
In our project, we need to fix all checkstyle checking errors. One of the most annoying error is missing a Javadoc comment.





Solution
We can install an Eclipse Plugin, JAutodoc, to help us.
JAutodoc is an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers.
Official site: http://jautodoc.sourceforge.net/index.html


Where to download?





How to Install?
1. Before you install, please shutdown your eclipse
2. copy two jar files to plugins folder
3. copy one feature folder to features folder

4. Restart Eclipse


How to Use?
Select a single or multiple class(es): right click --> JAutodoc --> Add Javadoc


 JAutodoc will generate comments from element name as shown below
 
 JAutodoc will generate comments from method name as shown below






2011/09/05

How to Adjust Your Eclipse's Tab Policy to Spaces Only


1. Window --> Preference

2. Use "formatter" as keyword to search --> New


3. Give it a new name in New Profile dialog --> Click OK 

4. In General Settings, choose "Spaces Only" in Tab policy

5. Click OK

2011/09/03

ADMA0174E: The filepermission argument contains an invalid formator contains an invalid regular exp

Problem

As I try to deploy my ear file to WAS(WebSphere Application Server), it show this error message

[10/09/03 15:22:21:394 GMT] 00000031 SystemErr R com.ibm.websphere.management.exception.AdminExcept ion: ADMA0174E: The filepermission argument contains an invalid format or contains an invalid regular expression pattern: {0}. Correct format is file_pattern=permission. Multiple filepermissions are separated by a # (Example: .*\.jsp=644#.*\.xml=744).
[10/09/03 15:22:21:394 GMT] 00000031 SystemErr R at com.ibm.ws.management.application.UpdateSchedulerI mpl.validateParams(UpdateSchedulerImpl.java:301)
[10/09/03 15:22:21:394 GMT] 00000031 SystemErr R at com.ibm.ws.management.application.UpdateSchedulerI mpl.setupTasks(UpdateSchedulerImpl.java:214)
[10/09/03 15:22:21:410 GMT] 00000031 SystemErr R at com.ibm.ws.management.application.SchedulerImpl.ru n(SchedulerImpl.java:250)
[10/09/03 15:22:21:410 GMT] 00000031 SystemErr R at java.lang.Thread.run(Thread.java:797)
[10/09/03 15:22:33:301 GMT] 00000034 SystemErr R com.ibm.websphere.management.exception.AdminExcept ion: ADMA0174E: The filepermission argument contains an invalid format or contains an invalid regular expression pattern: {0}. Correct format is file_pattern=permission. Multiple filepermissions are separated by a # (Example: .*\.jsp=644#.*\.xml=744).
[10/09/03 15:22:33:301 GMT] 00000034 SystemErr R at com.ibm.ws.management.application.UpdateSchedulerI mpl.validateParams(UpdateSchedulerImpl.java:301)
[10/09/03 15:22:33:301 GMT] 00000034 SystemErr R at com.ibm.ws.management.application.UpdateSchedulerI mpl.setupTasks(UpdateSchedulerImpl.java:214)
[10/09/03 15:22:33:301 GMT] 00000034 SystemErr R at com.ibm.ws.management.application.SchedulerImpl.ru n(SchedulerImpl.java:250)
[10/09/03 15:22:33:301 GMT] 00000034 SystemErr R at java.lang.Thread.run(Thread.java:797)


Solution
The root cause is still unknown, but if I remove the ear file and add it again. This problem is gone.

2011/09/01

@Autowire is not working properly in my spring application

Problem
From my @Controller, i can easily access my autowired @Service class and play with it no problem. But when I do that from a separate class without annotations, it gives me a NullPointerException.


Solution
Spring dependency injection works only in components managed by Spring.


By default, classes annotated with @Component, @Repository, @Service, @Controller, or a custom annotation that itself is annotated with @Component are the only detected candidate components.


If your class is not managed by Spring (i.e. is not a Spring bean), @Autowired doesn't work inside it.

2011/08/31

Example of the Strategy Design Pattern

Summary


The Strategy Design Pattern consists of a number of related algorithms encapsulated in a driver class often named Context. A user or a client program typically selects the algorithm they want to use, although the Context class may also select the algorithm automatically.


The intent of the Strategy Pattern is to make the algorithms easily interchangeable, and provide a means to choose the appropriate algorithm at a particular time.


Here is a brief summary of the Strategy Design Pattern:

  • Algorithms (strategies) are chosen at runtime.
  • A Strategy is dynamically selected by a client (a user or consuming program), or by the Context.
  • Your driver/controller class is typically named Context, though there is no requirement for this.
  • The Context class is aware of a variety of different algorithms, and each algorithm is considered a Strategy, and the name Strategy is often used as part of each class name, although again, this is only convention, and not a requirement.
  • The Context class is responsible for handling the data during the interaction with the client.

Example of the Strategy Design Pattern


NIG687提供一個介面讓使用者分別去搜尋異動記錄檔,包括

  • NIGU001 - 違章案件管制異動檔
  • NIGU005 - 案件紀錄異動檔
  • NIGU008 - 審理人員狀況維護檔(二)
  • NIGU014 - 未分配異動檔
  • NIGU015 - 已分配異動檔
  • NIGU020 - 列印參數維護檔
  • NIGU021 - 裁處書預設內容異動檔
  • NIGU036 - 違章機關代碼維護檔
  • NIGU037 - 適用法條代碼異動檔
  • NIGU038 - 違章事實代碼異動檔
  • NIGU039 - 違章作業代號異動檔
  • NIGU040 - 免議(罰)、撤銷、更裁原因代碼異動檔
  • NIGU042 - 附案證據代碼異動檔
  • NIGU050 - 違章月統計異動檔
  • NIGU081 - 法務科科室稅目對照維護檔
  • NIGU086 - 記帳士法徵銷管制異動檔
此function會有16個strategies


Class Diagram


Strategy interface: The classes that implement a concrete strategy should implement this interface.


在strategy interface中,定義其共同會使用到的algorithm or strategy
1:  package gov.fdc.nig.query.service.nig687;  
2:  import gov.fdc.common.table.Paging;  
3:  import gov.fdc.nig.query.service.params.NIG687Params;  
4:  /**  
5:  * @author albert  
6:  *  
7:  */  
8:  public interface Strategy {  
9:       Paging doQuery(NIG687Params params, final int rowsPerPage, final String sortDir);  
10:  }  





Context class: Configured with a ConcreteStrategy object and maintains a reference to a Strategy object.


負責建立與strategy class之間的關係,呼叫其相對應的strategy class method,以及接收client傳送過來的參數
1:  package gov.fdc.nig.query.service.nig687;  
2:  import gov.fdc.common.table.Paging;  
3:  import gov.fdc.nig.query.service.params.NIG687Params;  
4:  /**  
5:  * @author albert  
6:  *   
7:  */  
8:  public class Context {  
9:       private Strategy strategy;  
10:       public void setNIGU001Strategy() {  
11:            this.strategy = new NIGU001Strategy();  
12:       }  
13:       public void setNIGU005Strategy() {  
14:            this.strategy = new NIGU005Strategy();  
15:       }  
16:       public void setNIGU008Strategy() {  
17:            this.strategy = new NIGU008Strategy();  
18:       }  
19:       public void setNIGU014Strategy() {  
20:            this.strategy = new NIGU014Strategy();  
21:       }  
22:       public void setNIGU015Strategy() {  
23:            this.strategy = new NIGU015Strategy();  
24:       }  
25:       public void setNIGU020Strategy() {  
26:            this.strategy = new NIGU020Strategy();  
27:       }  
28:       public void setNIGU021Strategy() {  
29:            this.strategy = new NIGU021Strategy();  
30:       }  
31:       public void setNIGU036Strategy() {  
32:            this.strategy = new NIGU036Strategy();  
33:       }  
34:       public void setNIGU037Strategy() {  
35:            this.strategy = new NIGU037Strategy();  
36:       }  
37:       public void setNIGU038Strategy() {  
38:            this.strategy = new NIGU038Strategy();  
39:       }  
40:       public void setNIGU039Strategy() {  
41:            this.strategy = new NIGU039Strategy();  
42:       }  
43:       public void setNIGU040Strategy() {  
44:            this.strategy = new NIGU040Strategy();  
45:       }  
46:       public void setNIGU042Strategy() {  
47:            this.strategy = new NIGU042Strategy();  
48:       }  
49:       public void setNIGU050Strategy() {  
50:            this.strategy = new NIGU050Strategy();  
51:       }  
52:       public void setNIGU081Strategy() {  
53:            this.strategy = new NIGU081Strategy();  
54:       }  
55:       public void setNIGU086Strategy() {  
56:            this.strategy = new NIGU086Strategy();  
57:       }  
58:       public Paging executeStrategy(NIG687Params params,final int rowsPerPage, final String sortDir) {  
59:            return strategy.doQuery(params, rowsPerPage, sortDir);  
60:       }  
61:  }  





Concrete Strategy class implementations shown below here.


定義Strategy class的細部運作細節


NIGU001 Strategy class
1:  package gov.fdc.nig.query.service.nig687;  
2:  import gov.fdc.common.dao.wherecon.SimpleCriteria;  
3:  import gov.fdc.common.table.Paging;  
4:  import gov.fdc.nig.dao.Nigu001Dao;  
5:  import gov.fdc.nig.domain.Nigu001;  
6:  import gov.fdc.nig.domain.Nigu001PK;  
7:  import gov.fdc.nig.query.service.params.NIG687Params;  
8:  import org.apache.commons.lang.StringUtils;  
9:  import org.springframework.beans.factory.annotation.Autowired;  
10:  /**  
11:  * @author albert  
12:  *  
13:  */  
14:  public class NIGU001Strategy implements Strategy {  
15:       @Autowired  
16:       private transient Nigu001Dao nigu001Dao;  
17:       /* (non-Javadoc)  
18:       * @see gov.fdc.nig.query.service.nig687.Strategy#doQuery(gov.fdc.nig.query.service.params.NIG687Params)  
19:       */  
20:       @Override  
21:       public Paging doQuery(NIG687Params params, final int rowsPerPage, final String sortDir) {  
22:            final SimpleCriteria whereCondition = new SimpleCriteria();  
23:            Nigu001PK primaryKey = (Nigu001PK)params.getPrimaryKey();  
24:            if(StringUtils.isNotEmpty(primaryKey.getDlvUnit()) &&  
25:               StringUtils.isNotEmpty(primaryKey.getTaxCd()) &&  
26:              StringUtils.isNotEmpty(primaryKey.getDlvYr()) &&  
27:              StringUtils.isNotEmpty(primaryKey.getFlgTp()) &&  
28:              StringUtils.isNotEmpty(primaryKey.getSerialNo())){  
29:                 whereCondition.eq("id.dlvUnit", primaryKey.getDlvUnit());  
30:                 whereCondition.eq("id.taxCd", primaryKey.getTaxCd());  
31:                 whereCondition.eq("id.dlvYr", primaryKey.getDlvYr());  
32:                 whereCondition.eq("id.flgTp", primaryKey.getFlgTp());  
33:                 whereCondition.eq("id.serialNo", primaryKey.getSerialNo());  
34:            }  
35:            // 取得排序方向, 如果有的話代表是要排序  
36:            if (sortDir != null){  
37:                 whereCondition.orderBy("id", sortDir.equals("asc"));  
38:            }else{  
39:                 whereCondition.orderBy("id", true); // 預設照seqNo由小到大排  
40:            }  
41:            // 執行查詢  
42:            return new Paging(new Nigu001(), null, whereCondition, rowsPerPage, 100, nigu001Dao);  
43:       }  
44:  }  





NIGU005 Strategy Class
1:  package gov.fdc.nig.query.service.nig687;  
2:  import gov.fdc.common.dao.wherecon.SimpleCriteria;  
3:  import gov.fdc.common.table.Paging;  
4:  import gov.fdc.nig.dao.Nigu005Dao;  
5:  import gov.fdc.nig.domain.Nigu005;  
6:  import gov.fdc.nig.domain.Nigu005PK;  
7:  import gov.fdc.nig.query.service.params.NIG687Params;  
8:  import org.apache.commons.lang.StringUtils;  
9:  import org.springframework.beans.factory.annotation.Autowired;  
10:  /**  
11:  * @author albert  
12:  *   
13:  */  
14:  public class NIGU005Strategy implements Strategy {  
15:       @Autowired  
16:       private transient Nigu005Dao nigu005Dao;  
17:       /*  
18:       * (non-Javadoc)  
19:       *   
20:       * @see  
21:       * gov.fdc.nig.query.service.nig687.Strategy#doQuery(gov.fdc.nig.query.service  
22:       * .params.NIG687Params, int, java.lang.String)  
23:       */  
24:       @Override  
25:       public Paging doQuery(NIG687Params params, int rowsPerPage, String sortDir) {  
26:            final SimpleCriteria whereCondition = new SimpleCriteria();  
27:            Nigu005PK primaryKey = (Nigu005PK) params.getPrimaryKey();  
28:            if (StringUtils.isNotEmpty(primaryKey.getDlvUnit())     &&   
29:              StringUtils.isNotEmpty(primaryKey.getTaxCd()) &&   
30:                 StringUtils.isNotEmpty(primaryKey.getDlvYr()) &&   
31:                 StringUtils.isNotEmpty(primaryKey.getFlgTp()) &&   
32:                 StringUtils.isNotEmpty(primaryKey.getSerialNo())) {  
33:                   whereCondition.eq("id.dlvUnit", primaryKey.getDlvUnit());  
34:                  whereCondition.eq("id.taxCd", primaryKey.getTaxCd());  
35:                  whereCondition.eq("id.dlvYr", primaryKey.getDlvYr());  
36:                  whereCondition.eq("id.flgTp", primaryKey.getFlgTp());  
37:                  whereCondition.eq("id.serialNo", primaryKey.getSerialNo());  
38:            }  
39:            // 取得排序方向, 如果有的話代表是要排序  
40:            if (sortDir != null) {  
41:                 whereCondition.orderBy("id", sortDir.equals("asc"));  
42:            } else {  
43:                 whereCondition.orderBy("id", true); // 預設照seqNo由小到大排  
44:            }  
45:            // 執行查詢  
46:            return new Paging(new Nigu005(), null, whereCondition, rowsPerPage, 100, nigu005Dao);  
47:       }  
48:  }  





this is our "driver" method to demonstrate our Java Strategy Design Pattern example
1:  public static void main(String[] args){  
2:       Context context;  
3:       //搜尋NIGU001 table的資料  
4:       context = new Context();  
5:       context.setNIGU001Strategy();  
6:       context.executeStrategy(params, rowsPerPage, sortDir);  
7:       //搜尋NIGU005 table的資料  
8:       context = new Context();  
9:       context.setNIGU005Strategy();  
10:      context.executeStrategy(params, rowsPerPage, sortDir);  
11:  }  


2011/08/24

illegal character: \65279 when using file encoding UTF8

Problem
As I try to compile classes in my workspace, it show this error message "illegal character: \65279 when using file encoding UTF8".

Root Cause
Some Java class has BOM(Byte-Order Mark) character, so you need to remove it.

Solution
Use notepad++ to remove it.



JasperWave - designer for JasperReports




Another report designer tool choice for JasperReports: http://jasperwave.com/docs/introduction.html

Ease Your Effort of Putting Data into History Table


2011/08/23

had objects of type "gov.fdc.nig.domain.Nigt038PK" but expected signature "gov.fdc.nig.domain.Nigu038PK"

Problem
As I utilize Appche commons PropertyUtils.copyProperties API, it show this error message in runtime

Cannot invoke gov.fdc.nig.domain.Nigu038.setId on bean class 'class gov.fdc.nig.domain.Nigu038' - had objects of type "gov.fdc.nig.domain.Nigt038PK" but expected signature "gov.fdc.nig.domain.Nigu038PK"


Root Cause
Here is Nigt038's attributes
1:  @Entity   
2:  @EntityListeners({EntityListener.class})   
3:  @Table(name = "NIGT038")   
4:  public class Nigt038 extends DomainBase {   
5:       // Fields   
6:       private Nigt038PK id;   
7:       private String vioFactNm;   
8:       private Timestamp timeStamp;   
9:       private String updateCd;   
10:       private String userId;   
11:       private String updateDate;   
12:       //..........   



Here is Nigu038's attributes
1:  @Entity   
2:  @EntityListeners({EntityListener.class})   
3:  @Table(name = "NIGU038")   
4:  public class Nigu038 extends DomainBase {   
5:       // Fields   
6:       private Nigu038PK id;   
7:       private String vioFactNm;   
8:       private Timestamp timeStamp;   
9:       private String userId;   
10:       private String updateDate;   
11:       //........   

The two class the same attrbute name, but have different type. It's the reason why it fails to do object copy.
And in our case, we don't need to copy id attributes.

Solution
We need to igore the "id" attribute, so we use this way to do property copy.


1:    /**  
2:     * Copy properties.  
3:     *  
4:     * @param dest  
5:     *      the dest  
6:     * @param source  
7:     *      the source  
8:     */  
9:    public void copyProperties(Object dest, Object source) {  
10:      try {  
11:        PropertyDescriptor[] destDesc = PropertyUtils.getPropertyDescriptors(dest);  
12:        for (int i = 0; i < destDesc.length; i++) {  
13:          Class<?> destType = destDesc[i].getPropertyType();  
14:          Class<?> origType = PropertyUtils.getPropertyType(source, destDesc[i].getName());  
15:          if ((destType != null && destType.equals(origType) && !destType.equals(Class.class) && !"id"  
16:            .equals(destDesc[i].getName()))) {  
17:            Object value = PropertyUtils.getProperty(source, destDesc[i].getName());  
18:            PropertyUtils.setProperty(dest, destDesc[i].getName(), value);  
19:          }  
20:        }  
21:      } catch (IllegalAccessException e) {  
22:        e.printStackTrace();  
23:      } catch (InvocationTargetException e) {  
24:        e.printStackTrace();  
25:      } catch (NoSuchMethodException e) {  
26:        e.printStackTrace();  
27:      }  
28:    }  

2011/08/18

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.fdc.nig.controlop.NIG225Manager] found for dependency

Problem
As I execute my function, it show this error message
 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.fdc.nig.controlop.NIG225Manager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}   
 at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)   
 at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)   
 at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)   
 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)   
 ... 42 more   


Controller class is as bellowing
 /**   
 *   
 */   
 package gov.fdc.nig.web.controlop.controller;   
 /**   
 * @author albert   
 *   
 */   
 @Controller   
 @RequestMapping("/front/NIG225W")   
 public class NIG225Controller extends AbstractController {   
      @Autowired   
      private transient NIG225Manager nig225Manager;   
 }  

Root Cause
I forgot to add @Service to my service implementation


Solution
 @Service   
 public class NIG225ManagerImpl implements NIG225Manager {   
 }