Amazon Ads

顯示具有 EJB 標籤的文章。 顯示所有文章
顯示具有 EJB 標籤的文章。 顯示所有文章

2014年1月24日 星期五

【筆記】EJB使用Deployment Description來實現Interceptor

在Session Bean或Message Driven Bean的某些方法被呼叫時,可以使用Interceptor在呼叫前後,做一些其他的處理,他像是EJB的AOP (Aspect Oriented Programming) 。

Interceptor可以使用Annotation或使用Deployment Descriptor來宣告,下面的範例包含了一個Singleton Session Bean、一個要做為Interceptor的類別、一個宣告Interceptor的Deployment Descriptor文件,另外還有一個做為客戶端程式的Servlet,我使用GlassFish 3.1來做為我的伺服器,並使用Deployment Descriptor來宣告Interceptor。

SingletonSessionBean.java
package jk.idv.ssb;

import java.util.Date;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;

@Singleton(name="SingletonSessionBean")
@LocalBean
public class SingletonSessionBean
{
 private final static String MY_NAME = "SingletonSessionBean";
 
 private String username = "[no man]";
 
 @PostConstruct
 private void init()
 {
  System.out.println("    " + MY_NAME + " - Initialized");
 }
 
 @PreDestroy
 private void destroy()
 {
  System.out.println("*** " + MY_NAME + " - Destroyed");
 }
 
 public String retrieveMessage()
 {
  Date theCurrentTime = new Date();
  return "Name saved in " + MY_NAME + " is " + username + " "
  + theCurrentTime;
 }
 
 public void saveName(final String inName)
 {
  this.username = inName;
 }
}


上列程式碼中,未使用@Interceptors來宣告這個Singleton Session Bean相關的Interceptor。

LogInterceptor.java
package idv.jk.interceptor;

package idv.jk.interceptor;

import javax.interceptor.InvocationContext;

public class LogInterceptor
{
 public Object logMethod(InvocationContext inCtx) throws Exception
 {
  System.out.println(" LogInterceptor intercepting: " +
    inCtx.getTarget().getClass().getSimpleName() +
    "." + inCtx.getMethod().getName());
  return inCtx.proceed();
 }
}


上列的程式碼中,也沒有使用@Interceptor來宣告此類別為一個Interceptor。
SingletonClientServlet.java
package idv.jk.client;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jk.idv.ssb.SingletonSessionBean;

/**
 * Servlet implementation class SingletonClientServlet
 */
@WebServlet("/SingletonClientServlet")
public class SingletonClientServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
 @EJB
 private SingletonSessionBean singletonSessionBean;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SingletonClientServlet() {
        super();
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String theParam = request.getParameter("name");
  
  PrintWriter pw = response.getWriter();
  
  String msg = singletonSessionBean.retrieveMessage();
  pw.println("Get message from singleton session bean: ");
  pw.println(msg);
  
  if(theParam != null)
  {
   singletonSessionBean.saveName(theParam);
  }
  msg = singletonSessionBean.retrieveMessage();
  pw.println("Check message from singleton session bean: ");
  pw.println(msg);
  pw.println("Finished invoking singleton session beans!");
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 }

}

上列的Servlet使用注入的方式來使用Singleton Session Bean的方法,並在瀏覽器中印出一些我需要的資訊。

最後是名為ejb-jar.xml的Deployment Descriptor:

 
 
  
   idv.jk.interceptor.LogInterceptor
   
    logMethod
   
  
 
 
  
   SingletonSessionBean
   idv.jk.interceptor.LogInterceptor
  
 


將Web應用程式部署到GlassFish後,再打開瀏覽器輸入:http://localhost:8888/BusinessMethodInterceptorsDD/SingletonClientServlet?name=Javakid,應該可以看到下列的結果:

Get message from singleton session bean: 
Name saved in SingletonSessionBean is [no man] Fri Jan 24 00:05:32 CST 2014
Check message from singleton session bean: 
Name saved in SingletonSessionBean is Javakid Fri Jan 24 00:05:32 CST 2014
Finished invoking singleton session beans!

在Console中,也會看到一些訊息被印出來:


完整的程式由此下載

參考資料:

http://www.slideshare.net/krizsan/ocp-jbcd-6-study-notes,p.97

2013年11月1日 星期五

【筆記】Timer Life-Cycle


【筆記】Timer Life-Cycle



【筆記】GlassFish對應安全角色群組 (Mapping Security Roles in GlassFish)

在v3.1之前,在GlassFish中,做安全角色群組對應 (Mapping Security Roles in GlassFish) 的設定檔好像是寫在Web專案下「WEB-INF」下的「sun-web.xml」中,但到了v3.1之後,安全角色的對應是設定在「WEB-INF」下的「glassfish-web.xml」中,如:


 /EJBSecurityAnnotations
    
 
  superusers
  javakid
 
 
 
  plainusers
  plain-users
 
 
  runasadmin
  runas-superusers
 

參考來源:http://www.slideshare.net/krizsan/ocp-jbcd-6-study-notes,p.187

2013年10月29日 星期二

【筆記】The relationships between roles, users groups, security realms, principal and credentials



上圖中表示只有一個Security Realm (形式為LDAP realm) 存在於該應用程式伺服器中,Security Realm是指身份 (identity) 的儲存技術,如JDBC、LDAP或檔案系統,並且定義和認證儲存間的互動方式,用以儲存及存取使用者的認證 (authetication) 和群組資訊。

該LDAP realm中包含兩個群組:Regular Users Group (包含兩個使用者)以及Important Users Group (只有一個使用者),而其中金髮帶眼鏡的帥哥,不屬於任何群組。

每一個使用者都有某些credential和它聯結在一起 (如圖中使用者和鎖)。

在應用程式A中,定義了Acountant以及Plainuser兩個角色 (role),Acountant對應到帶眼鏡金髮帥哥這個Principal (如使用者和密碼的關聯),而角色Plainuser對應到群組Regular Users Group。

在應用程式B中,定義了Users以及Administrator兩個角色,其中角色Users對應到帶紅帽的美女,而Administrator對應到Important User Group這個群組。


2013年10月24日 星期四

【筆記】Life-cycle of a singleton session bean

Singleton session bean的生命週期和Stateless session bean的生命週期差不多,除了一個重要的差別,那就是當在business method或callback method被呼叫時,而有system exception發生,Singleton session bean的物件不會被消滅。



  1. 在上圖中,紅色表示Singleton Session Bean的不同狀態。
  2. 綠色方塊表示造成Singleton Session Bean狀態改變的用戶端行為。

節錄自:http://www.slideshare.net/krizsan/ocp-jbcd-6-study-notes,p.69

2013年10月23日 星期三

【筆記】Life-cycle of a stateless session bean



  1. 在上圖中,紅色表示Stateless Session Bean的不同狀態。
  2. 綠色方塊表示造成Stateless Session Bean狀態改變的用戶端行為。
節錄自:http://www.slideshare.net/krizsan/ocp-jbcd-6-study-notes,p.46

2013年10月14日 星期一

[筆記]TansacetionAttribute值可用情境

TransactioAttribute是用來定義一個transaction的屬性,根據使用的方法不一樣,對應的可用屬性就不同。

方法
TransactionAttribute可以使用的值
message-driven bean's message listener methods
REQUIRED
NOT_SUPPORTED

EJB's timeout callback methodsREQUIRED
REQUIRED_NEW
NOT_SUPPORTED

EJB's asynchronous business methodsREQUIRED

singleton session bean's PostConstruct/PreDestroy lifecycle callbak interceptor methodsREQUIRED
REQUIRED_NEW
NOT_SUPPORTED

If a EJB implements the javax.ejb.SessionSynchronization interfaces or uses at least one of the session synchronization annotationsREQUIRED
REQUIRED_NEW
MADATORY


對於一個類別的方法所設定的transaction屬性,可以對於類別或該類別中處理商業邏輯的方法,或者兩者一起的方式來定義。

摘錄自EJB3.1 spec,p.359-360

2013年10月1日 星期二

[筆記]在Stateless Session Bean的方法中允許的操作

Bean方法
允許的操作
建構子
Dependency injection methods (setter methods).SessionContext:
getEJBHome,
getEJBLocalHome,
lookup.

JNDI Access: Available
PostConstruct, PreDestroy methods (lifecycle
callback methods).
SessionContext:
getBusinessObject,
getEJBHome,
getEJBLocalHome,
getEJBObject,
getEJBLocalObject,
lookup,
getContextData,
getTimerService,
getUserTransaction (BMT only)

JNDI Access: Available
EntityManagerFactory: Accessible
Business method from any view or business method interceptor methodSessionContext:
getBusinessObject,
getEJBHome,
getEJBLocalHome,
getCallerPrincipal,
isCallerInRole,
getEJBObject,
getEJBLocalObject,
lookup,
getContextData,
getInvokedBusinessInterface,
wasCancelCalled,
getTimerService,
getUserTransaction (BMT only)
getRollbackOnly (CMT only)
setRollbackOnly (CMT only)
JNDI Access: Available
Resource managers: Accessible
Other EJBs: Accessible
EntityManagerFactory: Accessible
EntityManager: Accessible
Timer and TimeService methods: Accessbile
UserTransaction methods: Accessible (BMT only)
Business methods from web service endpoint.SessionContext:
getBusinessObject,
getEJBHome,
getEJBLocalHome,
getCallerPrincipal,
isCallerInRole,
getEJBObject,
getEJBLocalObject,
lookup,
getContextData,
getTimerService,
getMessageContext,
getUserTransaction (BMT only),
getRollbackOnly (CMT only),
setRollbackOnly (CMT only).
MessageContext methods: Available
JNDI Access: Available
Resource managers: Accessible.
Other EJBs: Accessible.
EntityManagerFactory: Accessible.
EntityManager: Accessible.
Timer and TimerService methods: Accessible.
UserTransaction methods: Accessible (BMT only).
Timeout callback method.SessionContext:
getBusinessObject,
getEJBHome,
getEJBLocalHome,
getCallerPrincipal,
isCallerInRole,
getEJBObject,
getEJBLocalObject,
lookup,
getContextData,
getTimerService,
getUserTransaction (BMT only),
getRollbackOnly (CMT only),
setRollbackOnly (CMT only).
JNDI Access: Available
Resource managers: Accessible.
Other EJBs: Accessible.
EntityManagerFactory: Accessible.
EntityManager: Accessible.
Timer and TimerService methods: Accessible.
UserTransaction methods: Accessible (BMT only).

ps.

  1. BMT表Bean Managed Transaction
  2. CMT表Container Managed Transaction

若在@PostConstruct和@PreDestroy中進行下列操作,則IllegalStateException會被丟出
呼叫對象
方法名稱
SesssionContext methodsSecurity related:
getCallerPrincipal,
isCallerInRole.
Transaction related:
getRollbackOnly,
setRollbackOnly
Asynchronous related methodswasCancelCalled
Client related SessionConext methodsgetInvokedBusinessInterface
TimerService and TimerAll methods

節錄自:http://www.slideshare.net/krizsan/ocp-jbcd-6-study-notes,p.47

2013年9月27日 星期五

[筆記]oceejbd6隨手筆記-Chapter 4

每個session bean的global JNDI name的語法如下:
java:global[/<app-name>]/<module-name$gt;/<bean-name$gt;[!<fully-qualified-interface-name$gt;]

其中
<app-name>只有在session bean是包在一個.ear的檔案才需要的,預設是.ear檔的名稱,可以透過application.xml來修改
<module-name>指的是session bean所在的模組 (module) 名稱,如ejb-jar檔或一個.war

2013年9月13日 星期五

[筆記]Session Bean Life-cycle Annotations

Annotation可以用來在Session Bean的生命周期 (life-cycle) 中,定義那些方法會因應相關事件而被呼叫,相關的Annotations如下表:
Annotaion
Comments
@PostConstruct
  1. 在EJB實體被建立之後,而開始被使用之前
  2. 可以用來做一些初始化的工作
  3. EJB 3.1 spec建議使用此來做初始化,而不是用建構方法
@PreDestroy
  1. 在EJB實體被容器停止服務之前被呼叫
  2. 可以用來清除或釋放一些被EJB實體使用的資源
  3. 當EJB實例丟出系統錯誤 (system exception) 時、容器毀損,或當Stateful session bean狀態為非活化 (passivated) 中而發生過時 (timeout)時,有此annotation的方法將不會被呼叫
@PrePassivate
  1. 當Stateful session bean狀態將轉為非活化 (passivated) 之前被呼叫
  2. 可以讓活化時的EJB實例所使用的資源得以釋放,並對一些非序列化的參照物件做序列化 (serialization)的處理
@PostActivate

    1. 當Stateful session bean狀態將轉為活化 (passivated) 之前被呼叫
    2. 用以獲得一些需要使用到的資源
    3. 對所參照的物件做反序列化的設定

    ps. 翻得不好,請有需要的朋友還是參考原文或EJB spec。

    節錄自:http://www.slideshare.net/krizsan/ocp-jbcd-6-study-notes,p.253

    2013年9月4日 星期三

    [筆記]GlassFish v3的部署設定檔:sun-web.xml

    有時要找一個設定檔,從空的XML開始,實在是有點為難自己,下列sun-web.xml是GlassFish v3特有的部署描述檔 (deployment descriptor),在此做下筆記,以後比較好找。


    
    
    
     /EJBSecurityAnnotations
     
     
      superusers
      ivan
     
     
     
      plainusers
      plain-users
     
     
      runasadmin
      runas-superuser
     
     
    
    
    
    節錄自:http://www.slideshare.net/krizsan/ocp-jbcd-6-study-notes,p.187

    2013年8月28日 星期三

    [筆記]Message Listenner Method Exception的處理

    下圖說明Message Listener Methods如何處理exception,圖一敘述「Exception Type」為「System」的部份,圖二敘述「Exception Type」為「Application」的部份。
    圖一


    圖二

    節錄自:http://www.slideshare.net/krizsan/ocp-jbcd-6-study-notes,p.150

    2013年8月24日 星期六

    [筆記]在GlassFish中建立JMS Physical Destination

    為了可以讓一個在Glassfish伺服器上應用程式內執行的message-driven EJB接收訊息,必須對伺服器上的JMS設定做一些調整,第一步就是建立一個JMS Physical Destination。

    打開【命令提示字元】切換到Glassfish安裝目錄下的「bin」目錄中,執行「create-jmsdest --desttype queue PSQueueDest」,其中,「--desttype queue」是指要建立的類型為「javax.jms.Queue」,若要建立類型為「javax.jms.Topic」,可以使用指令如:「create-jmsdest --desttype topic MyTopicPhysicalDestination

    執行成功後,執行「list-jmsdest」,應可看到剛建立的Physical Destination,如下圖:

    2013/08/27發現在GlassFish的Admin Console找到相關設定的地方,如下圖:

    請注意版本差別,之前版本好像是在左側選單中【Configuration】下。

    參考文件:http://docs.oracle.com/cd/E18930_01/html/821-2416/ablkj.html

    2013年8月23日 星期五

    [筆記]Business Method Interceptor的一些特性

    下表列出Business Method Interceptor的一些特性:
    QuestionAnswer
    May be defined on which EJB type(s)Session bean and message driven beans.
    Intercept which method types.Session bean business methods and message driven bean's message listener methods.
    Location of interceptor methods.In special interceptor class, interceptor superclass, or in the target class.
    Restrinctions on interceptor methods.At most one per class.
    Annotation(s) use to define interceptor method(s)@AroundLinvoke

    在「javax.interceptor」套件中
    Interceptor method security context.Same security context as intercepted business method.
    Interceptor method transaction context.Same transaction context as intercepted business method.
    Exceptions interceptor methods may throw.Exceptions declared in the throws-clause of the intercepted business method and system exceptions.
    Interceptor method signature.Object someMethodName(InvocationContext) throws Exception

    其中,「someMethodName」為開發者自取的方法名稱;
    「InvocationContext」類別在,「javax.interceptor」套件中。
    Interceptor method visibilityPublic, protected, private or package visibility

    節錄自:http://www.slideshare.net/krizsan/ocp-jbcd-6-study-notes,p.109

    2013年8月21日 星期三

    [筆記]EJB - Common system exception

    ExceptionTransaction StatusNotes
    The following exceptions are the basic exceptions
    EJBExceptionMay or may not have been marked for rollback.Not possible to determine whether EJB method has executed or not.
    Error may have occurred during communication with, or processing in, the EJB.
    RemoteExceptionMay or may not have been marked for rollback.See EJBException.
    The following exceptions indicate that the transaction has been marked for rollback and will never commit.
    EJBTransactionRolledback-ExceptionRolled back or marked for rollbackSubclass of EJBException.
    EJB invoked using EJB 3.1 view and EJB executing in client's transaction.
    TransactionRolledbackLocal-ExceptionRolled back or marked for rollbackSubclass of EJBException.
    EJB invoked using EJB 2.1 local client view.
    TransactionRolledback-ExceptionRolled back or marked for rollbackSubclass of RemoteException. JTA standard exception. EJB invoked using EJB 2.1 remote view or web service view.
    The following exceptions indicate that an attempt was made to invoke a method that require a client transaction without the client having a transaction context.
    These exceptions usually indicate an error in method transaction requirement declaration(s).
    EJBTransactionRequired-ExceptionNo transactionSubclass of EJBException.
    EJB invoked using EJB 3.1 view.
    TransactionRequiredLocal-ExceptionNo transactionSubclass of EJBException.
    EJB invoked using EJB 2.1 local client view.
    TransactionRequiredExceptionNo transactionSubclass of RemoteException. JTA standard exception.
    EJB invoked using EJB 2.1 remote view or web service view.
    The following exceptions indicate that an attempt was made to invoke a method on an EJB object that does not exist.
    NoSuchEJBExceptionRolled back or marked for rollback.Subclass of EJBException.
    EJB invoked using EJB 3.1 view.
    NoSuchObjectLocal-ExceptionRolled back or marked for rollback.Subclass of EJBException.
    EJB invoked using EJB 2.1 local client view.
    NoSuchObjectExceptionRolled back or marked for rollback.Subclass of RemoteException.
    EJB invoked using EJB 2.1 remote client view.


    摘錄自:http://www.slideshare.net/krizsan/ocp-jbcd-6-study-notes,96頁。

    2013年8月16日 星期五

    [筆記]EJB 3.1 Lite和Full EJB 3.1 API的比較

    EJB Lite是Full EJB 3.1 API的一個子集,讓開發者可以去實現較小、較不複雜的EJB容器,並且能(部份)符合EJB 3.1的規範。
    特徵
    Full EJB 3.1 APIEJB 3.1 Lite API
    Java Persistence 2.0可用可用
    Session beans local/no interface client view可用可用
    Session beans 3.0 remote client
    view
    可用不可用
    Session beans 2.x remote client
    view
    可用不可用
    Session beans exposed as JAXWS web service endpoints可用不可用
    Session beans exposed as JAXRPC web service endpoints可用不可用
    EJB timer service可用不可用
    Asynchronous invocation of
    session beans
    可用不可用
    Interceptors可用可用
    RMI-IIOP interoperability可用不可用
    Bean and container managed
    transactions
    可用可用
    Declarative and programmatic
    security
    可用可用
    Embeddable API可用,但embeddable
    container只需支援EJB 3.1 Lite
    可用
    Message driven beans可用不可用

    節錄自:http://www.slideshare.net/krizsan/ocp-jbcd-6-study-notes

    2013年8月14日 星期三

    [筆記]EJB程式設計的限制

    為了遵守EJB3.1的標準,確認在不同的容器(container)的可攜性(portability),有些程式設計原則是開發者需要遵守的:

    1. 為了確保在分散式環境中的一致性,EJB不會使用可寫的靜態變數(writable static fields)。
    2. 在一個應用程式中,Server通常不允許去使用鍵盤或螢幕,所以EJB不可使用AWT相關功能去產生「輸出(output)」,或從鍵盤去取得「輸入(input)」。
    3. 為了確保安全性,EJB不可嘗試直接去讀、寫一個file description。
    4. 為了確保安全性,EJB不可嘗試去載入一個native library。
    5. 為了確保安全性,EJB不可去定義套件中的類別。
    參考來源:

    2013年8月8日 星期四

    [分享] Oracle Certified Expert, Java Platform, Enterprise Edition 6 Enterprise JavaBeans Developer (OCEEJBD6,1Z0-895)的EJB認證準備

    拜歐實在不知道這個認證的縮寫,應該是OCEEJBD吧!它的考試代號為:1Z0-895,要考這項的話,考試券其實就跟考之前SCJP、SCWCD的一樣。

    在Oracle的官網,有相關的說明

    一樣在Coderanch的認證討論區中,有介紹的專區

    另外就是有賣相關教材(模擬考題)的EPractize Labs,還有,國外論壇考過的人都比較建議這一套Enthuware

    考試準備參考資料:

    1. EJB 3.1 Specification document,可以從這裡下載。(天啊!六百多頁)
    2. OReilly出版的Enterprise JavaBeans 3.1
    3. Frits WalravenIvan Krizsan提供的筆記(這兩位真是佛心來的) 
    4. Coding練習
    以下是一些考過的人經驗分享:


    參考來源:
    http://www.coderanch.com/t/614320/sr/certification/Passed-OCE-EJBD