EJB: Exemplos de Session Beans

Exemplo de um Session Bean sem Estado

O Problema

A Solução: Criação do Bean

import javax.ejb.EJBObject;
import java.rmi.RemoteException;
import java.math.*;

public interface Converter extends EJBObject {
 
  public BigDecimal dollarToYen(BigDecimal dollars) throws RemoteException;
  public BigDecimal yenToEuro(BigDecimal yen) throws RemoteException;
}
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface ConverterHome extends EJBHome {

  Converter create() throws RemoteException, CreateException;
}
import java.rmi.RemoteException; 
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import java.math.*;

public class ConverterBean implements SessionBean {
  BigDecimal yenRate = new BigDecimal("121.6000");
  BigDecimal euroRate = new BigDecimal("0.0077"); 

  public BigDecimal dollarToYen(BigDecimal dollars) {
    BigDecimal result = dollars.multiply(yenRate);
    return result.setScale(2,BigDecimal.ROUND_UP);
  }

  public BigDecimal yenToEuro(BigDecimal yen) {
    BigDecimal result = yen.multiply(euroRate);
    return result.setScale(2,BigDecimal.ROUND_UP);
  }

  public ConverterBean() {}
  public void ejbCreate() {}
  public void ejbRemove() {}
  public void ejbActivate() {}
  public void ejbPassivate() {}
  public void setSessionContext(SessionContext sc) {}
} // ConverterBean

Ciclo-Session-Beans-Stateless.gif (11015 bytes)

A Solução: Compilação do Bean

C:\...\src>ant converter
Buildfile: build.xml

init:

converter:
    [mkdir] Created dir: C:\Documents and Settings\JACQUES\Meus documentos\Cursos\Hp\j2ee\html\build\converter
    [javac] Compiling 4 source files to C:\Documents and Settings\JACQUES\Meus documentos\Cursos\Hp\j2ee\html\build\conv
erter
     [copy] Copying 1 file to C:\Documents and Settings\JACQUES\Meus documentos\Cursos\Hp\j2ee\html\build\converter

BUILD SUCCESSFUL

Total time: 5 seconds

A Solução: Packaging do Bean

A Solução: Criação do Cliente

<%@ page import="Converter,ConverterHome,javax.ejb.*, javax.naming.*,
                 javax.rmi.PortableRemoteObject, java.rmi.RemoteException,
                 java.math.*" %>
<%!
  private Converter converter = null;
   public void jspInit() { 
      try {
         InitialContext ic = new InitialContext();
         Object objRef = ic.lookup("java:comp/env/ejb/TheConverter");
         ConverterHome home = (ConverterHome)PortableRemoteObject.narrow(objRef,
                                                           ConverterHome.class);
         converter = home.create();
      } catch (RemoteException ex) {
            System.out.println("Couldn't create converter bean."+ ex.getMessage());
      } catch (CreateException ex) {
            System.out.println("Couldn't create converter bean."+ ex.getMessage());
      } catch (NamingException ex) {
            System.out.println("Unable to lookup home: "+ "TheConverter "+ ex.getMessage());
      } 
   }

   public void jspDestroy() {    
         converter = null;
   }
%>
<html>
<head>
    <title>Converter</title>
</head>
<body bgcolor="white">
<h1><b><center>Converter</center></b></h1>
<hr>
<p>Enter an amount to convert:</p>
<form method="get">
<input type="text" name="amount" size="25">
<br>
<p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
<%
    String amount = request.getParameter("amount");
    if ( amount != null && amount.length() > 0 ) {
      BigDecimal d = new BigDecimal (amount);
%>
<p><%= amount %> dollars are <%= converter.dollarToYen(d) %> Yen.
<p><%= amount %> Yen are <%= converter.yenToEuro(d) %> Euro.
<%
    }
%>
</body>
</html> 

A Solução: Compilação do Cliente

A Solução: Packaging do Cliente

A solução: O Deployment Descriptor

O DD da aplicação

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE application PUBLIC '-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN' 'http://java.sun.com/dtd/application_1_3.dtd'>

<application>
  <display-name>ConverterApp</display-name>
  <description>Application description</description>
  <module>
    <web>
      <web-uri>war-ic.war</web-uri>
      <context-root>converter</context-root>
    </web>
  </module>
  <module>
    <ejb>ejb-jar-ic.jar</ejb>
  </module>
</application>
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE j2ee-ri-specific-information PUBLIC '-//Sun Microsystems Inc.//DTD J2EE Reference Implementation 1.3//EN' 'http://localhost:8000/sun-j2ee-ri_1_3.dtd'>

<j2ee-ri-specific-information>
  <server-name></server-name>
  <rolemapping />
  <web>
    <module-name>war-ic.war</module-name>
    <context-root>converter</context-root>
    <ejb-ref>
      <ejb-ref-name>ejb/TheConverter</ejb-ref-name>
      <jndi-name>MyConverter</jndi-name>
    </ejb-ref>
  </web>
  <enterprise-beans>
    <module-name>ejb-jar-ic.jar</module-name>
    <unique-id>0</unique-id>
    <ejb>
      <ejb-name>ConverterEJB</ejb-name>
      <jndi-name>MyConverter</jndi-name>
...
    </ejb>
  </enterprise-beans>
</j2ee-ri-specific-information>

O DD do bean EJB

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
  <display-name>ConverterJAR</display-name>
  <enterprise-beans>
    <session>
      <display-name>ConverterEJB</display-name>
      <ejb-name>ConverterEJB</ejb-name>
      <home>ConverterHome</home>
      <remote>Converter</remote>
      <ejb-class>ConverterBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Bean</transaction-type>
      <security-identity>
        <description></description>
        <use-caller-identity></use-caller-identity>
      </security-identity>
    </session>
  </enterprise-beans>
</ejb-jar>

A Solução: Deployment da Aplicação

Objeto-Distribuído.gif (8565 bytes)

A Solução: Execução da Aplicação

wpe1.jpg (31840 bytes)

wpe3.jpg (34650 bytes)

Exemplo de um Session Bean com Estado

A Remote Interface

import java.util.*;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;

public interface Cart extends EJBObject {
 
  public void addBook(String title) throws RemoteException;
  public void removeBook(String title) throws BookException,
                                              RemoteException;
  public Vector getContents() throws RemoteException;
}

A Home Interface

import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface CartHome extends EJBHome {
 
  Cart create(String person) throws RemoteException, CreateException;
  Cart create(String person, String id) throws RemoteException, 
                                               CreateException; 
}

Classe de Implementação

import java.util.*;
import javax.ejb.*;

public class CartBean implements SessionBean {

  String customerName;
  String customerId;
  Vector contents;

  public void ejbCreate(String person) throws CreateException {
    if (person == null) {
      throw new CreateException("Null person not allowed.");
    } else {
      customerName = person;
    }
    customerId = "0";
    contents = new Vector();
  }

  public void ejbCreate(String person, String id) throws CreateException {
    ejbCreate(person);
    IdVerifier idChecker = new IdVerifier();
    if (idChecker.validate(id)) {
      customerId = id;
    } else {
      throw new CreateException("Invalid id: " + id);
    }
  }

  public void addBook(String title) {
    contents.add(title);
  }

  public void removeBook(String title) throws BookException {
    boolean result = contents.remove(title);
    if (result == false) {
      throw new BookException(title + " not in cart.");
    }
  }

  public Vector getContents() {
    return contents;
  }

  public CartBean() {}
  public void ejbRemove() {}
  public void ejbActivate() {}
  public void ejbPassivate() {}
  public void setSessionContext(SessionContext sc) {}
}
public class BookException extends Exception {

  public BookException() {
  }

  public BookException(String msg) {
    super(msg);
  }
}

public class IdVerifier {

  public IdVerifier() {
  }

  public boolean validate(String id) {

    boolean result = true;
    for (int i = 0; i < id.length(); i++) {
      if (Character.isDigit(id.charAt(i)) == false)
        result = false;
    }
    return result;
  }
}

A interface SessionBean

Ciclo-Session-Beans-Stateful.gif (15427 bytes)

Os Business Methods

  Cart shoppingCart = home.create(“Duke DeEarl”, “123”);
  . . .
  shoppingCart.addBook(“The Martian Chronicles”);
  shoppingCart.removeBook(“Alice In Wonderland”);
  bookList = shoppingCart.getContents();
  . . .
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
  <display-name>CartJAR</display-name>
  <enterprise-beans>
    <session>
      <display-name>CartEJB</display-name>
      <ejb-name>CartEJB</ejb-name>
      <home>CartHome</home>
      <remote>Cart</remote>
      <ejb-class>CartBean</ejb-class>
      <session-type>Stateful</session-type>
      <transaction-type>Container</transaction-type>
      <security-identity>
        <description></description>
        <use-caller-identity></use-caller-identity>
      </security-identity>
    </session>
  </enterprise-beans>
...
</ejb-jar>

Criação de um cliente

import java.util.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

public class CartClient {

  public static void main(String[] args) {
    try {
      Context initial = new InitialContext();
      Object objref = initial.lookup("java:comp/env/ejb/SimpleCart");

      CartHome home = 
          (CartHome)PortableRemoteObject.narrow(objref, 
                                       CartHome.class);

      Cart shoppingCart = home.create("Duke DeEarl","123");

      shoppingCart.addBook("The Martian Chronicles");
      shoppingCart.addBook("2001 A Space Odyssey");
      shoppingCart.addBook("The Left Hand of Darkness");
      
      Vector bookList = shoppingCart.getContents();
      Iterator enumer = bookList.iterator();
      while (enumer.hasNext()) {
        String title = (String) enumer.next();
        System.out.println(title);
      }

      shoppingCart.removeBook("Alice in Wonderland");
      shoppingCart.remove();

      System.exit(0);

    } catch (BookException ex) {
      System.err.println("Caught a BookException: " + ex.getMessage());
      System.exit(0);
    } catch (Exception ex) {
      System.err.println("Caught an unexpected exception!");
      ex.printStackTrace();
      System.exit(1);
    }
  } 
} 

Execução do exemplo CartEJB

C:\...\src\cart\earpronto>runclient -client CartApp.ear -
name CartClient -textauth
Initiating login ...
Username = null
Enter Username:guest
Enter Password:guest123
Binding name:`java:comp/env/ejb/SimpleCart`
The Martian Chronicles
2001 A Space Odyssey
The Left Hand of Darkness
Caught a BookException: Alice in Wonderland not in cart.
Unbinding name:`java:comp/env/ejb/SimpleCart`

exsession programa