Your SlideShare is downloading. ×
Java EE EJB Applications
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Java EE EJB Applications

1,168
views

Published on

This slide covers building EJB applications. Presented by DevelopIntelligence the leader in customized developer training.

This slide covers building EJB applications. Presented by DevelopIntelligence the leader in customized developer training.

Published in: Technology, Education

0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,168
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
134
Comments
0
Likes
5
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • A community-defined extension to the Java SE platformSeparate controlling specificationDefined in context of extending Java SE to enterpriseAn enterprise information systems platformEnables the development of Java-based middle-tier applications requiring “ility” characteristicsExtends Write-Once-Run-Anywhere (WORA) to middlewareA standard architecture definingAn application programming modelAn application execution platform
  • Java EE was not an “intent” of the original Java design It was more of a side-effect of the Java-web mergerClient-side web-based Java lost its luster and positioning to things like FlashThings like WORA, threading, networking, and security were desirable characteristics on the server-sideBut, Java didn’t have a formal server-side “platform”Java EE was more “evolutionary” than revolutionaryInitially addressed web-applicationsQuickly enhanced to address “middleware”Further enhanced to support Web services and SOA
  • Provide an easy to use framework to build middle-ware applications that:Enables developers to focus on business logic instead of “integration” logicCreates middleware server transparencyRemoves complexities of large-scale distributed applicationsProvide a managed execution environment that:Addresses “ility” characteristicsAllows secure and protected side-by-side deploymentsOffers common “services”
  • Programming model adopts a “managed” modelDesign and implementationLifecycleTransactions and securityDeploymentApplication implementation adheres to modelBuilt around abstracted interactions with Java EE execution environment Interactions provided through Java EE platform APIs
  • A major design motivation within Java EE is WORAGoal is to extend WORA into middlewareSpecifically at the Web and EJB container levelsThere are two ways to create WORA:Define an application programming model and its supporting technologiesDefine a set of services to support the programming modelJava EE defines the supporting services as “Standard Services”Standard Services address everything from HTTP to database interactionsA fully compliant Java EE server must support all Standard Services
  • Components enable application developmentBuilt using Java SE and Java EE technologiesComponents may be “homegrown” or third-partyComponents are grouped together as modulesModules represent basic unit of a Java EE applicationOne or more component per moduleModules consist of same “component type”Modules are described by deployment descriptorsModules and deployment descriptors packaged together as deployment units
  • Java EE application development process requires broad range of competenciesJava development skillsSource control / configuration skillsSystem administration skillsTo simplify “jack of all trades” skill requirement, Java EE specification defines set of Platform RolesNot all platform roles are realized within a software development organization
  • Prior to EJB specification, reusable middleware was hard to createVendors had own modelsMany different distributed programming technologiesNot a lot of portabilityEJB specification borrowed many concepts defined by servlets and adapted them to address middle tierPackagingLifecycle managementEtc.
  • Three primary types:Bean Managed Persistence (BMP) – good for complex schemas; but required good knowledge of SQLContainer Managed Persistence (CMP) – good for straightforward schemas; not SQL knowledge requiredJPA Entities – replaces CMPJPA also includes a “bean query language”
  • * - not applied to a “bean class”
  • * - in EJB3.1 you can create interface-less EJBs using the LocalBean annotation
  • Each EJB is defined by:Home interface*Aides in lifecycle management (create)Used to find and instanceBusiness interfaceDefines behaviors of beansCan be a local or remoteImplementationRealization of the business interfaceMight contain references to other beans
  • Each EJB is defined by:Home interface*Aides in lifecycle management (create)Used to find and instanceBusiness interfaceDefines behaviors of beansCan be a local or remoteImplementationRealization of the business interfaceMight contain references to other beans
  • XML based Functions as the deployment descriptorDefines things like:ejb-nameDescriptionLocal/remote business interface classesImplementation classServer-specific meta-data * Ties generic EJB to specific serverDefines things like:ejb-name
  • EJBs have their own deployment modelFollows standard Java JAR structureIncludes:META-INFMANIFEST.MFPossibly contains ejb-jar.xml and server-specific xml filePossibly contains persistence.xmlClassesEach deployment executes in its own contextThis can cause undue overheadConsider deploying multiple EJBs within a single deployment
  • Finding an EJB with JNDI uses four key conceptsContextImplemented as javax.naming.ContextDescribes the environment (directory and server) you’re working withinInitial ContextImplemented as javax.naming.InitialContextVendor specific implementation to interface with JNDI implementationPoints to “root node” used when traversing or searching JNDIPath & NameDescribes location and name of resourceUsually follows context_name:path/resource-name structureSearchAlso known as lookupLooking up specific resource in JNDI
  • Finally, an application server might use JNDI to access a directory service, such as a Lightweight Directory Access Protocol (LDAP) service, to authenticate users or look up user groups.
  • * - the values of these paths varied in EJB 3.0. In EJB 3.1, the specification defines a global JNDI naming convention to create consistency.
  • A message contains:Header fields: priority, timestamp, etc.Optional message body, like:Free-format textXMLSerialized objectOptional properties, like: application specific dataExamples: accountID, dueDate
  • If a session is configured with AUTO_ACKNOWLEDGE, the session automatically acknowledges a client’s receipt of a message. This acknowledgement occurs either when the client has successfully returned from a call to receive or when the MessageListener returns successfully.If a session is configured with CLIENT_ACKNOWLEDGE, the client acknowledges a message by calling the message’s acknowledge method.If a session is configured with DUPS_OK_ACKNOWLEDGE, the client can lazily acknowledge the delivery of messages. This mode should be used only by consumers that can tolerate duplicate messages.
  • Message Selection@MessageDriven(activationConfig={ @ActivationConfigProperty(propertyName=”messageSelector”, propertyValue=“JMSType = ‘car’ AND color = ‘blue’ and weight >2500”)})
  • @MessageDriven(name = "HelloWorldQueueMDB", activationConfig = { @ActivationConfigProperty( propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty( propertyName = "destination", propertyValue = "HelloWorldQueue")})
  • The JMSDestination and JMSReplyTo headers cannot be used as identifiers because their corresponding values are Destination objects whose underlying value is proprietary and therefore undefined.
  • javax.ejb.LockType.READ and javax.ejb.LockType.WRITE.
  • Attributes are defined in TransactionAttribute class
  • Attributes are defined in TransactionAttribute class
  • Transcript

    • 1. Java EE EJB Applications Building EJB Applications
    • 2. Presentation Topics In this presentation, we will discuss: Building the Enterprise History of EJB Development EJB Development Concepts Session Beans Message Driven Beans Persistent Entities Interceptors Timer Service Transactions Security 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 2
    • 3. Objectives When we are done, you should be able to: Explain benefits of EJB3 over EJB 2 Understand Java EE‘s layered architecture and the functions provided in its layers Describe three kinds of enterprise beans and their uses Explain pros and cons of stateful vs. stateless session beans Compare the development process under Java EE 5 versus J2EE 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 3
    • 4. Building the Enterprise The Tools of Java Enterprise Edition
    • 5. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Presentation Topics In this section, we will discuss: Overview of Java EE Java EE Platform Java EE Development 5
    • 6. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Objectives When we are done, you should be able to: Describe how Java EE and Java SE fit together List 3 technologies found in Java EE Describe the basic development lifecycle for a Java EE application 6
    • 7. Overview of Java EE A High-level Overview
    • 8. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com What is Java EE? A community-defined extension to the Java SE platform An enterprise information systems platform A standard architecture defining An application programming model An application execution platform 8
    • 9. History of Java EE Java EE was not an ―intent‖ of the original Java design Java EE was more ―evolutionary‖ than revolutionary 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 9
    • 10. Motivations for Java EE Provide an easy to use framework to build middle-ware applications Provide a managed execution environment 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 10
    • 11. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Industry Support Originally, Java EE was developed and maintained by Sun Today, Java EE is governed by the Java Community Process (JCP) Current focus of Java EE community is simplification Latest release is Java EE 6 (12/2009) 11
    • 12. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Application Programming Model Programming model adopts a ―managed‖ model Design and implementation Lifecycle Transactions and security Deployment Application implementation adheres to model Built around abstracted interactions with Java EE execution environment Interactions provided through Java EE platform APIs 12
    • 13. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Application Execution Platform Provides a ―managed‖ execution environment Java EE compliant applications Execution environment is a realized implementation of the Java EE APIs Relies on the Java SE platform 13
    • 14. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Java EE Platform Diagram Java SE Platform Solaris Linux Windows Mac OS X Java EE API Implementations Java EE APIs App Java EE Application Server App App App 14
    • 15. Java EE Platform An Application Development Perspective
    • 16. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Java EE Platform Java EE Platform supports three primary application types Web applications EJB applications Enterprise applications Each application type has its own set of characteristics Applications execute in ―domain‖ relevant containers 16
    • 17. Java EE Containers Java EE defines two primary types of containers: Web containers - managed environment for web applications EJB containers - managed environment for EJB applications A certified Java EE application server must provide an implementation for both types of containers 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 17
    • 18. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Java EE Technologies Enterprise Container Boundary 18
    • 19. Java EE Server Technologies WORA is a design motivation to justify use of Java EE There are two ways to create WORA: 1. Define an application programming model and its supporting technologies 2. Define a set of services to support the programming model Java EE defines the supporting services as ―Standard Services‖ 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 19
    • 20. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Java EE Standard Services Communication Email XML Processing Transactions Messaging Management Database Naming and Directory Security Web Services Legacy systems Deployment 20
    • 21. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Container Technologies Remaining technologies defined in Java EE specification address application development Technologies are associated with an application- centric container Relatively clean separation of technologies between container types Technology sharing is at the Standard Services level Technologies may exist as ―standard‖ implementations or vendor implementations 21
    • 22. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Web Container Technologies Web containers provide ―robust‖ web application environments A web container supports the following technologies: Servlets Filters Java Server Pages (JSP) JSP Standard Tag Library (JSTL) Java Server Faces (JSF) 22
    • 23. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com EJB Container Technologies EJB containers provide state, workflow, and persistent application environments An EJB container supports the following technologies: Session Beans (SB) Entity Beans (EB)* Message Driven Beans (MDB) 23 * Deprecated in EJB3.x
    • 24. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Java EE Application Diagram JSP Servlet JSF JSTL SB MDB EB WSI Standard Services Java SE Platform Web Container & Technologies EJB Container & Technologies Enterprise Container Java EE Platform 24
    • 25. Java EE Development
    • 26. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Java EE Applications Built using components, modules, and deployment units The Java EE application structure provides: Functional encapsulation Reusability Simplified configuration Transportability Modular-oriented development encourages Good Object oriented design Separation of functional concern Separation of development concern Has been considered the ―struggle‖ of Java EE 26
    • 27. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Components and Modules Components enable application development Modules represent basic unit of a Java EE application 27
    • 28. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Deployment Units Java EE applications may consist of A Single deployment unit Multiple deployment units packaged together as a single deployment unit Deployment units are the standard way to package and deploy Java EE applications Java EE defines three deployment units: Web Application Archive (WAR) Java Archive (JAR) Enterprise Application Archive (EAR) 28
    • 29. WAR – Web Module 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 29
    • 30. EJB JAR – EJB Module 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 30
    • 31. EAR 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 31
    • 32. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Java EE Development Process Creation Assembly Deployment 32
    • 33. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Java EE Development Roles Java EE application development process requires broad range of competencies To simplify ―jack of all trades‖ skill requirement, Java EE specification defines set of Platform Roles Not all platform roles are realized within a software development organization 33
    • 34. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Java EE Platform Roles Java EE Product Provider Application component provider Application assembler Deployer System Administrator Tool Provider System Component Provider 34 :: QUESTION :: Which of these roles exist within your organization?
    • 35. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Summary Java EE platform defines an application programming model and an execution environment Java EE platform enables WORA in middleware Java EE is comprised of Standard Services, Web Technologies, and EJB Technologies Java EE uses a deployment unit strategy for application packaging and deployment 35
    • 36. Resources Web Java EE Tutorial http://docs.oracle.com/javaee/6/tutorial/doc/ Java EE Specification http://jcp.org/aboutJava/communityprocess/pfd/jsr244/ Books ―Head First Servlets and JSP‖ : ISBN 0596005407 ―Head First EJB‖ : ISBN 0596005717 ―EJB3 in Action‖ : ISBN 1933988347 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 36
    • 37. History of EJB
    • 38. Objectives When we are done, you should be able to: Explain benefits of EJB 3 over EJB 2 Understand Java EE‘s layered architecture and the functions provided in its layers Describe three kinds of enterprise beans and their uses Explain pros and cons of stateful vs. stateless session beans Compare the development process under Java EE 5 versus J2EE 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 38
    • 39. Motivations for EJB Prior to EJB specification, reusable middleware was hard to create EJB specification borrowed many concepts defined by servlets and adapted them to address middle tier 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 39
    • 40. What is EJB? An Enterprise Java Bean is: A reusable component A Java object An encapsulation of enterprise business logic and data Executed in a Containers EJB Containers provide: Pooling Transaction Management Security Naming and Directory Configuration Etc. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 40
    • 41. History of EJB Four major releases of EJB specification EJB 1.0 - all Java based; cumbersome EJB 2.0 - Java based + xml; tedious EJB 2.1 - Java based + xml; slightly easier EJB 3.0 - Java based + xml + annotations; easier EJB 3.1 – Java based + xml + annotations; easiest Most applications ―legacy‖ EJB applications are built using EJB 2.X specification 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 41
    • 42. EJB 2.X Strengths More capabilities than EJB 1.0 spec Clean separation of business services Persistence supports usable object/relational mapping Message oriented middleware capabilities Performance improvements 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 42
    • 43. EJB 2.X Weaknesses Cumbersome programming model Complex deployment model Mediocre object/relational mapping 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 43
    • 44. EJB 3.x Strengths Simplified programming model Simplified deployment model More robust persistence structure 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 44
    • 45. EJB 3.x Weaknesses Yet another new programming model Aspect Oriented Programming and dependency injection not as robust as other frameworks Limited vendor support 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 45
    • 46. New Features in EJB3.0 Annotations instead of Deployment Descriptors Callback Methods and Listeners Interceptors Dependency Injection 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 46
    • 47. New Features of EJB3.1 Simplified EJB development – no interfaces Singleton Session Beans Enhanced Timer Service Application Profiles 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 47
    • 48. EJBs within Java EE 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Java client .NET client Desktop HTML client Java client Browse r Delphi client .NET client Server Client Tier Web Container JSP Servlet JSF WS JSTL CTL Beans POJO Beans POJO EJB Container EJB EJB EJB EJB JMS JCA JNDI JDBC DB Message System Directory Server Custom System EIS Tier 48
    • 49. Summary EJB3.x simplifies the development model There are three kinds of EJBs Session Beans Message Driven Beans ―Entity‖ Beans 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 49
    • 50. EJB Development Concepts
    • 51. Presentation Topics In this section, we will discuss: Type of Enterprise Java Beans EJB Client Access Modes EJB Instance Management EJB Development Elements 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 51
    • 52. Objectives When we are done, you should be able to: Describe the three types of EJBs Identify the three types of client access Understand the elements involved in building an EJB 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 52
    • 53. Types of Enterprise Java Beans
    • 54. Enterprise Java Beans Designed to provide: Database abstraction Reusable business logic components Workflow components Transportable implementation Exists as APIs in javax.ejb 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 54
    • 55. Types of Enterprise Java Beans Three main categories Business logic – javax.ejb.SessionBean Workflow logic – javax.ejb.MessageDrivenBean Persistence logic - JPA Entity Classifications specified with through: Interface – 2.x style Annotations – 3.x style 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 55
    • 56. Session Beans Reusable business logic components Can be used to manage state across client interactions Three types Stateless (SLSB) Stateful (SFSB) Singleton (SSB) [3.1 or higher]* 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 56 * Similar to Jboss@Service
    • 57. Message Driven Beans [MDB] Reusable workflow logic components Rely on Java Messaging System Support transactions Similar to Stateless Session Beans MDBs have no client-oriented state No distinction across client or bean Different from Stateless Session Beans No direct client access Asynchronous interactions 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 57
    • 58. Entity Beans Persistence model for EJB Focused on automatic persistence through object model Three primary types: Bean Managed Persistence (BMP) Container Managed Persistence (CMP) JPA Entities [EE 5 and higher] 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 58
    • 59. Category-Related Annotations Bean Type Annotation Session Bean @Stateless @Stateful @Singleton* Message Driven @MessageDriven JPA Entities @Entity** @EntityManager** 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 59 * EJB3.1 ** Part of JPA (javax.persistence)
    • 60. EJB Client Access Modes
    • 61. Types of EJB Access Modes Three client access modes: Local client-access Remote client-access Web service client-access Client-access modes specified by Interface – 2.x style Annotations – 3.x style 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 61
    • 62. EJB Classifications [cont.] Local beans are accessible Only by other EJBs in the same context (module) All categories of beans can be local Remote beans are accessible By EJBs in the same context and outside the context (modules) By other ―objects‖ outside of the container Only Session Beans can be remote Web Service end-points Translate SB and MDBs into web-services Container manages WSDL/SOAP mappings REST/JAXB mappings 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 62
    • 63. Access Mode Annotations Bean Type Annotation Session Bean @Local @Remote @LocalBean* @WebService @Path* Message Driven @WebService JPA Entities N/A 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 63 * EJB3.1
    • 64. EJB Instance Management
    • 65. EJB Management Modes Two management modes: Container-managed Bean-managed Management-modes specified by Annotations 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 65
    • 66. EJB Classifications In container-managed, container manages: Transactions Roles Security Persistence and Entities (PersistenceContext) In bean-managed, bean manages: Transactions Persistence 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 66
    • 67. Management Mode Annotations Bean Type Annotation Transactions @TransactionManagement(CONTAINER) @TransactionManagement(BEAN) Security @RunAs() @RolesAllowed 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 67
    • 68. EJB Access EJB Instance access is controlled by container There is no direct client access 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com ―proxy‖ EJB Client Container 68
    • 69. EJB Instantiation Instantiation of EJB is handled by container Container determines when and ―how many‖ Uses standard instantiation mechanism (public no argument constructor) Creates an EJBObect(proxy) Creates an EJB instance (actual bean instance) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 69
    • 70. EJB Lifecycle Lifecycle of an instance is managed by container Lifecycle phases: Does Not exist – no bean instance in memory Post-construct / Not-ready – bean instance exists but isn‘t ready for client interaction Ready – exists, initialized, and ready for interactions Pre-removal – bean instance is about to be removed Lifecycle transition notifications are handled through call-backs 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 70
    • 71. EJB Development Elements Developing an EJB
    • 72. Elements of an EJB 2.x Each EJB is implemented by: Home interface* Business interface Bean Implementation XML Files ejb-jar.xml app-server-xml.xml 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com *Deprecated in EJB3.0 72
    • 73. Elements of an EJB 3.x Each EJB is implemented by: Business interface* Bean Implementation XML File ejb-jar.xml* 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com *Optional in EJB3.1 73
    • 74. Elements of EJB [cont.] Each EJB is described by meta-data Tells container how to manage EJB Annotation-based in Java code Or, XML based* ejb-jar.xml server specific xml file Key description elements EJB name EJB JNDI name EJB type Security and transaction information 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com *Optional in EJB3.0 74
    • 75. EJB Development Cycle 1. Write client 2. Write EJB 1. Interfaces (depending on version) 2. Implementation 3. Define configuration 1. Annotate 2. Or create descriptors 4. Compile 5. Package 6. Generate client access classes 7. Deploy 8. Test 9. Repeat 2 - 8 until satisfied 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 75
    • 76. EJB Deployment EJBs have their own deployment model Each deployment executes in its own context 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 76
    • 77. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Summary There are 3 types of EJBS: Session Beans Message driven Beans JPA Entities There are 3 client access modes Remote Local Local no interface EJBs are implemented using: Business interface Bean implementation EJBs are configured using meta-data 77
    • 78. LAB: Setup Environment In this lab, you will: Setup your development environment: Install JBoss Install Eclipse Configure Eclipse Add JBoss as an app server Create an EJB Project 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 78
    • 79. Session Beans Enterprise Business Logic
    • 80. Presentation Topics In this section, we will discuss: Session Bean Concepts Developing a Session Bean Developing a Session Bean Client 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 80
    • 81. Objectives When we are done, you should be able to: Describe the 3 types of session beans Implement a simple stateless session bean Package and deploy a simple session bean Implement a simple stateful session bean Package and deploy a simple stateful bean Explain pros and cons of stateful vs. stateless vs. singleton session beans 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 81
    • 82. Session Bean Concepts
    • 83. Review of Session Beans Concepts Reusable business logic components Can be used to manage state across client interactions Three types Stateless (SLSB) Stateful (SFSB) Singleton (SSB) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 83
    • 84. Choosing a Session Bean Use a Session bean if: Only one client has access to bean at any given time State of bean is not persistent Bean represents a web service Use a Stateful Session bean if: Bean state represents client interaction Bean needs to hold client data across interactions Bean acts as a client mediator to other beans Need thread-safe interactions 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 84
    • 85. Choosing a Session Bean Use a Stateless Session bean if: Concerned about performance No distinction across client or interaction Need synchronous or asynchronous interactions Use a Singleton Session bean if: You need only a single instance of the bean in memory Want to maintain consistency across all client interactions Need to support concurrent client-access 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 85
    • 86. Session Bean Cardinality 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com @Stateless @Stateful @Singleton Remote Client Access ✔ ✔ ✔ Local Client Access ✔ ✔ ✔ Concurrent client access ✖ ✖ ✔ Unique per client ✖ ✔ ✖ Client-bean instances Pooled 1:1 Many:1 86
    • 87. Developing a Session Bean
    • 88. Developing a Session Bean Steps to create a session bean 1. Define business logic interface 2. Annotate the business interface 3. Create the session bean, implementing the interface 4. Annotate class defining type 5. Compile, deploy and debug as discussed above 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 88
    • 89. Developing Business Interface Similar to standard Java interface public interface SomeInterface public intgetSomeProperty(); Annotated with client-access mode @Local – local (in context of application only) @LocalBean– local (no interface bean) @Remote – remote (inside and outside of context) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 89
    • 90. Local Interface 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 90
    • 91. Remote Interface 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 91
    • 92. Developing a Session Bean Class requirements similar to JavaBeans: Must be a top level class Must be defined as public Can not be final or abstract Must have a public no-argument constructor that takes no parameters. Must not define the finalize method Must implement the methods of the business interface 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 92
    • 93. Requirements [cont.] Similar to implementing a POJO Implement business interface Define variables and other ―internal‖ methods Annotate bean with session bean type @Stateless @Stateful @Singleton 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 93
    • 94. Local Stateless Bean 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 94
    • 95. Remote Stateful Bean Implementation 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 95
    • 96. LocalBean Singleton Bean Implementation 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 96
    • 97. Summary There are three types of session beans: Stateless - @Stateless Stateful - @Stateful Singleton - @Singleton Every session bean has: Business interface Implementation class Deployment descriptor information 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 97 :: QUESTION :: What is the business interface of a LocalBean?
    • 98. LAB Implement the Three versions of the Calculator 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 98
    • 99. Accessing Session Beans
    • 100. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Section Topics In this section, we will discuss: Client EJB Interactions Using JDNI to Access EJBs Using DI to Access EJBs Hiding EJBs through a Session Facade 100
    • 101. Objectives When we are done, you should be able to: Be able to write three common types of clients for the various types of session beans Understand how and when a session bean instance is created Use JNDI and DI to access a bean 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 101
    • 102. Client-EJB Interactions
    • 103. Quick Review of EJB interactions EJB instance is created and managed by container Physical EJB instance is ―hidden‖ to client Client interactions are performed through a proxy (sometimes called the EJBObject) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 103
    • 104. Client -> EJB Interactions 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com ―proxy‖ EJB Client Container 104
    • 105. Client -> EJB Interactions [cont.] A client for an EJB can be: A Java EE Application Client A Java EE component (JSP, Servlet, JSF, EJB) Any Java object A Java application Client finds a proxy to interact with an EJB using: Java Naming and Directory Interfaces (JNDI) Dependency Injection (DI) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 105
    • 106. Steps for Interacting with an EJB 3 Step Plan: 1. Declare a reference for the EJB‘s interface 2. Get the EJB ―instance‖ Using JNDI for remote clients or legacy EJBs Using DI for local clients or application clients 3. Invoke methods on the interface 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 106
    • 107. Using JNDI to Access EJBs
    • 108. JNDI Java Naming and Directory Interface is part of Java SE Standard API to interact with naming and directory services Provide the ability to look things up in a ―registry‖ Used in enterprise solutions to locate resources such as EJBs, JMS queues or Web Services JNDI resources are organized in a tree structure Analogous to the folder structure of a computer‘s file system Supports events, lookups, and complex searching against structure 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 108 JNDI DS JNDIIMPl App
    • 109. Key JNDI Concepts Finding an EJB with JNDI uses four key concepts Context Initial Context Path & Name Search 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 109
    • 110. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com JNDI Contexts JNDI supports multiple contexts . . . . . . each containing different resources Local context - an application can obtain access to its resources—EJBs, DataSources, etc. Remote context - an application can also obtain access to a remote application server‘s resources – remote EJBs, etc. 110
    • 111. javax.naming.Context Contexts contain name-to-object bindings Interface representing a naming context Provides methods for binding, removing, finding, etc. Also supports environment properties 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 111
    • 112. javax.naming.InitialContext Represents the starting point for naming operations Could be ―root node‖ Or, ―sub node‖ in tree Is an implementation of Context 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 112
    • 113. Configuring the InitialContext Use a default configuration: Context c = new InitialContext(); Programmatically control the configuration Hashtableenv = new Hashtable(); env.put("java.naming.factory.Initial",”…"); env.put("java.naming.provider.url",”…); Context c = new InitialContext(env); Externalize the configuration in jndi.properties 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 113
    • 114. JBoss Context Properties Hashtableenv = new Hashtable(); env.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); env.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); env.put("java.naming.provider.url", "localhost:1099"); Context ctx = new InitialContext(env); 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 114
    • 115. Finding EJB References Traditionally, EJB containers defined their own ―naming‖ scheme Varied by app server vendor Path and entry name could be overridden in xml deployment descriptor EJB3.1 has global JNDI Naming conventions: qualified class name java:global[/<app-name>]/<module-name>/<bean-name> java:app[/<module-name>]/<bean-name> java:module/<bean-name> 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 115
    • 116. Global JNDI in JBoss AS java:global/Working-with-EJB3- Tutorials/EJB3/HelloWorld!com.developintelligence.tutorials.ejb3.HelloWorld java:global/Working-with-EJB3-Tutorials/EJB3/HelloWorld java:app/EJB3/HelloWorld!com.developintelligence.tutorials.ejb3.HelloWorld java:app/EJB3/HelloWorld java:module/HelloWorld!com.developintelligence.tutorials.ejb3.HelloWorld java:module/HelloWorld 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 116
    • 117. Simple JNDI Client Example Example represents a ―stand alone‖ Java application Java application uses JNDI to find a remote bean Uses the remote reference to invoke operations 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 117
    • 118. Viewing JNDI Tree in JBoss 5 http://localhost:8080/jmx-console 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 118 Click on: • Service=JNDIView
    • 119. JNDIView 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 119 Click on ―Invoke‖
    • 120. JMX MBean Operation View Scroll down until you see … 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 120
    • 121. Naming View in Jboss 7 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 121 http://localhost:9990/console/App.html#naming
    • 122. Simple JNDI Lookup [Glassfish] 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 122
    • 123. Simple JNDI Lookup [JBoss] 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 123
    • 124. Making the Stand Alone Client Work There‘s some magic to make the client work: 1. Need to bundle the ―remote‖ interfaces of EJB in a Jar (commonly called the ejb-client-jar) 2. Need to define the JNDI properties 3. Need to bundle Java EE jars for things like UserTransaction 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 124 : : NOTE : : Some app servers provides an appserver-client.jar to simplify #2 & #3
    • 125. Simple Servlet JNDI Example Example represents a servlet ―controller‖ Java application uses JNDI to find an EJB Uses the local reference to invoke operations 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 125
    • 126. Simple JNDI Servlet [Glassfish] 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 126
    • 127. Simple JNDI Servlet [JBoss] 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 127
    • 128. LAB: JDNI Client Labs In this lab you will: Write a stand-alone client A Servlet / JSP client 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 128
    • 129. Problems with JNDI Keeping track of: JNDI path Bean name 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 129
    • 130. Using DI to Access EJBs
    • 131. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Dependency Injection Java EE 5 introduced support for dependency injection (DI) Container can automatically ―inject‖ references Used commonly in context of JNDI Based on annotations Dependency injection Simplifies programming Makes access to JNDI largely transparent 131
    • 132. Working with DI Removes JNDI lookups; DI can be used to inject: @EJB @Resource, @PersistenceContext, @EntityManager Container ―inserts‖ references based on defaults Default naming schemes, typing, mappings Defaults can be over-ridden using annotation attributes DI is supported within: Enterprise Java Beans Servlets / JSPs / Filters / ManagedBeans Application Client Container Clients 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 132
    • 133. Key DI Annotations @EJB Used for DI of an EJB Can specify additional information such as EJB‘sname or beanNameor lookup @Resource Used for DI of non-EJBs Specify things like SessionContextor DataSource 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 133
    • 134. Working with EJB Injection Need to understand defaults DI attempts to inject based on context Attempts to resolve EJB reference based type of interface Can only have one bean bound with that type Beyond defaults DI attempts to inject based on context Attempts to resolve EJB reference based on name 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 134
    • 135. In-Container DI [EJB -> Servlet DI] 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 135
    • 136. Hiding EJBs through a Session Facade
    • 137. Façade Pattern Description Intent: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. Motivation: Structuring a system into subsystems helps reduce complexity. A common design goal is to minimize the communication and dependencies between subsystems. A façade provides a single, simplified interface to the more general facilities of a subsystem. 137
    • 138. Façade Real World Example The Facade defines a unified, higher level interface to a subsystem, that makes it easier to use. Consumers encounter a Facade when ordering from a catalog. The consumer calls one number and speaks with a customer service representative. The customer service representative acts as a Facade, providing an interface to the order fulfillment department, the billing department, and the shipping department. 138
    • 139. Session Façade Implementation of the Façade pattern Applied to Enterprise JavaBeans Façade is implemented as a Session Bean Commonly implemented to create: Single point of entry into complex systems Hide / abstract functionality Web service endpoint Session Façade could be implemented as @Local or @Remote 139
    • 140. Session Façade Structure 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 140
    • 141. Implementing a Session Facade Simple steps to create a session façade Create Façade interface Exposes a limited number of methods Potentially hides exception and data dependencies Create Bean implementation Accesses / relies on other beans to perform operations Generally multiple dependent operations are performed in a single interface method Translate results / exceptions in client-neutral way 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 141
    • 142. Session Façade Implementation 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 142
    • 143. Façade Delegate 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 143
    • 144. Summary EJB‘s are located using JNDI or DI JNDI relies on Context, InitialContext, and lookups DI relies on @EJB annotation 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 144
    • 145. LAB: Convert JNDI Client to DI 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 145
    • 146. Advanced Session Bean Concepts
    • 147. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Section Topics In this section, we will discuss: Session Bean Identity Session Bean Lifecycle Implementing Lifecycle Listeners Advanced Singleton Concepts 147
    • 148. Objectives When we are done, you should be able to: Understand when and how a session bean is created Understand uniqueness constraints of each bean type Describe the lifecycle phases for Stateless, Stateful, and Singleton beans Implement lifecycle call-back handlers 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 148
    • 149. Session Bean Identity
    • 150. Session Bean Identity Can test session bean references using equals method or hashCodemethod Stateless session bean identity - references of the same interface type, for the same stateless session bean, have the same object identity 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com @EJB MyBean bean1; @EJB MyBean bean2; if(bean1.equals(bean1)) // true if(bean1.equals(bean2)) //true 150
    • 151. Session Bean Identity Stateful session bean identity – stateful beans have a unique identity that is assigned by the container at the time the object is created. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com @EJB MyBean bean1; @EJB MyBean bean2; if(bean1.equals(bean1)) // true if(bean1.equals(bean2)) //false 151
    • 152. Session Bean Identity Singleton session bean identity – all references of the same type, for the same singleton session bean, have the same object identity 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com @EJB MyBean bean1; @EJB MyBean bean2; if(bean1.equals(bean1)) // true if(bean1.equals(bean2)) //true 152
    • 153. Session Bean Lifecycle
    • 154. Session Bean Creation Session bean instances are created and managed by container No way for client to directly instantiate a bean Physical EJB object creation is ―hidden‖ from client Session beans are created as a result of some other action Stateless – first client lookup Stateful – on every client lookup Singleton – on application load 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 154
    • 155. Session Bean Destruction Session bean instance is destroyed by container Session bean ―destruction‖ is result of some other action Stateless – pool clean up or inactivity Stateful – client inactivity or remove Singleton – application shutdown Certain exceptions can cause beans to be destroyed (on initialization) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 155
    • 156. Session Bean Lifecycle In between creation and destruction, a bean has a lifecycle Lifecycles are slightly different for each type Lifecycle allows container and developer to initialize / un-initialize bean at key times 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 156
    • 157. 5 Key Lifecycle Phases @PostConstruct - after object is created @PreDestroy– before object is removed from container @PrePassivate– before object‘s states are preserved @PostActivate– after object‘s states are resurrected @Remove – after client signals object removal 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com : : NOTE : : NOT ALL SESSION BEANS GO THROUGH ALL PHASES 157
    • 158. Stateless Session Beans Stateless Session Bean Lifecycle Create instance @PostConstruct– perform initialization Process business methods @PreDestroy– undo initialization 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 158
    • 159. Stateful Session Beans Stateful Session Bean Lifecycle Create instance @PostConstruct– perform initialization Process business methods @PrePassivate– prepare for serialization @PostActivate – recover from serialization @Remove – remove ejb from container @PreDestroy– undo initialization 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 159
    • 160. Stateful Session Bean Lifecycle 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 160
    • 161. Singleton Session Beans Singleton Session Bean Lifecycle Create instance @PostConstruct– perform initialization Process business methods @PreDestroy– undo initialization 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 161
    • 162. Implementing Lifecycle Callback Listeners
    • 163. Lifecycle Callbacks As an EJB developer, you can receive notification as a bean transitions through each phases Notification is done through use of a callback method Callback methods are annotated with the appropriate lifecycle callback annotation 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 163
    • 164. Implementing Callback Methods Annotations are used to identify a callback method A single method can handle multiple callbacks Methods can be defined using any access modifier Callback methods can throw runtime exceptions, but not application exceptions 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 164
    • 165. Lifecycle Example 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 165
    • 166. LAB: Implement Lifecycle Listeners 1. Add the remaining lifecycle methods to the Stateful bean 1. @PrePassivate/ @PostActivate 2. Make the add method @Remove 2. Add the lifecycle methods to the Singleton and the other stateless bean 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 166
    • 167. Advanced Singleton Concepts
    • 168. Singleton Initialization Strategies Two types of initialization strategies for Singletons: Lazy – container chooses when to instantiate bean Eager Explicitly tell container to create instance at application load Over-rides default behavior Implemented using the @Startup annotation 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 168
    • 169. @Startup Singleton 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 169
    • 170. Ordered Instantiation Singleton bean instantiation can depend on other beans Dependencies can be determined by container Or, explicitly defined by developer Uses @DependsOnannotation 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 170 :: QUESTION :: Which singleton is create first?
    • 171. Summary Each session bean has a distinct lifecycle There are 5 lifecycle annotations @PostConstruct @PreDestroy @PrePassivate @PostActivate @Remove Beans can receive notification of lifecycle transitions through callbacks 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 171
    • 172. LAB Implement two singletons and prove out the @Startup and @DependsOnannotation 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 172
    • 173. Java Message Service An overview of JMS
    • 174. Section Topics In this section, we will discuss: Introduction to Java Messaging Service (JMS) Working with JMS Developing a Message Producer 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 174
    • 175. Objectives When we are done, you should be able to: Understand the advantages of using a messaging system Describe the 5 key concepts found in messaging systems Create a message Publish a message to a queue 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 175
    • 176. Introduction to Java Messaging Service
    • 177. Overview of Messaging Systems Function as intermediary between end-points of a system Creates a loosely coupled system Participants can function independent from one another Solutions built using message are commonly referred to as MOM (message-oriented- middleware) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 177
    • 178. Key Messaging Concepts Message – encapsulates data passed during communication Message Producer – creator of the message Messaging System – responsible for routing and delivery of message Destination – delivery endpoint for message Message Consumer – end recipient of message 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 178
    • 179. What is a ―Message?‖ A collection of data passed in a one way (e.g., queued) communication A message contains: Header fields: priority, timestamp, etc. Optional message body Optional properties 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 179
    • 180. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com What is Java Message Service? A Java-based messaging system Robust messaging support: Asynchronous sending and receiving of messages Decoupled communication between sender, receiver Robust and transparent delivery mechanisms Defined as an API - javax.jms Used by developers interacting with messaging systems Implemented by Java EE server vendors 180
    • 181. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com Destination Types Queue Topic Point-to-point communication Multipoint communication Publishers emit messages to topics Subscribers monitor topics of interest One message is received per message sent One published message can result in zero to many messages received Useful for queuing some data that needs to be processed exactly once Useful when an unknown number of observers may need to monitor the same events 181
    • 182. Working with JMS Creating a Message Producer
    • 183. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com What is a Message Producer? Message producers create messages ―Send‖ messages to destination through messaging system Can be just about anything: Stand alone Java application Java Object Java EE Component Legacy Systems 183
    • 184. Key JMS API Concepts To create a message producer, you need: Destination Connection Session MessageProducer Message 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 184
    • 185. JMS Destination javax.jms.Destination General description of a JMS endpoint Represents provider-specific address javax.jms.Queue Considered a Destination General description of a JMS Queue javax.jms.Topic Considered a Destination General description of a JMS Topic 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 185
    • 186. Accessing a JMS Destination Two choices to access a destination: JNDI Lookup Dependency Injection Dependency Injection examples: @Resource(mappedName="jms/Queue") private Queue queue; @Resource(mappedName="jms/Topic") private Topic topic; @Resource(mappedName="jms/Queue") private Destination topic; 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 186
    • 187. JMS Connection javax.jms.Connection - physical connection to the underlying JMS implementation Connections are retrieved through a javax.jms.ConnectionFactory Two types of connection factories: javax.jms.QueueConnectionFactory javax.jms.TopicConnectionFactory 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 187
    • 188. Getting a JMS Connection Get ConnectionFactory 1st @Resource(mappedName="jms/ConnectionFactory") private ConnectionFactoryconFactory; Get connection from factory Connection con = conFactory.createConnection(); Close connection when done con.close(); 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 188
    • 189. JMS Session A javax.jms.Session Describes interactions between message producer/consumer and messaging system Is single-thread context for producing/consuming messages Created through a Connection Session session = con.createSession(. . .); 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 189
    • 190. Session Configuration Sessions are configured as part of creation: createSession(txn-support, acknowledgement) Sessions support transactions Transacted (true): messages are not sent until the session closes Not transacted (false): messages are sent immediately Session support acknowledgement AUTO_ACKNOWLEDGE CLIENT_ACKNOWLEDGE DUPS_OK_ACKNOWLEDGE 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 190
    • 191. MessageProducer javax.jms.MessageProducer Associated with a specific Destination Created from Session MessageProducer producer = session.createProducer(destination); MessageProducer producer = session.createProducer(queue); MessageProducer producer = session.createProducer(topic); Used to send messages to a Destination producer.send(message); 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 191
    • 192. Message javax.jms.Message described by: Header – name-value pairs used by messaging system and message consumer Properties – name-value pairs to specify additional information Body – payload of the message Type - of message being transported 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 192
    • 193. Common Message Header Fields Filed Name Set By JMSDestination send or publish method JMSDeliveryMode send or publish method JMSExpiration send or publish method JMSPriority send or publish method JMSMessageID send or publish method JMSTimestamp send or publish method JMSCorrelationID Client JMSReplyTo Client JMSType Client JMSRedelivered JMS provider 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 193
    • 194. Message Types Message Type Contents of Body TextMessage String MapMessage Name-value-pairs ByteMessage Stream of bytes StreamMessage Stream of Java ―primitives‖ ObjectMessage Serializable object 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com TextMessage message = session.createTextMessage(); message.setText(“Hello Messaging World”); producer.send(message); 194
    • 195. Developing a Message Producer
    • 196. Creating a Message Producer Steps to create a Message Producer 1. Create Destination in Messaging System 2. Create Client 1. Get Destination 2. Create Connection 3. Create Session 4. Create MessageProducer 5. Create Message 6. Send Message 7. Close Session 8. Close Connection 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 196
    • 197. Message Producer [Glassfish] 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 197
    • 198. Message Producer [cont.] 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 198
    • 199. JMS in JBoss Connection factory Single connection factory Can use with default destinations Or, user created destinations Accessed using JNDI key ConnectionFactory Destinations Create using admin-console Specify type (template), name, and JNDI path 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 199
    • 200. Message Producing in JBoss Connection Factory is: @Resource(mappedName="ConnectionFactory‖) ConnectionFactoryconFactory; Queue is: @Resource(mappedName="HelloWorldQueue‖) Queue queue; 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 200
    • 201. Summary 6 Key Concepts in JMS Solutions Message Producer Message System Message Consumer Message Destination Session 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 201
    • 202. LAB Modify the Bean: For every lifecycle transition that occurs: Send a text message the Queue Specify in the message a property called ―operation‖ With a value ―lifecycle‖ For every other operation: Send a text message the Queue Specify in the message a property called ―operation‖ With a value with the name of the operation 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 202
    • 203. Message Driven Beans
    • 204. Section Topics In this section, we will cover: Developing a Message Driven Bean Configuring a MDB Message Handling 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 204
    • 205. Objectives When we are done, you should be able to: Identify two ways to implement an MDB Provide the appropriate configuration for an MDB using a Queue Filter out messages using a Selector 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 205
    • 206. Developing a Message Driven Bean
    • 207. Message Driven Beans [MDB] Reusable workflow logic components Rely on Java Messaging System Support transactions Similar to Stateless Session Beans MDBshave no client state data No distinction across client or bean Different from Stateless Session Beans No direct client access Invoked through message notification Asynchronous interactions 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 207
    • 208. MDB Lifecyle Very simple lifecycle Create @PostConstruct, @PreDestroy onMessage– when a message is delivered 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 208
    • 209. Developing an MDB Set up messaging in Java EE application server Develop the MDB class Configure the MDB Process the Message Compile, deploy and debug as discussed above 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 209
    • 210. Develop the MDB Two ways to implement an MDB 1. Inheritence-based 1. MessageListenerinterface 2. implement onMessagemethod 2. Annotation-based 1. Flexible implementation 2. Declare with method handles the message 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 210
    • 211. Inheritance Based Example import javax.ejb.*; import javax.jms.*; @MessageDriven public class MyMDB implements MessageListener { public void onMessage(Messagemsg) { System.out.println("Got message!"); } } 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 211
    • 212. Annotation Based Example import javax.ejb.*; import javax.jms.*; @MessageDriven(messageListenerInterface= javax.jms.MessageListener.class) public class MyMDB { public void onMessage(MessageinMessage) { System.out.println("Got message!"); } } 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 212
    • 213. Configuring a MDB
    • 214. MDB Configuration Creating an MDB with @MessageDriven is not enough Need to configure the MDB with: Destination information Message acknowledgement Message selection 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 214
    • 215. Destination Configuration Simple configuration @MessageDriven(mappedName = "jms/HelloMDBQueue”) Complete configuration @MessageDriven(activationConfig ={ @ActivationConfigProperty (propertyName="destination", propertyValue = "jms/HelloMDBQueue"), @ActivationConfigProperty (propertyName="destinationType”, propertyValue = "javax.jms.Queue") } ) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 215
    • 216. Simple MDB Configuration Example 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 216
    • 217. Traditional MDB Configuration Example 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 217
    • 218. LAB Build a MDB Associate it with the HelloWorldQueue Implement the onMessagemethod Print off each message that‘s received Run the ―test‖ servlet 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 218
    • 219. Message Handling
    • 220. Message Filtering MDBs are not associated with a specific type of Message Can receive message sent to associated Destination Need to filter out unwanted messages Simple filtering performed using instanceof 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 220
    • 221. Advanced Filtering Advanced, delivery-time filtering can be performed by container Only ―matching‖ messages will be delivered to MDB Matching based on headers and properties, not JMS Message type Matching criteria defined as a Message Selector Defined in the activationConfigattribute of @MessageDriven Defined as an @ActivationConfigPropertynamed messageSelector 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 221
    • 222. MDB Message Selector Example 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 222
    • 223. Message Selectors Defined as part of the activation configuration information Use SQL-like syntax to specify criteria Work with message headers And developer created properties Defined in terms of: Identifiers – part of expression being compared Literals – hard-coded expression values Comparison operators – comparison logic 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 223
    • 224. Message Selector Identifiers Potential identifiers for a message selector JMS Headers JMSDeliveryMode JMSPriority JMSMessageID JMSTimestamp JMSCorrelationID JMSType JMS Properties setStringProperty, setBooleanProperty setIntProperty, etc. 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 224
    • 225. Message Selector Literals Define literal values String Enclosed in single-quotes Apostrophe are delimited with a single-quote ‗DevelopIntelligence‘‘s‘ Booleans – true or false Numerics Whole numbers: 700, -743 Real number: 3.145, 9.82 Scientific: 3.5E6 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 225
    • 226. Message Selector Comparison Operators Common comparison operators: Algebraic comparison operators LIKE operator BETWEEN operator IN operator NOT operator IS NULL operator 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 226
    • 227. Message Selector Examples Only ―add‖ operations ActivationConfigProperty(propertyName="messageSelector", propertyValue = "Operation = 'add‘‖)} Only ―multiply‖ operations with a result equal to 100 ActivationConfigProperty(propertyName="messageSelector", propertyValue = "Operation = ‘multiply‘ AND Result = 100‖)} Only ―multiply‖ or ―add‖ operations with a result greater than 100 ActivationConfigProperty(propertyName="messageSelector", propertyValue = "Operation IN (‘multiply‘,‘add‘) AND Result > 100‖)} 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 227
    • 228. MDB Message Selector Example II 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 228
    • 229. Message Acknowledgement Configuration Default – AUTO_ACKNOWLEDGE Non-Default Example: @MessageDriven( activationConfig={ @ActivationConfigProperty( propertyName=”acknowledgeMode”, propertyValue=“Dups-ok-acknowledge) } ) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 229
    • 230. Summary Message Driven Beans have a distinct lifecycle Simplest way to implement an MDB @MessageDriven(mappedName=―queue/Example‖) implements MessageListener onMessage(Messagem) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 230
    • 231. LAB: Modify the MDB to only handle lifecycle messages 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 231
    • 232. Advanced EJB Development
    • 233. Section Topics In this section, we will cover: Managing Singleton Concurrency Aspect-Oriented Programming with Interceptors EJB Transactions EJB Security Web Service Development using EJBs 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 233
    • 234. Objectives When we‘re done, you should be able to: Understand how to manage concurrency in a Singleton EJB Apply AOP to EJBs using interceptors Identify the two types of transaction strategies Identify a security mechanism supported in EJB Indentify how to transform an EJB into a Web Service 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 234
    • 235. Singleton Concurrency Management
    • 236. Concurrent Access in Singletons Singletons support concurrent access Unprotected concurrent access can cause corruption Concurrency can be managed by: CONTAINER – default BEAN – explicit (developer) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 236 @ConcurrencyManagement(ConcurrencyMangagementType.BEAN)
    • 237. Controlling Concurrency with Locks Container uses an Object-locking strategy Sometimes referred to as an object monitor Conceptually similar to java.util.Lock mechanism Default behavior is to lock object for all method operations Obtaining a lock can be expensive Can cause unnecessary ―waiting‖ in caller By default, bean access isn‘t really concurrent Can over-ride default behavior using @Lock 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 237
    • 238. @Lock Used to define method-level locking strategies Bean can have a concurrent-safe methods Or, concurrent unsafe methods Or, a mixture of the two Locking strategy is applied using: @LOCK(LockType.READ) – supports concurrency @LOCK(LockType.WRITE) – does not support concurrency Locking strategy can be applied to: Class – defines general locking strategy for all methods Method – defines specific locking strategy for method 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 238
    • 239. Singleton Concurrency Example 239 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com
    • 240. Controlling Dead Lock Deadlock - is a situation where in two or more competing actions are each waiting for the other to finish, and thus neither ever does Deadlock can occur in every concurrent system In singletons, may be caused by long-running operations Manage ―wait-times‖ using 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 240
    • 241. Lab: Apply Locking to a Singleton 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 241
    • 242. Aspect-Oriented Programming with Interceptors
    • 243. Aspect Oriented Programming Definition: is a programming paradigm which aims to increase modularity by allowing the separation of cross- cutting concerns Common cross-cutting concerns: Logging, Security Validation, Transformation Advantages of AOP Reusability Separation of Concern Consistency 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 243
    • 244. What is an Interceptor? Interceptor functionality enables Aspect-oriented programming within Java EE Interceptors can be associated with methods or an entire class Interceptors ―intercept‖ interactions with bean Can forward the call to the bean Can process the call directly Can process and forward the call 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 244
    • 245. Interceptor 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com ―proxy‖ EJB Client Container 245
    • 246. Interceptor Characteristics Interceptors have: Same lifecycle as the associated bean Their own context, known as an InvocationContext 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 246
    • 247. Types of EJB Interceptors 3 Types of Interceptors 1. Business Method level interceptors Apply to a single method in a class Or, apply to all methods in a call 2. Lifecycle Callback Interceptors 3. Timer Timeout Interceptors 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 247
    • 248. Implementing a Business Method Interceptor [in EJB] You can implement an interceptor method within an EJB Simplest way to setup AOP in EJB But, the concern is no longer reusable And, you can only have one per class 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 248 @AroundInvoke public Object anyMethodName(InvocationContextic) throws Exception
    • 249. Refactoring to an Interceptor If every method in an EJB has code that performs same concern. . . Consider refactoring to an internal interceptor Makes code cleaner Potentially easier to maintain Higher consistency of execution 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 249
    • 250. Redundant Concern 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 250
    • 251. Refactored Concern 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 251
    • 252. Refactored Concern [cont.] 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 252
    • 253. Externalizing the Concern Better approach is to externalize the concern Create a class that is an Interceptor Declare a Java technology class Include a public no-arg constructor Declare an interceptor method class @AroundInvoke public Object methName(InvocationContextic) throws Exception { . . } Invokes the InvocationContextobject‘s proceed return ic.proceed(); Associate interceptor with EJB 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 253
    • 254. Associating an Interceptor With a class: @Stateless @Interceptors(MyInterceptor.class) public class MyBean { . . . } With a specific method @Stateless public class MyBean { @Interceptors(MyInterceptor.class) public void someMeth() { . . . } } 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 254
    • 255. EJB with Interceptor Example 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 255
    • 256. Interceptor Class 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 256
    • 257. Implementing Other Interceptors Lifecycle Interceptors Timeout Interceptors 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 257 throws Exception {}
    • 258. Interceptor Chaining More than one inceptor can be applied to a bean or a method This creates an interceptors chain Class-level interceptors are executed first, then method level interceptors 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 258
    • 259. Default Interceptors May want to configure cross-cutting concerns at application level More flexibility Externalized from code Default interceptors are configured in ejb-jar.xml Can bind an interceptor to all beans or a single bean Can specify ordering and override other interceptors 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 259
    • 260. ejb-jar.xml Example 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 260
    • 261. LogInterceptor Example 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 261
    • 262. LAB Create a log interceptor, defining it as a default interceptor for all ejbs deployed in the application 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 262
    • 263. Transactions
    • 264. Overview of Transactions Purpose of transactions: Treat multiple operations as if they were one All succeed together or fail together ACID of transactions: Automicity – all operations succeed or none do Consistency – system will be consistent before and after request Isolation – txns are not seen outside of their scope until completed Durability – once a txn successfully completes, client must commit to its changes 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 264
    • 265. Transactions and Java EE Two primary types of transaction management: Container managed Container responsible for creating, committing, and rolling back txns Completely hidden from developer Bean managed Developer responsible for creating, committing, and rolling back txns Developer must have good understanding of Transaction API 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 265
    • 266. Java EE Transaction Management Transaction management configuration performed using either: Annotations XML file Annotation-based @TransactionManagement Applied to the bean class Default is container-managed Strategy defined by TransactionManagementType @TransactionManagement(TransactionManagementType.BEAN) @TransactionManagement(TransactionManagementType.CONTAINER) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 266
    • 267. CMT Transactional EJB @TransactionManagement(CONTAINER) public class MyEJB implements MyI { . . . public void doSomething(){ . . . } . . . } 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 267
    • 268. BMT Transactional EJB @TransactionManagement(BEAN) public class MyEJB implements MyI { . . . public void doSomething(){ . . . } . . . } 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 268
    • 269. Transaction Management Attributes 6 different settings relating to transaction needs: NOT_SUPPORTED – method can not operate correctly within a txn; container possibly suspends current txn when performing operation SUPPORTS – method can operate correctly within a txn REQUIRED – method requires txn, but doesn‘t need to be new 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 269
    • 270. Transaction Management Attributes 6 different settings relating to transaction needs: REQUIRES_NEW – method requires txn, creates new txn, possibly suspending current txn until operation completes MANDATORY – method can only operate within txn; if method is invoked without txn, an exception is generated NEVER – method can not operate within txn; if method is invoked within txn, an exception is generated 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 270
    • 271. TransactionAttributes Defined in TransactionAttributes Inform container about a bean‘s transaction requirements Can be applied to an entire bean or a set of methods or both 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 271
    • 272. EJB Attribute Support Attribute Stateless Stateful Singleton MDB NOT_SUPPORTED ✔ ✔ ✔ ✔ REQUIRED ✔ ✔ ✔ ✔ REQUIRES_NEW ✔ ✔ ✔ ✖ SUPPORTS ✔ ✔ ✔ ✖ MANDATORY ✔ ✔ ✔ ✖ NEVER ✔ ✔ ✔ ✖ 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 272
    • 273. CMT Transactional EJB All methods – REQUIRED @TransactionAttribute(REQUIRED) public class MyEJB implements MyI { . . . public void doSomething() { . . . } . . . } 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 273
    • 274. CMT Transactional EJB Single method – REQUIRED public class MyEJB implements MyI { . . . @TransactionAttribute(REQUIRED) public void doSomething() { . . . } . . . } 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 274
    • 275. Managing Transactions Only BMT bean‘s have direct access to txn Hidden from CMT beans CMT can flag a txn for rollback using EJBContext‘ssetRollbackOnlymethod Or determine if txn is going to be rolled-back using getRollbackOnly Applications can be configured to roll back a txn automatically 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 275
    • 276. LAB Add transaction REQUIRED TransactionAttributeannotation to sayHelloremote bean Run servlet Should fail 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 276
    • 277. Security
    • 278. Security Terms Identity – who you are Authentication – validating you are you who say you are Authorization – validating you have permission to take action 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 278
    • 279. Java EE & Security Identity – can be specified as security credential Authentication – handled by server or 3rd party Authorization – focus of EJB security support 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 279
    • 280. JSR250 Security Annotations 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 280
    • 281. Configuring Authorization Declares roles that could interact with bean @DeclareRoles( . . . ) public class MyBean implements MyI { . . . } Identify roles are allowed to interact with bean @RolesAllowed(ADMIN) public class MyBean implements MyI { . . . } Or identify roles allowed to interact with method @RolesAllowed(ADMIN) public void doSomethingDangerous() { . . . } 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 281
    • 282. Working with Roles Can determine if caller belongs to a role context.isCallerInRole(ADMIN) Can change the role a bean operates under @RunAs(ADMIN) public class MyBean implements MyI { . . . } 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 282
    • 283. EJB Web Services
    • 284. EJB Web Services Support EJB supports three types of web services: JAX-RPC Creates Web Service Endpoints defined by WSDL Uses SOAP as ―transport‖ mechanism JAX-WS ―New‖ version of JAX-RPC Better support for more modern web service development JAX-RS REST-based web services Simple to implement and use 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 284
    • 285. Web Service Development Two ways to develop web services Manually assemble web service WSDL Java Interface Bindings Automatically Translate an EJB into a Web Service Annotation driven 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 285
    • 286. JAX-WS Web Service Annotations @WebService javax.jws.WebService Apply to EJB class Exposes all public methods @WebMethod javax.jws.WebMethod Apply to specific methods to expose within bean SOAP Configuration annotations @SOAPBinding @WebParam @WebResult 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 286
    • 287. Simple Example 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 287
    • 288. JAX-RS Annotations @Path – entry point for REST service HTTP request methods @Get @Post @Put @Delete @Produces / @Consumes – data transfers @Produces(―application/xml‖) @Consumes(―application/xml‖) @Produces(―application/json‖) @Consumes(―application/json‖) @Produces(―text/plain‖) @Consumes(―text/plain‖) 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 288
    • 289. Simple REST EJB 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 289
    • 290. Summary AOP can be applied using Interceptors Transactions can be managed by the container or the bean Java EE is focused on authorization, not authentication Stateless and MDBs can be converted to web services with the @WebServiceannotation 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 290
    • 291. EJB Timer Service Timers
    • 292. Section Topics In this section, we‘ll cover: Introduction to the Timer Service Key Steps to Developing Timed Executions Handling Timeouts 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 292
    • 293. Objectives When we‘re done, you should be able to: Identify the corrector timer given a set of requirements Implement a timer callback Manage a timer 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 293
    • 294. Introduction to Timer Service
    • 295. Java EE Timer Service Timers in Java java.util.Timer javax.swing.Timer javax.management.timer.Timer javax.ejb.Timer&javax.ejb.TimerServices TimerServiceintroduced as part of EJB 2.1 Considered a core service Provides scheduled, automatic execution No real-time scheduling 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 295
    • 296. javax.ejb.TimerService Container provided timer service Can be used with Session and Message driven beans Modeled after long-lived processes (survivability after crashes) Supports three types of Timers Non-Interval (ie: in 5 minutes) Interval (ie: every 5 minutes) Scheduled (ie: every 5 minutes on Mondays) Timer notification Structured around a timeout callback Callback invoked when Timer times-out 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 296
    • 297. Key Steps to Developing Timed Executions
    • 298. Steps to Building Timed Execution 1. Access the Timer Service 2. Schedule Timer 3. Process timeout expiration 4. Manage lifecycle of timer 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 298
    • 299. Accessing the TimerService Can use either JNDI or DI @Resource private TimerServicets; 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 299
    • 300. Schedule a Timer Create a Timer Single Action Timer – occurs 1 time only ts.createTimer(delay,object); Interval-based Timer – executes on intervals ts.createTimer(delay,interval, object); Calendar-based timer using a schedule ts.createCalendarTimer(schedule); 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 300
    • 301. Process Timeout Expiration Handle timeout (version 1) @Timeout public void listOrders(Timer timer) { String name = timer.getInfo(); // do something fancy } Handle timeout (version 2) @Timeout public void listOrders() { // do something fancy } 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 301
    • 302. Process Timeout Expiration Handle timeout (version 3) EJB2.1 style Implement javax.ejb.TimedObject Must implement ejbTimeoutmethod 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 302 :: QUESTION :: Which approach should you use, and why?
    • 303. Simple Timer Example 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 303
    • 304. Automatic Timers
    • 305. Scheduled Timers Timer Service supports UNIX cron-job like schedules Defined through a ScheduleExpression ScheduleExpression schedule = new ScheduleExpression(); //define schedule . . . timerService.createCalendarTimer(schedule); 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 305
    • 306. Defining Schedules Schedules consist of 7 attributes: Time components second – [0,59] minute – [0,59] hour – [0,23] Calendar components: dayOfMonth – [1,31],‖Last‖, ―Sun‖, ―Mon‖, ―Tue‖, etc. month – [1,12], ―Jan‖, ―Feb‖, ―Mar‖, etc. dayOfWeek – [0,7], ―Mon‖, ―Tue‖, etc. year – [2001] 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 306
    • 307. Schedule Examples Every Tuesday at Midnight ScheduleExpression schedule = new ScheduleExpression(); schedule.setDayOfWeek(―Tue‖); schedule.setHour(―0‖); Every Weekday at 3:15 AM ScheduleExpression schedule = new ScheduleExpression(); schedule.setDayOfWeek(―Mon-Fri‖); schedule.setHour(―3‖); schedule.setMinute(―15‖); Every 15 minutes of Every Hour Every Day ScheduleExpression schedule = new ScheduleExpression(); schedule.setHour(―*‖); schedule.setMinute(―*/15‖); 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 307
    • 308. Automatic Creation of Timers @Schedule annotation is interpreted by container Automatically creates a ScheduleExpression Registers ScheduleExpressionwith TimerService Apply @Schedule to a method in an EJB Can have multiple per Bean Method functions as timeout callback 308 @Schedule(dayOfWeek=―Mon‖) public void listOrders(Timer timer) { // do something fancy }2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com
    • 309. Working with Timers
    • 310. Persistent Timers Survive crash of JVM / Application Server Can configure timers to be non-persistent Must explicitly define a timer as non-persistent Programmatically using TimerConfig Automatically using @Schedule 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 310
    • 311. Timer Management Timers references can be: Stored as a result of a create call Retrieved from the TimerService Retrieved from the callback Timer management is performed on the Timer getInfo getHandle getNextTimeout getTimeRemaining cancel 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 311
    • 312. Summary Timers can be used to execute automated tasks The functionality of a method or a bean can be augmented through an interceptor 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 312
    • 313. Lab: Create an Automatic Timer 2003 – 2013 DevelopIntelligence http://www.DevelopIntelligence.com 313

    ×