Jee Unidad3
-
Upload
jose-narvaez -
Category
Documents
-
view
228 -
download
0
Transcript of Jee Unidad3
-
8/12/2019 Jee Unidad3
1/104
UNIVERSIDAD CARLOS III DE MADRIDDEPARTAMENTO DE INGENIERA TELEMTICA
SOFTWARE DE COMUNICACIONES (I.T.T.T)
Programacin con EJBs:Entity Beans y Session Beans
Pablo Basanta ValFlorina Almenares Mendoza
Basado en material de:Natividad Martnez Madrid, Marisol Garca Valls y Simon Pickin
Departamento de Ingeniera TelemticaUniversidad Carlos III de Madrid
{pbasant a, f l or i na, nat i , mval l s, spi cki n}@i t . uc3m. es
-
8/12/2019 Jee Unidad3
2/104
P . 2
Objetivos didcticos Comprender el contrato existente entre el servidor de
aplicaciones y los diferentes tipos de componentes Comprender el esquema de concurrencia de cada componente Comprender los esquemas de gestin de pooling , swapping ,
activation y pasivacin Comprender los modelos de gestin de la persistencia de tipo CMP
y BMP
Comprender y distinguir los ciclos de vida de los diferentes tiposde componentes EJB Entity Bean , Session Bean (stateless, statefull) y Message Beans Ver cmo los ciclos de la vida se corresponden al API
Aprender a codificar EJB Diseo de interfaces, mtodos de negocio, modelo de persistencia
e invocacin desde clientes Con Entity Beans de tipo CMP
Con Session Beans de tipo stateless
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
3/104
P . 3
ndice (1/3)Bloque I: Modelo ofertado por el contenedor a los EJBs
Qu modelo de concurrencia se asigna a cada tipo de componente El problema de la re-entrancia
Cmo se gestiona las estancias de cada uno de los beans Cmo se asigna una instancia del pool a un Entity Bean El swapping de un stateless bean La activacin y pasivacin de un session bean
Cmo se gestiona la persistencia (Entity Beans) Dos modelos de persistencia soportados (CMP y BMP) Configuraciones ms tpicas (objeto-relacional, persistencia BD O-O y
aplicacin legado)
Detalles del desarrollo con CMP Detalles del desarrollo con BMP
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
4/104
P . 4
ndice (2/3)
Bloque II: Ciclos de vida y reflejo en el API Entity Beans
Session Beans Message Beans
Bloque III: Programacin con Entity Beans de tipo CMP Caractersticas del modelo CMP
Caractersticas del modelo BMP Ejemplo del CabinBean (tipo CMP) Interfaz CabinRemote Interfaz CabinRemoteHome Interfaz CabinBean
Cliente Remoto Detalles
Contexto inicial en JNDI Mtodos lookup Mtodos narrow Consideraciones a tener en cuenta sobre RMI
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
5/104
P . 5
ndice (3/3)
Bloque IV: Programacin con Session Beans de tipo StateLess Caractersticas generales Diferencias existentes entre un StateFull y un StateLess Ejemplo del TravelAgentBean (tipo stateless)
Interfaz CabinRemote
Interfaz TravelAgentRemoteHome Interfaz TravelAgentBean Cliente TravelAgentClient
Bloque V: Ejercicios y cuestiones para profundizar
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
6/104P . 6
Modelos de concurrencia
soportados En el caso de los Session Beans
El acceso concurrente no est soportado bean de sesin con estado sirve nicamente un cliente el mbito de un bean de sesin sin estado es una sola invocacin
En el caso de los Entity Beans
El acceso concurrente es prohibido por defecto En el caso de los Message Beans
Permitido el tratamiento concurrente de mensajes (y esencial) mltiples instancias
Nota sobre los Session y Entity Beans Creacin de hilos por bean est prohibida Permite que el contenedor mantenga control de concurrencia
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
7/104P . 7Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Concurrencia y cdigo reentrante
en EJBs Los beans de entidad no son reetrantes (por defecto) No permite loopbacks: callbacks directos o indirectos
p.ej. un cliente llama al objeto A, A llama a B, B llama a A en el descriptor de despliegue se puede cambiar:
False
Los beans de sesin nunca pueden ser reentrantes Una excepcin es lanzada si un loopback es intentado
Problema: contenedor no puede distinguir entre Acceso concurrente por el mismo hilo via loopback Acceso concurrente por distintos hilos
Instancia de bean invoca sus propios mtodos No se considera reentrante
-
8/12/2019 Jee Unidad3
8/104P . 8
Pooling de instancias Delegacin: los clientes no acceden a las instancias
directamente
Acceso a travs de objetos EJB implementacin de las interfaces locales y remotas (EJB 2.0)
El servidor mantiene un pool de instancias
Que se asocian a los objetos EJB cuando se requiere Aplica a beans de entidad y a beans de sesin sin estado Puede ser compartido por mltiples clientes
Manejo de recursos ms eficiente
Beans dirigidos a mensaje beans se suscriben a un destino de mensajes especifico clientes entregan mensajes a alguno de los destinos
contenedor crea un pool de beans por cada destino
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
9/104P . 9Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Asignacin de una instancia del
Pool
Fuente:Enterprise JavaBeans, Fourth Edit ionBy Richard Monson-Haefel (Author), BillBurke (Author), Sacha Labourey (Author)Publisher: OReilly
-
8/12/2019 Jee Unidad3
10/104P . 10
Beans de sesin sin estado & Swapping de instancia
Beans de sesin sin estado ( stateless session beans ) Se declaran como tales en el descriptor de despliegue
se codifican de la misma forma que los beans de sesin con estado ( stateful sessionbeans )
No deben mantener el estado conversacional, aunque pueden tener variables de instancia pueden obtener informacin de JNDI ENC
Asignacin de una instancia por invocacin el mismo cliente servido por instancias de bean diferente la misma instancia de bean es swapped entre objetos EJB /
clientes pocas instancias de beans de sesin sin estado sirven a muchos
clientes ciclo de vida: combina los estados ready y pooled de los
beans de entidad
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
11/104P . 11Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Ejemplo Swapping
Fuente:Enterprise JavaBeans, Fourth Edit ionBy Richard Monson-Haefel (Author), BillBurke (Author), Sacha Labourey (Author)Publisher: OReilly
-
8/12/2019 Jee Unidad3
12/104P . 12
Activacin/ Passivation Los beans de sesin con estado no participan en el
pooling de instancias El estado de la conversacin con el cliente debe mantenerse
durante toda la vida del servicio proporcionado a dicho cliente El contenedor usa activacin/ passivation
para gestionar recursos
mecanismo transparente al cliente
Passivation: disociacin del objeto EJB y la instancia del bean serializacin del estado de la instancia a almacenamiento
secundario
Activacin: Restauracin del estado de la instancia relativa al objeto EJB
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
13/104P . 13
Proceso de
Activacin/ Passivation
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), BillBurke (Author), Sacha Labourey (Author)Publisher: OReilly
-
8/12/2019 Jee Unidad3
14/104P . 14
Activacin/ Passivation Beans de entidad
Tambin aplica a los beans de entidad para notificar a la instancia cuando va a ser swapped hacia o
fuera del pool de instancia
Passivation Libera recursos Almacena los datos que contiene en la base de datos
subyacente
Activacin Adquiere los recursos Carga los datos de la base de datos subyacente
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
15/104P . 15
Ciclo de vida de un Entity Bean
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:
Java EE Tutorial 1.4 , Fourth Edition
-
8/12/2019 Jee Unidad3
16/104P . 16
API de un Entity Bean
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Method Summary
void ejbActivate() A container invokes this method when the instance is taken outof the pool of available instances to become associated with a specific EJBobject.
void ejbLoad() A container invokes this method to instruct the instance tosynchronize its state by loading it state from the underlying database.
void ejbPassivate () A container invokes this method on an instance before theinstance becomes disassociated with a specific EJB object.
void ejbRemove() A container invokes this method before it removes the EJB objectthat is currently associated with the instance.
void ejbStore() A container invokes this method to instruct the instance tosynchronize its state by storing it to the underlying database.
void setEntityContext(EntityContext ctx) Set the associated entity context.void unsetEntityContext() Unset the associated entity context.
Fuente:http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#ejbActivate%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#ejbLoad%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#ejbPassivate%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#ejbRemove%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#ejbStore%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#setEntityContext%28javax.ejb.EntityContext%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityContext.htmlhttp://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#unsetEntityContext%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#unsetEntityContext%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityContext.htmlhttp://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#setEntityContext%28javax.ejb.EntityContext%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#ejbStore%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#ejbRemove%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#ejbPassivate%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#ejbLoad%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/EntityBean.html#ejbActivate%28%29 -
8/12/2019 Jee Unidad3
17/104P . 17Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Ciclo de vida de los Session Beans
a) Statefull b) Stateless
-
8/12/2019 Jee Unidad3
18/104P . 18
API de los SessionBeans
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Method Summary
void ejbActivate() The activate method is called when the instance is activated from its"passive" state.
void ejbPassivate () The passivate method is called before the instance enters the"passive" state.
void ejbRemove() A container invokes this method before it ends the life of the sessionobject.
void setSessionContext (SessionContext ctx) Set the associated session context.
Fuente:http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/SessionBean.html
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/SessionBean.html#ejbActivate%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/SessionBean.html#ejbPassivate%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/SessionBean.html#ejbRemove%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/SessionBean.html#setSessionContext%28javax.ejb.SessionContext%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/SessionContext.htmlhttp://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/SessionContext.htmlhttp://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/SessionBean.html#setSessionContext%28javax.ejb.SessionContext%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/SessionBean.html#ejbRemove%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/SessionBean.html#ejbPassivate%28%29http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/SessionBean.html#ejbActivate%28%29 -
8/12/2019 Jee Unidad3
19/104P . 19
Ciclo de vida de un Message
Bean
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
20/104P . 20
API de un MessageBean
Method Summary
void ejbRemove() A container invokes this method before it ends the life of the
message-driven object.void setMessageDrivenContext(MessageDrivenContext ctx) Set the associated
message-driven context.
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/MessageDrivenBean.html0
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/MessageDrivenBean.html#setMessageDrivenContext(javax.ejb.MessageDrivenContext)http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/MessageDrivenContext.htmlhttp://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/MessageDrivenContext.htmlhttp://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/ejb/MessageDrivenBean.html#setMessageDrivenContext(javax.ejb.MessageDrivenContext) -
8/12/2019 Jee Unidad3
21/104P . 21
Persistencia Los beans de entidad son persistentes
Su estado se almacena permanentemente en una base de datos Valores de atributos de la instancia del bean son sincronizados con la
base de datos
Persistencia manejada por contenedor ( Container-managedpersistence, CMP) gestionada automticamente
beans independiente de una base de datos especifica el contenedor genera la lgica de acceso a la base de datos en tiempode despliegue
Persistencia manejada por bean ( Bean-managed persistence, BMP) gestionada manualmente (contenedor asistido) desarrollador debe entender la estructura de la base de datos y APIs ms flexibilidad; por ejemplo, para sistemas legados no soportados por
el vendedor pero menos flexibilidad a la hora de realizar cambios
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
22/104P . 22
Implementaciones comunes de
persistencia Persistencia objeto-relacional
el bean se representa como una tabla (o ms) Varias tablas: cambios en el bean de entidad requiere a menudo joins SQL
las propiedades (atributos) se representan como columnas dela tabla
cada instancia del bean ser una fila de la tabla CMP: el contenedor se encarga de mantener el estado de la
instancia consistente con las tablas Sincronizar el estado de la instancia del bean
CMP: intercepcin en la creacin y borrado de instancias Resultados en la creacin y borrado de registros de la BD
La identidad del bean de entidad representa un puntero a suestado en la BD
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
23/104P . 23
Implementaciones comunes de persistencia (II)
Persistencia BD O-O ms limpia la asociacin entre beans de entidad y la BD ms eficientes para grafos de objetos complejos menos aceptadas y extendidas que las relacionales
Persistencia legada CMP requiere un contenedor especial sistema legado no es soportado por el vendedor: BMP
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
24/104P . 24
Entity Bean de tipo CMP La clase de un bean de entidad CMP debe ser abstracta Los elementos persistentes se acceden mediante mtodos
especiales No se declaran los atributos persistentes
Tpicamente se utilizan getters y setters pr i vat e abst r act St r i ng get Name( ) ;
pr i vat e abst r act St r i ng set Name( ) ; El contenedor ha de generar el cdigo necesario para acceder al
sistema EIS (tpicamente a la base de datos).
No se suelen implementar los mtodos de callback No se implementan los mtodos ej bSt or e (), ej bLoad (),
ej bAct i vat e (), ej bPassi vat e (), set Ent i t yCont ext (),unSet Ent i t yCont ext (), ej bRemove ().
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
25/104P . 25
Entity Bean de tipo CMP (II) Se suelen implementar de la interfaz mtodos de tipo create
Cuando queremos poder crear nuevos objetos persistentes Internamente hay un equivalente de tipo ej bCr eat e
No se implementan los mtodos de bsqueda por cada mtodo de bsqueda opcional ( f i ndByXxx )
habr una entrada en el descriptor de despliegue, que utiliza EJB QL
EJB QL (Query Language ) Una consulta EJB QL es una cadena que contiene tres clusulas:
SELECT, FROM, y opcionalmente WHERE Por ejemplo:
SELECT OBJ ECT( p) FROM Per sona AS p WHERE p. edad > ; ?1
Los mtodos de negocio Cuando queremos poder crear nuevos objetos persistentes Mantienen la signatura que se les da en la interfaz remota
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
26/104P . 26
Entity Bean de tipo BMP Es una clase no abstracta
No hay mtodos abstractos de tipo get ni set
Se suelen implementar tres tipos de mtodos de creacin, bsqueda y algunos de callback
ej bCr eat e ej bFi ndByPr i mar yKey ej bLoad , ej bSt or e , ej bRemove, set Ent i t yCont ext , unset Ent i t yCont ext
El programador hay de realizar todas las comunicaciones con el EIS Por ejemplo si es una base de datos
Se suele obtener debe obtener un recurso de conexin del ENC JNDIDat asour ce ds =( Dat aSour ce) cnt x. l ookup( " j ava: comp/ env/ j dbc/ t i t anDB" ) ;
Y tambin se crea el objeto data source
En ellos el desarrollador es responsable de lanzar las excepcionesen el momento correcto
Abre, cierra y reutiliza conexiones con la base de datos
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
27/104P . 27
Manejada por bean vs. por el contenedor
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
AccountBeanJDBCDriver RDBMSData Access
Component
AccountBeanRM2
Driver RM2Data AccessComponent
JDBC API
RM2 API
AccountBeanJDBCDriver RDBMS
JDBC APIGeneracinde cdigo
JDBC
CMP
AccountBeanRM2
Driver RM2RM2 APIGeneracin
de cdigoRM2
CMP
-
8/12/2019 Jee Unidad3
28/104P . 28
Ejemplo de componente Entity
CMP Ejemplo bean de entidad: Cabin
Modela un camarote en un barco crucero Interfaz remota: CabinRemote Interfaz remota home: CabinHomeRemote Clase: CabinBean
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
29/104P . 29
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Interfaz remota: CabinRemotepackage com. t i t an. cabi n;i mpor t j ava. r mi . Remot eExcept i on;
publ i c i nt er f ace Cabi nRemot e ext ends j avax. ej b. EJ BObj ect {
publ i c St r i ng get Name ( ) t hr ows Remot eExcept i on;publ i c voi d set Name ( St r i ng st r ) t hr ows Remot eExcept i on;
publ i c i nt get DeckLevel ( ) t hr ows Remot eExcept i on;publ i c voi d set DeckLevel ( i nt l evel ) t hr ows Remot eExcept i on;publ i c i nt get Shi pI d ( ) t hr ows Remot eExcept i on;publ i c voi d set Shi pI d ( i nt sp) t hr ows Remot eExcept i on;
publ i c i nt get BedCount ( ) t hr ows Remot eExcept i on;publ i c voi d set BedCount ( i nt bc) t hr ows Remot eExcept i on;
}Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
-
8/12/2019 Jee Unidad3
30/104
P . 30
Interfaz remota home :
CabinHomeRemotepackage com. t i t an. cabi n;i mpor t j ava. r mi . Remot eExcept i on;
i mpor t j avax. ej b. Cr eat eExcept i on;i mpor t j avax. ej b. Fi nder Except i on;
publ i c i nt er f ace Cabi nHomeRemot e ext ends j avax. ej b. EJ BHome {
publ i c Cabi nRemot e create ( I nt eger i d)
t hr ows Cr eat eExcept i on, Remot eExcept i on;
publ i c Cabi nRemot e f i ndByPr i mar yKey ( I nt eger pk)t hr ows Fi nder Except i on, Remot eExcept i on;
}
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth Edit ionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
-
8/12/2019 Jee Unidad3
31/104
P . 31
Clase bean: CabinBean (I)package com. t i t an. cabi n;
i mpor t j avax. ej b. Ent i t yCont ext ;i mpor t j avax. ej b. Cr eat eExcept i on;
publ i c abst r act cl ass Cabi nBeani mpl ement s j avax. ej b. Ent i t yBean {
publ i c I nt eger ej bCr eat e ( I nt eger i d)
t hr ows Cr eat eExcept i on {t hi s. set I d( i d) ;r et ur n i d;
}
publ i c voi d ej bPost Cr eat e ( I nt eger i d)t hr ows Cr eat eExcept i on {
}
[ ]
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
-
8/12/2019 Jee Unidad3
32/104
P . 32
Clase bean: CabinBean (II)[ ]
publ i c abst r act voi d set I d ( I nt eger i d) ;publ i c abst r act I nt eger get I d ( ) ;
publ i c abst r act voi d set Shi pI d ( i nt shi p) ;publ i c abst r act i nt get Shi pI d ( ) ;
publ i c abst r act voi d set Name ( St r i ng name) ;publ i c abst r act St r i ng get Name ( ) ;
publ i c abst r act voi d set BedCount ( i nt count ) ;publ i c abst r act i nt get BedCount ( ) ;
publ i c abst r act voi d set DeckLevel ( i nt l evel ) ;publ i c abst r act i nt get DeckLevel ( ) ;
[ ]
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
-
8/12/2019 Jee Unidad3
33/104
P . 33Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Clase bean: CabinBean (III)publ i c voi d set Ent i t yCont ext ( Ent i t yCont ext ct x) {
/ / Not i mpl ement ed.}publ i c voi d unset Ent i t yCont ext ( ) {
/ / Not i mpl ement ed.}publ i c voi d ej bAct i vat e ( ) {
/ / Not i mpl ement ed.}publ i c voi d ej bPassi vat e ( ) {
/ / Not i mpl ement ed.}publ i c voi d ej bLoad ( ) {/ / Not i mpl ement ed.}publ i c voi d ej bSt or e ( ) {
/ / Not i mpl ement ed.}publ i c voi d ej bRemove ( ) {/ / Not i mpl ement ed.}
}
Fuente:
Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
C i b l
-
8/12/2019 Jee Unidad3
34/104
P . 34
Comentarios sobre el
CabinBean El mtodo ejbCreate La interfaz home tiene un mtodo create con la misma
signatura
El mtodo findByPrimaryKey La interfaz home define siempre este mtodo Los beans de entidad CMP no necesitan implementarlo (lo
hace el contenedor) primary key es algn objeto serializable
Los atributos persistentes no se declaranexplcitamente tiene mtodos abstractos modificadores y de acceso
La interfaz remota no tiene un mtodo get y set parael atributo I d
No implementa ninguno de los mtodos de callback p. ej. ej bSt or e, ej bLoad, ej bRemove
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
35/104
P . 35
Descriptor de despliegue CabinEJB
Cabi nEJ B com. t i t an. cabi n. Cabi nHomeRemot e com. t i t an. cabi n. Cabi nRemot e
com. t i t an. cabi n. Cabi nBean Cont ai ner j ava. l ang. I nt eger Fal se Cabi n
. . .
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
D i d d li
-
8/12/2019 Jee Unidad3
36/104
P . 36
Descriptor de despliegue
CabinEJB (II) shi pI d name deckLevel bedCount i d i d
. . .
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
-
8/12/2019 Jee Unidad3
37/104
P . 37
Descriptor de despliegue CabinEJB (III). . .
ever yone
Cabi nEJ B *
Cabi nEJ B *
Requi r ed
. . .
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth Edit ionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
C i b l
-
8/12/2019 Jee Unidad3
38/104
P . 38
Comentarios sobre el
despliegue Se realiza con el fichero ejb-jar.xml (deployment
descriptor ) y con ayuda de la herramienta de despliegue (deploy tool) del servidor EJB,
o Un entorno de desarrollo integrado (por ejemplo, NetBeans o
Eclipse)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
C i d t bl C bi
-
8/12/2019 Jee Unidad3
39/104
P . 39
Creacin de una tabla Cabin en
la BD La herramienta de instalacin/despliegue mapea beans deentidad a tablas de la bases de datos Pero primero necesita instalar la BD y crear una tabla CABIN
En este ejemplo, se utiliza la siguiente sentencia SQL:create table CABIN(
ID int primary key NOT NULL,SHIP_ID int,BED_COUNT int,
NAME char(30),DECK_LEVEL int
)
En algunos casos se puede forzar a que el motor de eldespliegue del EJB cree las tablas ( opcin: create tables on
deployment)Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
40/104
P . 40Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Cliente remoto Client1package com. t i t an. cl i ent s;
i mpor t com. t i t an. cabi n. Cabi nHomeRemot e;
i mpor t com. t i t an. cabi n. Cabi nRemot e;
i mpor t j avax. nami ng. I ni t i al Cont ext ;i mpor t j avax. nami ng. Cont ext ;
i mpor t j avax. nami ng. Nami ngExcept i on;i mpor t j avax. r mi . Por t abl eRemot eObj ect ;i mpor t j ava. r mi . Remot eExcept i on;i mpor t j ava. ut i l . Pr oper t i es ;
Fuente:Enterprise JavaBeans, Fourth Edition
By Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
-
8/12/2019 Jee Unidad3
41/104
P . 41
Cliente remoto Client1 (II)publ i c cl ass Cl i ent 1 {
publ i c st at i c voi d mai n( St r i ng [ ] ar gs) {t r y {
Cont ext j ndi Cont ext = get I ni t i al Cont ext ( ) ;
Obj ect r ef = j ndi Cont ext . l ookup ( " Cabi nHomeRemot e" ) ;
Cabi nHomeRemot e home = ( Cabi nHomeRemot e)Por t abl eRemot eObj ect .
narrow ( r ef , Cabi nHomeRemot e. cl ass) ;i f ( r ef ! = nul l ) {
Syst em. out . pr i nt l n( " Found Cabi n Home" ) ;}Cabi nRemot e cabi n1=home. create ( new I nt eger ( 1) ) ;
cabi n1. set Name ( " Mast er Sui t e" ) ;cabi n1. set DeckLevel (1 ) ;cabi n1. set Shi pI d (1 ) ;cabi n1. set BedCount (3 ) ;
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
-
8/12/2019 Jee Unidad3
42/104
-
8/12/2019 Jee Unidad3
43/104
P . 43
Cliente remoto Client1 (IV)publ i c s t at i c Cont ext get I ni t i al Cont ext ( )
t hr ows j avax. nami ng. Nami ngExcept i on {Pr oper t i es p = new Pr oper t i es( ) ;/ / speci f y t he J NDI Pr oper t i es speci f i c t o t he vendorp. put ( Cont ext . I NI TI AL_CONTEXT_FACTORY,
"webl ogi c. j ndi . WLI ni t i al cont ext Fact or y") ;p. put ( Cont ext . PROVI DER_URL, " t 3: / / l ocal host : 7001" ) ;
r et ur n new j avax. nami ng. I ni t i al Cont ext ( p) ;} / / get I ni t i al cont ext
} / / cl ass
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
-
8/12/2019 Jee Unidad3
44/104
-
8/12/2019 Jee Unidad3
45/104
P . 45
Contexto inicial JNDI JNDI: API del servicio de nombres
Acceso uniforme a diferentes servicios de nombres LDAP, NIS+, CORBA Naming,...
parecido a obtener una conexin al controlador de JDBC: accesouniforme a diferentes bases de datos relacionales
JNDI: organiza elementos EJB en estructura de directoriosvirtuales
beans, servicios, datos, recursos vistos como directorios en el sistema de ficheros comn puede incluso estar distribuido
contexto inicial raz del sistema de fichero JNDI Objeto InitialContext creado en la llamada a getInitialContext()
Objeto Properties pasado al objeto InitialContext en la creacin, el cual indica:
Dnde est el servidor EJB Qu controlador JNDI ( JNDI service provider ) cargar
Parmetros son dependientes de la implementacin
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Contexto inicial en aplicaciones
-
8/12/2019 Jee Unidad3
46/104
P . 46
Contexto inicial en aplicaciones
.ear Es ms sencillo pues se puede revolver el problema haciendo uso
de un mtodo initial context
I ni t i al Cont ext i ct x = new I ni t i al Cont ext ( ) ;Obj ect h = i ct x. l ookup( j ava: comp/ env/ ej b/ Cabi nEJ B) ;
De bastante utilidad cuando queremos acceder desde una pagina jsp a un entity almacenado dentro del mismo ear
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
47/104
P . 47
Lookup en JNDI
lookup() de la interfaz home mtodo de la clase javax.naming.Context el nombre de objeto buscado es pasado como argumento
uso: Object ref = jndiContext.lookup("CabinHomeRemote");
Bean como cliente de otro bean bean puede buscar el home de otro bean en su propio JNDI
ENC ( Environment Naming Context ) ENC para cada bean creado en el despliegue: ENC inicial: java:com/env Localizacin de otros beans a los que accede: java:com/env/ejb
ejemplo: Object ref =jndiContext.lookup(java:comp/env/ejb/CabinHomeRemote)
lookup de otros recursos: ENC da acceso a las propiedades y otros recursos del contenedor
parmetros de inicializacin, etc.Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
48/104
P . 48
Narrow y Casting narrow()
mtodo de la clase javax.rmi.PortableRemoteObject definido en java.lang.Object
argumentos referencia remota para ser narrowed Tipo al cual debera ser narrowed
uso: CabinHomeRemote home = (CabinHomeRemote)PortableRemoteObject.narrow(ref, CabinHomeRemote.class);
Especie de casting para objetos remotos compatibilidad CORBA: RMI sobre IIOP CORBA admite muchos lenguajes, no todos tienen un casting nativo
Si la referencia devuelta tiene directamente el tipo adecuado narrow() no es necesario
p.ej. create() devuelve directamente un objeto CabinRemote
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
I i d t d t (RMI)
-
8/12/2019 Jee Unidad3
49/104
P . 49
Invocacin de mtodo remoto (RMI):
Tipos Interfaces de componentes remotos utilizan tipos Java RMI
Existen dos clases de tipos de retorno y parmetros tipos declarados: verificados en tiempo de compilacin tipos reales: verificados en tiempo de ejecucin
Java RMI restringe los tipos de parmetros reales a:
Primitivos ( byt e , bool ean , char , i nt , l ong , doubl e , f l oat ) String remoto ( java.rmi.Remote )
No tienen explcitamente que implementar java.rmi.Remote
serializable ( java.io.Serializable ) No tienen explcitamente que implementar java.io.Serializable p. ej. j ava. ut i l . Col l ect i on
La restriccin no est en los tipos de parmetros declarados Tipos declarados pueden no ser remotos / serializable
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Tipos de parmetros
-
8/12/2019 Jee Unidad3
50/104
P . 50
Tipos de parmetros
Serializable y remoto Serializable:
se pasa por valor se pasa una copia del objeto cambios al objeto no son vistos por el objeto que tiene la copia
Remoto: se pasa como referencia remota se pasa una copia del stub (paso por valor del stub)
la copia del stub apunta al mismo objeto remoto cambios al objeto son vistos por todos los objetos que tienen
referencias remotas
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
51/104
P . 51
Serializacin de referencias remotas: Handles
Un Handle es Una instancia de javax.ejb.Handle Una referencia serializada al objeto EJB
Un cliente puede Serializar handle para almacenar la referencia al objeto remoto EJB deserializar handle para recuperar la referencia al objeto remoto EJB
Conversin a / desde un formato serializable desde EJBObject a Handle : EJBObject.getHandle() desde Handle a EJBObject : Handle.getEJBObject()
Debe ser narrowed a un tipo de interfaz remota adecuado
Handle handle = // get HandleObject ref = handle.getEJBObject();CabinRemote cabin = (CabinRemote)
PortableRemoteObject.narrow(...);
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
52/104
P . 52
Beans de sesin con estado
Mantienen el estado del lado del servidor en representacinde un solo cliente
El estado conversacional consta de variables de instancia definidas en la clase bean
datos ledos de la base datos (o un bean de entidad)
objetos alcanzables desde la variables de instancia por ejemplo, datos introducidos por el usuario
Si se utiliza desde un cliente servlet o JSP la primera vez, el cliente obtiene la referencia del EJB
la almacena como atributo del objeto Ht t pSessi on
a continuacin, para acceder al EJB se obtiene la referencia delobjeto sesin
No poseen mtodos ni find ni unsetSessionContext
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Bean de session sin estado
-
8/12/2019 Jee Unidad3
53/104
P . 53
Bean de session sin estado
(stateless) Desde el punto de vista del programador
Esta prohibido el guardar ningn tipo de estado dentro delentity bean
Desde el punto de vista del contenedor No hay diferencia entre clientes (puesto que no guardan ningn
tipo de estado), lo cual permite que sean reutilizados por diferentes clientes
Se distingue de un session bean de tipo session de uno de tipo
stateless mediante el atribution session-typeStatelessStateful
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
54/104
P . 54
Statefull vs. Stateless
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Contenedor EJB(statefull)obj1:EnrollmentRMI
obj2:EnrollmentRMI
obj2:EnrollmentRMI
inst1:EnrollmentBean
inst2:EnrollmentBean
inst3:EnrollmentBean
Client1
Client2Client3
Contenedor EJB(stateless)
inst1:PayrollBean
inst2:PayrollBean
inst3:PayrollBean
Client1
Client2
Client3
obj:PayrollRMI
Fuente: Applying Enterprise JavaBeans:Component-Based Development for the J2EE Platform, Second EditionBy: Vlada Matena; Sanjeev Krishnan; Linda DeMichiel; Beth Stearns Publisher: Prentice Hall
-
8/12/2019 Jee Unidad3
55/104
P . 55
Ejemplo de Session Bean : TravelAgentEJB
Ejemplo de un bean de sesin: Tr avel Agent Modela un agente de viaje utilizado para reservar un viaje en
un barco crucero Interfaz remota: TravelAgentRemote Interfaz remota home: TravelAgentHomeRemote
Clase: TravelAgentBean
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Interfaz remota:
-
8/12/2019 Jee Unidad3
56/104
P . 56
Interfaz remota:
TravelAgentRemotepackage com. t i t an. t r avel agent ;i mpor t j ava. r mi . Remot eExcept i on;
i mpor t j avax. ej b. Fi nder Except i on;
publ i c i nt er f ace Tr avel Agent Remot eext ends j avax. ej b. EJ BObj ect {
/ / St r i ng el ement s f ol l ow t he f or mat/ / " i d, name, deck l evel "publ i c St r i ng [ ] l i st Cabi ns ( i nt shi pI D,
i nt bedCount ) t hr ows Remot eExcept i on;
}
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
Interfaz remota home :T lA tH R t
-
8/12/2019 Jee Unidad3
57/104
P . 57
Interfaz remota home :TravelAgentHomeRemote
package com. t i t an. t r avel agent ;i mpor t j ava. r mi . Remot eExcept i on;i mpor t j avax. ej b. Cr eat eExcept i on;
publ i c i nt er f ace Tr avel Agent HomeRemot eext ends j avax. ej b. EJ BHome {
publ i c Tr avel Agent Remot e create ( )t hr ows Remot eExcept i on, Cr eat eExcept i on;
}
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
-
8/12/2019 Jee Unidad3
58/104
P . 58
Clase Bean: Tr avelAgentBean (I)publ i c cl ass Tr avel Agent Bean i mpl ement s j avax. ej b. Sessi onBean {
publ i c voi d ej bCr eat e ( ) t hr ows Cr eat eExcept i on {/ / Do not hi ng.
}
publ i c St r i ng [ ] l i st Cabi ns ( i nt shi pI D, i nt bedCount ) {
t r y { j avax. nami ng. Cont ext j ndi Cont ext = new I ni t i al Cont ext ( ) ;Obj ect obj =
j ndi Cont ext . l ookup ( " j ava: comp/ env/ ej b/ Cabi nHomeRemot e" ) ;
Cabi nHomeRemot e home = ( Cabi nHomeRemot e) j avax. r mi . Por t abl eRemot eObj ect .narrow ( obj , Cabi nHomeRemot e. cl ass) ;
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:
Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
Cl se Be n T lA B (II)
-
8/12/2019 Jee Unidad3
59/104
P . 59
Clase Bean: TravelAgentBean (II)[ . . . ]
Vect or vect = new Vect or ( ) ;f or ( i nt i = 1; ; i ++) {
I nt eger pk = new I nt eger ( i ) ;Cabi nRemot e cabi n = nul l ;t r y {
cabi n = home. f i ndByPr i mar yKey (pk);} cat ch( j avax. ej b. Fi nder Except i on f e) {
br eak;}/ / Check t o see i f t he bed count and shi p I D mat ch .i f ( cabi n ! = nul l &&
cabi n. get Shi pI d ( ) == shi pI D &&cabi n. get BedCount ( ) == bedCount ) {St r i ng det ai l s = i + " , " + cabi n. get Name ( ) + " , " +
cabi n. get DeckLevel ( ) ;vect . addEl ement ( det ai l s) ;
}}
[ . . . ]
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth Edit ionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
-
8/12/2019 Jee Unidad3
60/104
P . 60
Clase Bean: TravelAgentBean (III)[ . . . ]
St r i ng [ ] l i s t = new St r i ng[ vect . s i ze( ) ] ;vect . copyI nt o( l i st ) ;r et ur n l i st ;
} cat ch( Except i on e) {t hr ow new EJ BExcept i on( e) ;
}}
pr i vat e j avax. nami ng. Cont ext get I ni t i al Cont ext ( )t hr ows j avax. nami ng. Nami ngExcept i on {Pr oper t i es p = new Pr oper t i es( ) ;/ / . . . Speci f y t he J NDI pr oper t i es speci f i c t o t he vendor .r et ur n new j avax. nami ng. I ni t i al Cont ext ( p) ;
}
[ . . . ]
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
-
8/12/2019 Jee Unidad3
61/104
P . 61
Clase Bean: TravelAgentBean (IV)
[ . . . ]
publ i c voi d ej bRemove ( ){}
publ i c voi d ej bAct i vat e ( ){}
publ i c voi d ej bPassi vat e ( ) { }
publ i c voi d set Sess i onCont ext( j avax. ej b. Sessi onCont ext cnt x) {}
}
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
Descriptor de despliegue TravelAgentEJB
-
8/12/2019 Jee Unidad3
62/104
P . 62
Descriptor de despliegue TravelAgentEJB
Tr avel Agent EJ Bcom. t i t an. t r avel agent . Tr avel Agent HomeRemot ecom. t i t an. t r avel agent . Tr avel Agent Remot ecom. t i t an. t r avel agent . Tr avel Agent BeanStatelessCont ai ner
ejb/CabinHomeRemoteEntitycom.titan.cabin.CabinHomeRemotecom.titan.cabin.CabinRemote
. . .
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBsFuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
l ( )
-
8/12/2019 Jee Unidad3
63/104
P . 63
Cliente TravelAgentClient (I)publ i c cl ass Tr avel Agent Cl i ent {
publ i c st at i c i nt SHI P_I D = 1;publ i c s t at i c i nt BED_COUNT = 3;
publ i c st at i c voi d mai n ( St r i ng [ ] ar gs) {t r y {
Cont ext j ndi Cont ext = get I ni t i al Cont ext ( ) ;Obj ect r ef = j ndi Cont ext . l ookup ( " Tr avel Agent Home" ) ;
Tr avel Agent HomeRemot e home = ( Tr avel Agent HomeRemot e)Por t abl eRemot eObj ect . narrow ( r e f ,
Tr avel Agent HomeRemot e. cl ass) ;
Tr avel Agent Remot e t r avel Agent = home. create ( ) ;[ . . . ]
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:Enterprise JavaBeans, Fourth Edition
By Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
Cli t d l l (II)
-
8/12/2019 Jee Unidad3
64/104
P . 64
Cliente de TravelAgentClient (II)[ . . . ]
/ / Get a l i st of al l cabi ns on shi p 1 wi t h a bed count of 3.St r i ng l i st [ ] =
t r avel Agent . l i st Cabi ns ( SHI P_I D, BED_COUNT) ;f or ( i nt i = 0; i < l i st . l engt h; i ++) {
Syst em. out . pr i nt l n( l i st [ i ] ) ;}
} cat ch( j ava. r mi . Remot eExcept i on r e) {r e. pr i nt St ackTr ace( ) ;
} cat ch( Thr owabl e t ) {t . pr i nt St ackTr ace( ) ;
}Syst em. exi t ( 0) ;
}
st at i c publ i c Cont ext get I ni t i al Cont ext ( ) t hr ows Except i on {Pr oper t i es p = new Pr oper t i es( ) ;/ / speci f y t he J NDI pr oper t i es speci f i c t o t he vendorr et ur n new I ni t i al Cont ext ( p) ;
}
}
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Fuente:
Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
j i i 1 l i d C
-
8/12/2019 Jee Unidad3
65/104
P . 65
Ejercicio 1: Implementacin de un Bean CMP
package com. t i t an. cust omer ;publ i c i nt er f ace Cust omer Remot e
ext ends j avax. ej b. EJ BObj ect {
publ i c St r i ng get Last Name ( ) t hr ows Remot eExcept i on;publ i c voi d set Last Name ( St r i ng l name)
t hr ows Remot eExcept i on;
publ i c St r i ng get Fi r st Name ( ) t hr ows Remot eExcept i on;publ i c voi d set Fi r st Name ( St r i ng f name)
t hr ows Remot eExcept i on;
}
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Crea un bean de entidad CMP que tenga las siguientes interfacesremotas: CustomerRemote y CustomerHomeRemote
publ i c i nt er f ace Cust omer HomeRemot eext ends j avax. ej b. EJ BHome {
publ i c Cust omer Remot e create ( I nt eger i d)t hr ows Cr eat eExcept i on, Remot eExcept i on;
publ i c Cust omer Remot e f i ndByPr i mar yKey ( I nt eger i d)t hr ows Fi nder Except i on, Remot eExcept i on;
}Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
Ejercicio 2: Proceso de negocio soportado por un stateless
-
8/12/2019 Jee Unidad3
66/104
P . 66
Ejercicio 2: Proceso de negocio soportado por un stateless
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Cree un componente: IntercambiaUsuariosEJB , session bean detipo stateless, que tenga un mtodo (intercambia) que intercambielos datos de dos usuarios ( f i r st name y l ast name ). Diseetanto la interfaces de la vista cliente como la implementacin delbean.
publ i c i nt er f ace I nt er cambi aUsuar i oRemot eext ends j avax. ej b. EJ BObj ect {
publ i c St r i ng i nt er cambi a ( I nt eger user 1, I nt eger user 2) t hr ows
Remot eExcept i on;}
Fuente:Enterprise JavaBeans, Fourth EditionBy Richard Monson-Haefel (Author), Bill Burke (Author), Sacha Labourey (Author) Publisher: OReilly
Cuestiones para profundizar
-
8/12/2019 Jee Unidad3
67/104
P . 67
Cuestiones para profundizar
(1/2)Bloque I: Acciones llevadas a cabo por el servidor Cul es el principal motivo por el que se soporta pasivacin en la arquitectura
J2EE?
El contenedor de EJBs, puede utilizar pooling con un Session de tipostateful?
En un SessionBean, es posible acceder tomar acciones cuando este sepasivaza o activa?Cmo?
Bloque II: Ciclos de vida y API Cul es el principal motivo por el que se soporta pasivacin en la arquitectura
J2EE? Para que sirven los mtodos ejbActivate y ejbPassivate()?Por qu no
aparecen en un Message Driven Bean?
Bloque III: Programacin con CMP En la codificacin de un Entity Bean de tipo CMP, qu propiedad cumplen los
mtodos que permiten acceder al estado persistente del objeto? Cul es la diferencia entre entre ejbCreate y ejbPostCreate? Diga cuales son los pasos que da un cliente (de consola) al invocar a un
EntityBean ya existente
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
Cuestiones para profundizar
-
8/12/2019 Jee Unidad3
68/104
P . 68
Cuestiones para profundizar
(2/2)Bloque V: Creacin de un Session Bean de tipo StateLess
Cmo se sabe si un SessionBean es de tipo StateFull o StateLess?
Por qu un componente de tipo StateLess no tiene mtodos find?
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
UNIVERSIDAD CARLOS III DE MADRIDDEPARTAMENTO DE INGENIERA TELEMTICA
-
8/12/2019 Jee Unidad3
69/104
DEPARTAMENTO DE INGENIERA TELEMTICASOFTWARE DE COMUNICACIONES (I.T.T.T)
Material Auxiliar:-Entity Bean tipo BMP (SelectionEJB)-Session Bean de tipo Statefull (EnrollmentEJB)
-
8/12/2019 Jee Unidad3
70/104
P . 70
Partes lgicas de la aplicacin de Beneficios
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs 70
EmployeeDatabase
PayrollEJB
PayrollSystem
BenefitsDatabase
PremiumHealthDatabase
Partes de Start Engine
Partes de Wombat
Partes de Providence
Partes de PremiumHealth
EnrollmentWeb
PayrollEJB
EnrollMentEJB
WrrapperPlanEJB
SelectionEJB
EmployeeEJB
ProvidencePlanEJB ProvidenceServiceWeb
PremiumHealthAdminApp
PremiumAdminWeb
PremiumHealthPlanEJB
SelectionEJB: Interfaz remota y Home
-
8/12/2019 Jee Unidad3
71/104
P . 71
SelectionEJB: Interfaz remota y Home
Interfaz Remota
Interfaz Home d
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
package com. wombat . benef i t s;i mpor t j avax. ej b. *;i mpor t j ava. r mi . Remot eExcept i on;i mpor t com. wombat . pl an. Pl an;publ i c i nt er f ace Selection ext ends EJBObject {
Sel ect i onCopy getCopy ( )t hr ows Remot eExcept i on, Sel ect i onExcept i on;
voi d updateFromCopy ( Sel ect i on copy)t hr ows Remot eExcept i on, Sel ect i onExcept i on;
}package com. wombat . benef i t s;
. . .publ i c i nt er f ace SelectionHome ext ends EJBHome {
Sel ect i on create ( Sel ect i onCopy copy)t hr ows Remot eExcept i on, Cr eat eExcept i on;
Sel ect i on findByPrimaryKey ( I nt eger empl Number )t hr ows Remot eExcept i on, Fi nder Except i on;
Sel ect i on findByEmployee ( Empl oyee empl oyee)t hr ows Remot eExcept i on, Fi nder Except i on;
Sel ect i on findByPlan ( Pl an pl an)t hr ows Remot eExcept i on, Fi nder Except i on;
}Fuente: Applying Enterprise JavaBeans:Component-Based Development for the J2EE Platform, Second EditionBy: Vlada Matena; Sanjeev Krishnan; Linda DeMichiel; Beth Stearns Publisher: Prentice Hall
-
8/12/2019 Jee Unidad3
72/104
P . 72
SelectionEJB: clases auxiliares
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
package com. wombat . benef i t s;. . .
publ i c i nt er f ace SelectionCopy ext ends SelectionCopy {
pr i vat e Empl oyee empl oyee;
pr i vat e i nt cover age;pr i vat e Pl an medi cal Pl an;pr i vat e bool ean smoker St at us;
publ i c Empl oyee getEmployee ( ) { . . . }publ i c i nt getCoverage ( ) { . . . }publ i c Pl an getMedicalPlan ( ) { . . . }publ i c bool ean getSmokerStatus ( ) { . . . }
publ i c voi d getEmployee ( Empl oyee e) { . . . }publ i c voi d getCoverage ( i nt i ) { . . . }
publ i c voi d getMedicalPlan ( Pl an p) { . . . }publ i c voi d getSmokerStatus ( bool ean s) { . . . }}
SelectionBean (I)
-
8/12/2019 Jee Unidad3
73/104
P . 73
SelectionBean (I)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs 73
package com. wombat . benef i t s;
i mpor t j avax. nami ng. *;i mpor t j ava. sql . * ;i mpor t j avax. sql . *;i mpor t j ava. ut i l . * ;i mpor t j avax. r mi . Por t abl eRemot eObj ect . *;
i mpor t com. wombat . pl an. *;
publ i c cl ass SelectionBean ext ends EntityBean {pr i vat e Ent i t yCont ext ent i t yCont ext ;pr i vat e Dat aSour ce ds;
/ / Mt odos cr eat epubl i c I nt eger ejbCreate ( Sel ect i onCopy copy)
t hr ows Sel ect i onExcept i on, Cr eat eExcept i on{
t r y {Connect i on con =get Connect i on( ) ;Pr epar edSt at ement pst mt =con. pr epar eSt at ement (
I NSERT I NTO Sel ect i ons + VALUES ( ?, ?, ?, ?) ) ;
pst mt . set I nt ( 1, empl oyeeNumber . i nt Val ue( ) ) ;pst mt . set I nt ( 2, cover age) ;pst mt . set St r i ng( 3, ( St r i ng) medi cal Pl an. get Pr i mar yKey( ) ) ;
SelectionBean (II)
-
8/12/2019 Jee Unidad3
74/104
P . 74
SelectionBean (II)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
pst mt . set St r i ng( 3, ( St r i ng) medi cal Pl an. get Pr i mar yKey( ) ) ;pst mt . set St r i ng( 4, smoker St at us ? Y: N) ;i f ( pst mt . execut eUpdat e( ) ==1{
con. cl ose( ) ;r et ur n empl oyeeNumber ;
}el se{con. cl ose( ) ;t hr ow new Cr eat eExcept i on( ) ;
}
}cat ch( SQLExcept i on ex) { t hr ow new EJ BExcept i on( ex) ;
}cat ch( Remot eExcept i on ex) { t hr ow new EJ BExcept i on( ex) ; } }publ i c I nt eger ejbFindByPrimaryKey ( I nt eger empl oyeeNumber )
t hr ows Fi nder Except i on {t r y {
Connect i on con = get Connect i on( ) ;Pr epar edSt at ement pst mt = con. pr epar eSt at ement (
SELECT sel _empl + FROM Sel ect i ons + WHERE sel _empl = ? ) ;
pst mt . set I nt ( 1, empl oyeeNumber . i nt Val ue( ) ) ;Resul t Set r s=pst mt . execut eQuer y( ) ;
SelectionBean (III)
-
8/12/2019 Jee Unidad3
75/104
P . 75
SelectionBean (III)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs 75
i f ( r s . next ( ) ) {con. cl ose( ) ;t hr ow new Obj ect Not FoundExcept i on( ) ;
}el se {con. cl ose( ) ;t hr ow new Obj ect Not FoundExcept i on( ) ;
}}cat ch ( SQLExcept i on ex) {t hr ow new EJ BExcept i on( ex) ; }
}
publ i c I nt eger ejbFindByPrimaryKey ( I nt eger empl oyeeNumber )
t hr ows Fi nder Except i on{t r y {Connect i on con =get Connect i on( ) ;Pr epar edSt at ement pst mt = con. pr epar eSt at ement (
SELECT sel _empl +
FROM Sel ect i ons + WHERE sel _empl =? ) ;
pst mt . set I nt ( 1, empl oyeeNumber . i nt Val ue( ) ) ;Resul t Set r s=pst mt . execut eQuer y( ) ;i f ( r s. next ( ) ) { con. cl ose( ) ; r et ur n empl oyeeNumber ;}el se{ con. cl ose( ) ; t hr ow new Obj ect Not FoundExcept i on( ) ; }
}cat ch( SQLExcept i on ex) {t hr ow new EJ BExcept i on( ex) ; }}
SelectionBean (IV)
-
8/12/2019 Jee Unidad3
76/104
P . 76
SelectionBean (IV)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
publ i c I nt eger ejbFindByEmployee ( Empl oyee empl oyee)t hr ows Fi nder Except i on{t r y {
r et ur n ej bFi ndByPr i mar yKey(( I nt eger ) empl oyee. get Pr i mar yKey( ) ) ;
}cat ch( j ava. r mi . Remot eExcept i on ex) {t hr ow new EJ BExcept i on( ex) ;
}}
publ i c Col l ect i on ejbFindByPlan ( Pl an pl an) {t r y {Pl anI nf o pl anI nf o = pl an. get Pl anI nf o( ) ;i nt pl anType = pl anI nf o. get Pl anType( ) ;St r i ng pl anI d = ( St r i ng) pl anI nf o. get Pl anI d( ) ;St r i ng col umnName = Pl anType. MEDI CAL;
Connect i on con = get Connect i on( ) ;Pr epar edSt at ement pst mt = con. pr epar eSt at ement (
SELECT sel _empl + FROM Sel ect i ons + WHERE +col umnName+ = ? ) ;
pst mt . set St r i ng( 1, pl anI d) ;Resul t Set r s=pst mt . execut eQuer y( ) ;
SelectionBean (V)
-
8/12/2019 Jee Unidad3
77/104
P . 77
Se ect o Bea (V)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs 77
Vect or vec = new Vect or ( ) ;whi l e ( r s . next ( ) ) {
i nt empl num=r s. get I nt ( 1) ;vec. add( new I nt eger ( empl num) ) ;
}con. cl ose( ) ;r et ur n vec;}cat ch( Except i on ex) {t hr ow new EJ BExcept i on ( ex) ; }
}/ / Mtodos de la interfaz EntityBeanpubl i c voi d setEntityContext ( Ent i t yCont ext ct x) {
r eadEnvi r onment ( ) ;t hi s . ct x=ct x; }
publ i c voi d ejbRemove ( ) {t r y {
Connect i on con = get Connect i on( ) ;
Pr epar edSt at ement pst mt = con. pr epar eSt at ement ( DELETE FROM Sel ect i ons + WHERE sel _empl = ? ) ;
pst mt . set I nt ( 1, empl oyeeNumber . i nvt Val ue( ) ) ;pst mt . execut eUpdat e( ) ;
con. cl ose( ) ;}cat ch( Except i on ex) {t hr ow new EJ BExcept i on( ex) ; }
}
SelectionBean (VI)
-
8/12/2019 Jee Unidad3
78/104
P . 78
SelectionBean (VI)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs 78
publ i c voi d ejbLoad ( ) {t r y {
St r i ng medi cal Pl anI d;empl oyeeNumber = ( I nt eger ) ent i t yCont ext . get Pr i mar yKey( ) ;empl oyee = empl oyeeHome. f i ndByPr i mar yKey( empl oyeeNumber ) ;
Connect i on con = get Connect i on( ) ;Pr epar edSt at ement pst mt = con. pr epar eSt at ement ( SELECT sel _cover age, sel _smoker , +
sel _medi cal _pl an + FROM Sel ect i ons +
WHERE sel _empl = ? ) ;pst mt . set I nt ( 1, empl oyeeNumber . i nt Val ue( ) ) ;Resul t Set r s = pst mt . execut eQuer y( ) ;i f ( r s . next ( ) ) {
cover age = r s. get I nt ( 1) ;
smoker St at us = r s. get St r i ng( 2) . equal s( Y) ;medi cal Pl anI d = r s. get St r i ng( 3) ;con. cl ose( ) ;
} el se {t hr ow new NoSuchEnt i t yExcept i on( ) ;
}medi cal Pl an =pl anHome. f i ndByPl anI d( medi cal Pl anI d) ;dent al Pl an = pl anHome. Fi ndbyPl anI d( dent al Pl anI d) ;
S l i B (VII)
-
8/12/2019 Jee Unidad3
79/104
P . 79
SelectionBean (VII)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
}cat ch ( Except i on ex) {t hr ow new EJ BExcept i on( ex) ; }}
publ i c voi d ejbStore ( ) {t r y {
Connect i on con =get Connect i on( ) ;Pr epar edSt at ement pst mt = con. pr epar eSt at ement ( UPDATE Sel ect i ons SET + sel _cover age = ?, + sel _medi cal _pl an = ?, +
sel _smoker = ? + WHERE sel _empl = ? ) ;pst mt . set I nt ( 1, cover age) ;pst mt . set St r i ng( 2, ( St r i ng) medi cal Pl an. get Pr i mar yKey( ) ) ;pst mt . set St r i ng( 2, smoker St at us ? Y : N) ;
pst mt . execut eUpdat e( ) ;con. cl ose( ) ;}cat ch( Except i on e) {t hr ow new EJ BExcept i on( ex) ; }
}
/ / Mt odos auxi l i ar es
S l i B (VIII)
-
8/12/2019 Jee Unidad3
80/104
P . 80
SelectionBean (VIII)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
/ / Mt odos auxi l i ar espr i vat e Connect i on getConnection ( ) {
t r y{ r et ur n ds. get Connect i on( ) ; }cat ch ( Except i on e){ t hr ow new EJ BExcept i on( ex) ; }
}pr i vat e readEnviroment ( ) {
t r y{ Cont ext i ct x = new I ni t i al Cont ext ( ) ;pl anHome = ( Pl anHome) Por t abl eRemot eObj ect . nar r ow(
i ct x. l ookup( j ava: comp/ env/ ej b/ Pl anEJ B ) ,Pl anHome. cl ass) ;
empl oyeeHome =( Empl oyeeHome)Por t abl eRemot eObj ect . nar r ow(i ct x. l ookup( j ava: comp/ env/ j dbc/ Empl oyeeDB ) ,Empl oyeeHome. cl ass;
benef i t sHome =( Empl oyeeHome)Por t abl eRemot eObj ect . nar r ow(i ct x. l ookup( j ava: comp/ env/ j dbc/ Benef i t sDB ) ,Benef i t sHome. cl ass) ;
}cat ch( Except i on ex) { t hr ow new EJ BExcept i on( ex) ; }}
S l i B (IX)
-
8/12/2019 Jee Unidad3
81/104
P . 81
SelectionBean (IX)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
/ / Var i abl es del est adopr i vat e i nt cover age;pr i vat e bool ean smoker St at us;pr i vat e Empl oyee empl oyee;pr i vat e Pl an medi cal Pl an;pr i vat e I nt eger empl oyeeNumber ;/ / Var i abl es i nt er nasbool ean checkPl anType;. . .
/ / Mt odos de negoci opubl i c Sel ect i onCopy getCopy ( ) {
Sel ect i onCopy copy = new Sel ect i onCopy( ) ;copy. set Empl oyee( empl oyee) ;copy. set Cover age( cover age) ;copy. set Medi cal Pl an( medi cal Pl an) ;copy. set Smoker St at us( smoker St at us) ;r et ur n copy; }
S l ti B (X)
-
8/12/2019 Jee Unidad3
82/104
P . 82
SelectionBean (X)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
publ i c voi d updateFromCopy ( Sel ect i onCopy copy)t hr ows Sel ect i onExcept i on{
t r y {updat eMedi cal Pl an( copy. get Medi cal Pl an( ) ) ;
updat eSmoker St at us( copy. get Smoker St at us( ) ) ;updat eCover age( copy. get Cover age( ) ) ;
}cat ch( Remot eExcept i on ex) { t hr ow new EJ BExcept i on( ex) ; }
}
publ i c voi d updateMedicalPlan ( Pl an p) {medi cal Pl an =p }publ i c voi d updateCoverage ( i nt v) { cover age=v; }
publ i c voi d updateSmokerStatus ( bool ean v) {smoker St at us=v; }
} //@SelectionBean
Partes del EnrollmentEJB Session
-
8/12/2019 Jee Unidad3
83/104
P . 83
Bean
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs 83
EmployeeInfo Summary Options EnrollmentException
Enrollment
EnrollmentHome
EnrollmentBean DBUpdateSelection
DBQuerySelection
DBInsertSlection
DBQueryEmployee
Employee
Selection
HealthPlan
Enrollment Remote Interface (mtodos de negocio)
-
8/12/2019 Jee Unidad3
84/104
P . 84
( g )
package com. st ar . benef i t s;i mpor t j avax. ej b. *;i mpor t j ava. r mi . Remot eExcept i on;publ i c i nt er f ace Enrollment ext ends javax.ejb.EJBObject {
Empl oyeeI nf o getEmployeeInfo ( )t hr ows Remot eExcept i on, Enr ol l ment eExcept i on;Opt i ons getCoverageOptions ( )t hr ows Remot eExcept i on, Enr ol l ment eExcept i on;voi d setCoverageOptions ( i nt choi ce)t hr ows Remot eExcept i on, Enr ol l ment eExcept i on;Opt i ons getMedicalOptions ( )t hr ows Remot eExcept i on, Enr ol l ment eExcept i on;voi d setMedicalOptions ( i nt choi ce)
t hr ows Remot eExcept i on, Enr ol l ment eExcept i on;bool ean getSmokerStatus ( )
t hr ows Remot eExcept i on, Enr ol l ment eExcept i on;voi d setSmokerStatus ( bool ean st at us)t hr ows Remot eExcept i on, Enr ol l ment eExcept i on;Summar y getSummary ( )t hr ows Remot eExcept i on, Enr ol l ment eExcept i on;voi d commitSelections ( bool ean st at us)t hr ows Remot eExcept i on, Enr ol l ment eExcept i on;
}//Enrollment remote interface
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs 84
EnrollmentHome Home Interface (mtodos de vida)
-
8/12/2019 Jee Unidad3
85/104
P . 85
( )
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
package com. st ar . benef i t s;i mpor t j avax. ej b. *;i mpor t j ava. r mi . Remot eExcept i on;publ i c i nt er f ace EnrollmentHome ext ends javax.ejb.EJBHome {
Enr ol l ment create ( i nt empl num)t hr ows Remot eExcept i on, Cr eat eExcept i onEnr ol l ment eExcept i on;
}/ / Enr ol l ment Home r emot e i nt er f ace
Detalles de las clases auxiliares (Home y Bean)
-
8/12/2019 Jee Unidad3
86/104
P . 86
( y )
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
package com. st ar . benef i t s;publ i c cl ass EmployeeInfo i mpl ement s java.io.Serializable {
i nt empl oyeeNumber ;
St r i ng f i r st Name;St r i ng l ast Namepubl i c EmployeeInfo ( ) {}publ i c EmployeeInfo ( i nt empl num, St r i ng f name, St r i ng l name) {
empl oyeeNumber =empl num; f i r st Name=f name; l ast name=l name; }
publ i c i nt getEmployeeNumber ( ) {r et ur n empl oyeeNumber ; }publ i c St r i ng getFirstName ( ) {r et ur n f i r st Name; }publ i c i nt getLastName ( ) {r et ur n Last Namer ; }publ i c voi d setEmployeeNumber ( i nt val ) {empl oyeeNumber =val ; }publ i c voi d setFirstName ( St r i ng val ) {f i r st Name=val ; }publ i c voi d setLastName ( St r i ng val ) {l ast Name=val ; }
} //Employee Helper class
EmployeeInfo Summary Options EnrollmentException
Esqueleto de la clase
-
8/12/2019 Jee Unidad3
87/104
P . 87
qEnrollmentBeanpackage com. st ar . benef i t s;publ i c cl ass EnrollmentBean i mpl ement s javax.ejb.SessionBean {
publ i c Enr ol l ment Bean( ) {super ( ) ; }//Implementacin de los business methodspubl i c Empl oyeeI nf o getEmployeeInfo ( ) {. . . }publ i c Opt i ons getCoverageOptions ( ) {. . . }publ i c voi d setCoverageOptions ( i nt choi ce) {. . . }
publ i c Opt i ons getMedicalOptions ( ) {. . . }publ i c voi d setMedicalOptions ( i nt choi ce) {. . . }publ i c bool ean getSmokerStatus ( ) {. . . }publ i c voi d setSmokerStatus ( bool ean st at us) {. . . }publ i c Summar y getSummary ( ) {. . . }publ i c voi d commitSelections ( ) {. . . }
//Implementacin de los mtodos create()publ i c Empl oyeeI nf o ejbCreate ( i nt empl Num) {. . . }//Implementacin de los javax.ejb.SessionBeanpubl i c Empl oyeeI nf o ejbRemove ( ) {. . . }publ i c Empl oyeeI nf o ejbPassivate ( ) {. . . }publ i c Empl oyeeI nf o ejbActivate ( ) {. . . }publ i c Empl oyeeI nf o setSessionContext ( Sess i onCont ext sc) {. . . }//Mtodos auxiliarespr i vat e voi d calculateCostAndDeduction ( ) {. . . }pr i vat e voi d getDataSources ( ) {. . . }} //Clase EnrollmentBean
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs 87
Detalles de la clase
-
8/12/2019 Jee Unidad3
88/104
P . 88
EnrollmentBean (I)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs 88
package com. st ar . benef i t s;i mpor t j avax. ej b;i mpor t j avax. nami ng. Cont ext ;i mpor t j avax. nami ng. I ni t i al Cont ext ;
i mpor t com. st ar t . payr ol l . Payr ol l ;i mpor t com. st ar t . payr ol l . Payr ol l Home;i mpor t j ava. ut i l . Dat e;i mpor t j ava. sql . SQLExcept i on;i mpor t j ava. sql . Dat aSour ce;i mpor t j avax. r mi . Por t abl eRemot eObj ect ;
i mpor t com. st ar . beni f i t s. db. DBQuer yEmpl oyee;i mpor t com. st ar . beni f i t s. db. DBQuer ySel ect i on;i mpor t com. st ar . beni f i t s. db. DBI nser t Sel ect i on;i mpor t com. st ar . beni f i t s. db. DBUpdat eSel ect i on;//Representa la informacin del empleado
cl ass Employee {i nt empl Number ;St r i ng f i r st Name;St r i ng l ast Name;Dat e bi r t hDat e;Dat e st ar t Dat e;}
Detalles de la clase
-
8/12/2019 Jee Unidad3
89/104
P . 89
EnrollmentBean (II) Aqu iran los mtodos de negocio.
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
//Representa la seleccin
cl ass Selection {i nt empl Number ;i nt cover age;St r i ng medi cal pl an;
bool ean smoker St at us;}//La clase EnrollmentBeanpubl i c cl ass EnroollmentBean i mpl ement s Sess i onBean {
pr i vat e f i nal st at i c St r i ng[ ] cover ageDescr i pt i ons = {
empl oyee onl y,empl oyee and espouse,empl oyee, spouse and chi l dr en };
//tablas internas al EJBpr i vat e Heal t hPl an[ ] medi cal Pl ans;pr i vat e doubl e empl oyeeCost Fact or =0. 10;pr i vat e i nt empl oyeeNumber ;pr i vat e Sel ect i on sel ect i on;pr i vat e bool ean cr eat eSel ect i on;pr i vat e i nt age; //Variable auxiliarespr i vat e i nt medi cal sel ect i on =- 1;pr i vat e doubl e t ot al Cost ;pr i vat e doubl e payr ol l Deduct i onpr i vat e Dat aSour ce empl oyeeDS; //JDBC data structurespr i vat e Dat aSour ce benef i t sDS;
Detalles de la claseE ll B (III)
-
8/12/2019 Jee Unidad3
90/104
P . 90
EnrollmentBean (III)
Aqu iran los mtodos de negocio.
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
pr i vat e Payr ol l payr ol l ;//public no-arg constructor publ i c EnrollmentBean ( ) { }//Business methods follow.
//Get employee information.publ i c Empl oyeeI nf o getEmployeeInfo ( ) {
r et ur n new Empl oyeeI nf o( empl oyeeNumber ,empl oyee. f i r st Name, empl oyee. l ast Name) ;
}//Get Coverage options.publ i c Opt i ons getCoverageOptions ( ) {Opt i ons opt = new Opt i ons( cover ageDescr i pt i ons. l engt h) ;
opt . set Opt i onDescr i pt i on( cover ageDescr i pt i ons) ;opt . set Sel ect edOpt i on( sel ect i on. cover age) ;r et ur n opt ; }
//Set selected coverage option.publ i c voi d setCoverageOption ( i nt choi ce)
t hr ows Enr ol l ment Except i on{i f ( choi ce >=0 && choi ce
-
8/12/2019 Jee Unidad3
91/104
P . 91Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
EnrollmentBean (IV)//Get lists of available medical optionspubl i c Opt i ons getMedicalOptions ( ) {
Opt i ons opt =new Opt i ons( medi cal Pl ans. l engt h) ;f or ( i nt i =0; i < medi cal Pl ans. l engt h; i ++) {
Heal t hPl an pl an = medi cal Pl ans[ i ] ;opt . set Opt i onDescr i pt i on( i , pl an. get Descr i pt i on( ) ) ;opt . set Opt i onCost ( i ,
pl an. get Cost ( sel ect i on. cover age, age,sel ect i on. smoker St at us) ) ;
}
opt . set Sel ect edOpt i on( medi cal Sel ect i on) ;r et ur n opt ;
}//Set selected medical option.publ i c voi d setMedicalOption ( i nt choi ce)
t hr ows Enr ol l ment Except i on{i f ( choi ce >=0 && choi ce
-
8/12/2019 Jee Unidad3
92/104
Detalles de la claseEnrollmentBean (VI)
-
8/12/2019 Jee Unidad3
93/104
P . 93Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
EnrollmentBean (VI)//Update corporate databases with the new selections.publ i c voi d commitSelections ( ) {
i f ( cr eat eSel ect i on) {DBI nser t Sel ect i on cmd1 = nul l ;t r y {
cmd1=new DBI nser t Sel ect i on( benef i t sDS) ;
cmd1. set Empl Number ( empl oyeeNumber ) ;cmd1. set Cover age( sel ect i on. cover age) ;cmd1. set Medi cal Pl anI d( sel ect i on. medi cal Pl anI d) ;cmd1. set Smoker St at us( sel ect i on. smoker St at us) ;cmd1. execut e( ) ;cr eat eSel ect i on =f al se; }cat ch ( SQLExcept i on ex) {
t hr ow new EJ BExcept i on( ex) ; } f i nal l y{ i f ( cmd1 ! =nul l ) cmd1. r el ease( ) ; }
} el se {DBUpdat eSel ect i on cmd2 =nul l ;t r y {
cmd2 =new DBUpdat eSel ect i on( benef i t sDS) ;cmd2. set Empl Number ( empl oyeeNumber ) ;cmd2. set Cover age( sel ect i on. cover age) ;cmd2. set Medi cal Pl anI D( sel ect i on. medi cal Pl anI D) ;cmd2. set Smoker St at us( sel ect i on. smoker St at us) ;cmd2. execut e( ) ; }cat ch( SQLExcept i on ex) {
t hr ow new EJ BExcept i on( ex) ; } f i nal l y{i f ( cmd2 ! =nul l ) cmd. r el ease( ) ; }
}
Detalles de la clasell ( )
-
8/12/2019 Jee Unidad3
94/104
P . 94Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
EnrollmentBean (VII)//Update information in the payroll systemt r y {
payr ol l . set Benef i t sDeduct i on( empl oyeeNumber ,payr ol l Deduct i on) ;
}cat ch( Except i on ex) {t hr ow new EJ BExcept i on( ex) ;}
} /@commitSelections//Life methods (create, ejbRemove, ejbPasivate and activate)publ i c voi d ejbCreate ( i nt empl Num) t hr ows
Enr ol l ment Except i on{empl oyeeNumber = empl Num;/ / Obt ai ni ng t he envi r onment ent r i esr eadEnvi r oment Ent r i es( ) ;/ / Obt ai n J DBC dat a sour ces f r om t he envi r onment
get Dat aSour ces( ) ;/ / Read empl oyee i nf omr at i on.DBQuer yEmpl oyee cmd1=nul l ;t r y {
cmd1 =new DBQuer yEmpl oyee( empl oyeeDS) ;cmd1. set Empl oyeeNumber ( empl Num) ;cmd1. execut e( ) ;i f ( cmd1. next ( ) ) {
empl oyee =new Empl oyee( ) ;
Detalles de la claseEnrollmentBean (VIII)
-
8/12/2019 Jee Unidad3
95/104
P . 95Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
EnrollmentBean (VIII)empl oyee. empl Number =empl Num;empl oyee. f i r st Name = cmd1. get Fi r st Name( ) ;empl oyee. l ast Name =cmd1. get Last Name( ) ;empl oyee. st ar t Dat e = cmd1. get St ar t Dat e( ) ;empl oyee. bi r t hDat e = cmd1. get Bi r t hDat e( ) ;
} el se {t hr ow new Enr ol l ment Except i on
( no empl oyee r ecor d) ;}
}cat ch ( SQLExcept i on ex) {t hr ow new EJ BExcept i on( ex) ;
}f i nal l y{i f ( cmd1 ! =nul l ) cmd1. r el ease( ) ;}
//Read the previous benefits selectionDBQuer ySel ect i on cmd2=nul l ;
t r y {cmd2 = new DBQuer ySel ect i on( benef i t sDS) ;cmd2. set Empl oyeeNumber ( empl Num) ;cmd2. execut e( ) ;i f ( cmd2. next ( ) ) {
sel ect i on = new Sel ect i on( ) ;sel ect i on. empl Number = empl Num;sel ect i on. cover age= cmd2. get Cover age( ) ;sel ect i on. medi cal Pl anI D = cmd2. get Medi cal Pl anI d( ) ;
Detalles de la clase EnrollmentBean (IX)
-
8/12/2019 Jee Unidad3
96/104
P . 96
( )
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs 96
sel ect i on. smoker St at us= cmd2. get Smoker St at us( ) ;cr eat eSel ect i on = f al se;
}el se{//No previous selectionsel ect i on=new Sel ect i on( ) ;sel ect i on. empl Number = empl Num;sel ect i on. cover age=0;
sel ect i on. medi cal Pl anI D = medi cal Pl ans[ 0] . get Pl anI d( ) ;sel ect i on. smoker St at us =f al se;cr eat eSel ect i on = t r ue;
}}cat ch ( SQLExcept i on ex) {
t hr ow new EJ BExcept i on( ex) ;} f i nal l y {
i f ( cmd2 ! =nul l ) cmd2. r el ease( ) ; }//Calculate employees age.
j ava. ut i l . Dat e t oday = new j ava. ut i l . Dat e( ) ;age = ( i nt ( ( t oday. get Ti me( ) - empl oyee. bi r t hDat e. get Ti me( ) ) /
( ( l ong) 365*24*60*60*1000) ) ;//Translate the dical plan ID to an indexf or ( i nt i =0; i
-
8/12/2019 Jee Unidad3
97/104
P . 97
EnrollmentBean (X)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
//Clean up any resource held by the instancepubl i c voi d ejbRemove ( ) {
t r y {payr ol l . r emove( ) ;
}cat ch( Except i on ex) {}}//Release state that cannot be preserved across passivationpubl i c voi d ejbPassivate ( ) {
empl oyeeDS =nul l ;benef i t sDS =nul l ;
}//Reacquire state released before passivation
publ i c voi d ejbActivate ( ) {get Dat aSour ces( ) ;}//Session contextpubl i c voi d setSessionContext ( Sessi onCont ext sc) {}
Detalles de la claseE ll B (XI)
-
8/12/2019 Jee Unidad3
98/104
P . 98
EnrollmentBean (XI)
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
//Helper methods follow.
//Calculate total benefits cost and payroll deduction.pr i vat e voi d calculateTotalCostAndPayrollDeductions ( ) {
doubl e medi cal Cost =
medi cal Pl ans[ medi cal Sel ect i on] . get Cost (sel ect i on. cover age, age, sel ect i on. smoker St at us) ;t ot al Cost =medi cal Cost ;payr ol l Deduct i on=t ot al Cost *empl oyeeCost Fact or ;}
//Read and process enterprise beans environment entries.pr i vat e voi d readEnvironmentEntries ( ) {t r y {
Cont ext i ct x = new I ni t i al Cont ext ( ) ;St r i ng medi cal Pl anLi st = ( St r i ng)
i ct x. l ookup( j ava: comp/ env/ medi cal Pl ans) ;St r i ng[ ] medi cal Pl anCl assNames = par seCl assNames(
medi cal Pl anLi st ) ;medi cal Pl ans = new Heal t hPl an[ medi cal Pl anCl assNames. l engt h] ;f or ( i nt i =0; i
-
8/12/2019 Jee Unidad3
99/104
Detalles de la clase EnrollmentBean (XIII)
//Parse: separated class names
-
8/12/2019 Jee Unidad3
100/104
P . 100Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
//Parse: separated class names.pr i vat e st at i c St r i ng[ ] parseClassNames ( St r i ng l i st ) {
St r i ng[ ] r v = new St r i ng[ 0] ;whi l e ( l i s t . l engt h( ) ! =0) {i nt x = l i st . i ndexOf ( : ) ;St r i ng name;i f ( x
-
8/12/2019 Jee Unidad3
101/104
DBQueryEmployee Command Bean
-
8/12/2019 Jee Unidad3
102/104
P . 102
package com. st ar . benef i t s. db;
i mpor t j ava. sql . SQLExcept i on;i mpor t j ava. ut i l . Dat e;i mpor t j ava. sql . Dat aSour ce;publ i c cl ass DBQueryEmployee ext ends DBQueryBean {
st at i c St r i ng statement =SELECT empl _f i r st _name, empl _l ast _name, empl _bi r t h_dat e
+empl _st ar t _dat e, empl _dept _i d +FROM empl oyees WHERE empl _i d = ? ;publ i c DBEmployee ( Dat aSour ce ds) t hr ows SQLExcept i on{
super ( ds , s t at ement ) ; }publ i c voi d setEmployeeNumber ( i nt empl Num) t hr owsSQLExcept i on{ pst mt . set I nt ( 1, empl Num) ; }publ i c St r i ng getFirstName ( ) t hr ows SQLExcept i on{r et ur n r esul t Set . get St r i ng( 1) ; }publ i c St r i ng getLastNameName ( ) t hr ows SQLExcept i on{
r et ur n r esul t Set . get St r i ng( 2) ; }publ i c St r i ng getBirthDate ( ) t hr ows SQLExcept i on{
r et ur n r esul t Set . get St r i ng( 3) ; }publ i c St r i ng getStartDate ( ) t hr ows SQLExcept i on{r et ur n r esul t Set . get St r i ng( 4) ; }publ i c St r i ng getDepartmentNumber ( ) t hr ows SQLExcept i on{
r et ur n r esul t Set . get St r i ng( 5) ; }}
Software de Comunicaciones I.T.T.T. - Programacin Entity y Session EJBs
-
8/12/2019 Jee Unidad3
103/104
Deployment descriptor: statefull o stateless
-
8/12/2019 Jee Unidad3
104/104
. . .
Enr ol l ment e BeanEnr ol l ment EJ Bcom. st ar t . benef i t s. Enr ol l ment Homecom. st ar t . benef i t s. Enr ol l ment St at ef ul l
. . .
Payr ol l BeanPayr ol l EJ Bcom. st ar t . benef i t s. Payr ol l Home
com. st ar t . benef i t s. Payr ol l St at el ess