KEMBAR78
Intro in JavaEE world (TU Olomouc) | ODP
JavaEE Tour

Petr Blaha
Sun Microsystems, Inc


                        1
Agenda
•   Java World introduction
•   JavaEE (Why to use this technology, APIs)
•   Dive in Enterprise Java Beans
•   Demo
•   Q&A




                                                2
Java
• First implementation released in 1995 (1.1)
• Java compiled to bytecode -> JVM
• Basic Philosophy
  > Object-oriented
  > Platform independent
  > Automatic memory management
• Current version 6



                                                3
The Java™ Platform
multiple configurations built for different types



     Java Technology   Java Technology   Workgroup   High-End
     Enabled Devices   Enabled Desktop    Server      Server




                                                      4
The Java          TM
                         Platform
                         Java 2 Platform Micro Edition
                                       (JavaMETM)


 Optional
 Packages

              Optional
              Packages


                              Personal       Personal
 Java 2       Java 2         Basis Profile    Profile
Enterprise   Standard
 Edition     Edition           Foundation Profile             MIDP
(JavaEE)     (JavaSE)                                                        Java
                                         CDC                 CLDC            Card
                                                                             APIs


                       JVM                                     KVM          CardVM


                                               * Under development in JCP
                                                                             5
What Is the JavaEE?


   Open and standard based platform for
   developing, deploying and managing
   n-tier, Web-enabled, server-centric, and
    component-based enterprise applications




                                               6
Evolution of Enterprise Application
Development Frameworks




                                 7
Single Tier (Mainframe-based)




• Dumb terminals are directly connected to mainframe
• Centralized model (as opposed distributed model)
• Presentation, business logic, and data access are
  intertwined in one monolithic mainframe application



                                                        8
Single-Tier: Pros & Cons
• Pros:
  > No client side management is required
  > Data consistency is easy to achieve
• Cons:
  > Functionality (presentation, data model, business
    logic) intertwined, difficult for updates and
    maintenance and code reuse




                                                    9
Two-Tier
                SQL
                request
                              Database
                SQL
                response



• Fat clients talking to back end
  database
  > SQL queries sent, raw data returned
• Presentation,Business logic and Data
  Model processing logic in client
  application
                                          10
Two-Tier
• Pro:
  > DB product independence (compared to single-tier model)
• Cons:
  > Presentation, data model, business logic are intertwined (at
      client side), difficult for updates and maintenance
  >   Data Model is “tightly coupled” to every client: If DB Schema
      changes, all clients break
  >   Updates have to be deployed to all clients making System
      maintenance nightmare
  >   DB connection for every client, thus difficult to scale
  >   Raw data transferred to client for processing causes high
      network traffic


                                                              11
Three-Tier (RPC based)
                                           SQL
                 RPC request               request
                                                          Database
                 RPC response             SQL
                                          response


• Thinner client: business & data model separated from
  presentation
  > Business logic and data access logic reside in middle tier server
     while client handles presentation
• Middle tier server is now required to handle system services
  > Concurrency control, threading, transaction, security, persistence,
     multiplexing, performance, etc.

                                                                 12
Three-tier (RPC based): Pros & Cons
 • Pro:
   > Business logic can change more flexibly than 2-tier
     model
      > Most business logic reside in the middle-tier server
 • Cons:
   > Complexity is introduced in the middle-tier server
   > Client and middle-tier server is more tightly-
     coupled (than the three-tier object based model)
   > Code is not really reusable (compared to object
     model based)


                                                               13
Three-Tier (Web Server)

                                       SQL
              HTML request    WEB      request
                              Server              Database
              HTML response            SQL
                                       response




• Browser handles presentation logic
• Browser talks Web server via HTTP protocol
• Business logic and data model are handled by “dynamic
  contents generation” technologies

                                                        14
Three-tier (Web Server based):
Pros & Cons
• Pro:
  > Ubiquitous client types
  > Zero client management
  > Support various client devices
     > J2ME-enabled cell-phones
• Cons:
  > Complexity in the middle-tier still need to be
    addressed


                                                     15
Trends
• Moving from single-tier or two-tier to multi-
  tier architecture
• Moving from monolithic model to object-
  based application model
• Moving from application-based client to
  HTML-based client



                                          16
Outstanding Issues & Solution
• Complexity at the middle tier server still remains
• Duplicate system services still need to be provided for the
  majority of enterprise applications
  > Concurrency control, Transactions
  > Load-balancing, Security
  > Resource management, Connection pooling
• How to solve this problem?
  > Commonly shared container that handles the above system
    services
  > Proprietary versus Open-standard based




                                                          17
Proprietary Solution
• Use "component and container" model
  > Components captures business logic
  > Container provides system services
• The contract between components and container
  is defined in a well-defined but with proprietary
  manner
• Problem of proprietary solution: Vendor lock-in
• Example: Tuxedo, .NET



                                                18
Open and Standard Solution
J2EE
• Use "component and container" model in which
  container provides system services in a well-
  defined and as industry standard
• JavaEE is that standard that also provides
  portability of code because it is based on Java
  technology and standard-based Java programming
  APIs



                                            19
J2EE is End-to-End Solution
         Firewall
                           J2EE
                        Application
               Client     Server

                                                          Enterprise
                                        Enterprise       Information
                                       JavaBeans™
               Client                                   Systems (EIS):
Client                                                   Relational
                                                         Database,
                          Web           Enterprise        Legacy
Client                   Server         JavaBeans       Applications,
                         JSP,
                                                        ERP Systems
                        Servlets
Client
             HTML/XML
                                      Other Services:
                                        JNDI, JMS,       Enterprise
         Client         Middle          JavaMail™       Information
          Tier           Tier                                Tier

                                                               20
J2EE Application DEMO




                        21
J2EE 1.4 APIs and Technologies
•   J2SE 1.4               •   Servlet 2.4
•   JAX-RPC                •   JSP 2.0
•   Web Service for J2EE   •   EJB 2.1
•   J2EE Management        •   JAXR
•   J2EE Deployment        •   Connector 1.5
•   JMX 1.1                •   JACC
•   JMS 1.1                •   JAXP 1.2
•   JTA 1.0                •   JavaMail 1.3
                           •   JAF 1.0


                                               22
The J2EE Challenge
               TM




• J2EE is enormously powerful
  > The industry standard for robust enterprise apps
• But that power sometimes gets in the way
  > Too difficult to get started
  > Even simple apps need boring boilerplate


• Can we keep the power, but make typical
  development tasks simpler?

• YES: and that is the focus of Java EE 5!
                                                       23
EoD Improvements in Java EE 5            TM




• POJO-based programming
  > More freedom, fewer requirements
• Extensive use of annotations
  > Reduced need for deployment descriptors
• Resource Injection
  > Inversion of control
• New APIs and frameworks

                                              24
Annotations in Java EE 5         TM




• Making extensive use of annotations
  >   For defining and using web services
  >   To map Java classes to XML
  >   To greatly simplify EJB development
  >   To map Java classes to databases
  >   To specify external dependencies
  >   To reduce need for deployment descriptors



                                                  25
Java EE 5 Major Features
        TM




•   Simplified web services support
•   More web service standards support
•   Greatly simplified EJBTM development
•   New persistence API
•   Easy web applications with JavaServerTM Faces



                                               26
Java EE 5 Platform

•   JSR 220 (EJB 3.0)
•   JSR 224 (JAX-WS 2.0)
•   JSR 222 (JAXB 2.0)
•   JSR 252 (JavaServer Faces 1.2)
•   JSR 52 (JSTL 1.1)
•   JSR 181 (WS Annotations)
•   JSR 245 (JSP 2.1)

                                     27
EJB (Enterprise Java Beans)




                              28
What is EJB Technology?
• A server-side component technology
• Easy development and deployment of Java
  technology-based application that are:
  > Transactional, distributed, multi-tier, portable,
    scalable, secure, …




                                                        29
Why EJB Technology?
• Leverages the benefits of component-model on the
  server side
• Separates business logic from system code
  > Container provides system services
• Provides framework for portable components
  > Over different J2EE-compliant servers
  > Over different operational environments
• Enables deployment-time configuration
  > Deployment descriptor



                                                 30
EJB Architecture




                   31
Enterprise JavaBeans

                       Enterprise JavaBeans




    Synchronous communication          Asynchronous communication
   Session Bean        Entity Bean            Message-Driven Bean




Stateless   Stateful




                                                               32
EJB 2.1 Example
// EJB 2.1

public class PayrollBean
        implements javax.ejb.SessionBean {

    SessionContext ctx;
    DataSource empDB;

    public void setSessionContext(SessionContext ctx) {
       this.ctx = ctx;
    }

    public void ejbCreate() {
      Context initialContext = new InitialContext();
      empDB = (DataSource)initialContext.lookup(
        “java:comp/env/jdbc/empDB”);
    }


                                                          33
EJB 2.1 Example
// EJB 2.1 (cont.)

    public void ejbActivate() {}
    public void ejbPassivate() {}
    public void ejbRemove() {}

    public void setBenefitsDeduction (int empId, double
    deduction) {
      ...
      Connection conn = empDB.getConnection();
      ...
    }
    ...
}

// NOTE deployment descriptor needed
                                                     34
EJB 2.1 Example
<session>
  <ejb-name>PayrollBean</ejb-name>
  <local-home>PayrollHome</local-home>
  <local>Payroll</local>
  <ejb-class>com.example.PayrollBean</ejb-class>
  <session-type>Stateless</session-type>
  <transaction-type>Container</transaction-type>
  <resource-ref>
    <res-ref-name>jdbc/empDB</res-ref-name>
    <res-ref-type>javax.sql.DataSource</res-ref-type>
    <res-auth>Container</res-auth>
 </resource-ref>
</session>
...
<assembly-descriptor>
...
</assembly-descriptor>


                                                        35
Bean Classes
 • In EJB 3.0, session beans, message-driven beans
   are ordinary Java classes
   > Container interface requirements removed
   > Bean type specified by annotation or XML
 • Annotations
   > @Stateless, @Stateful, @MessageDriven
   > Specified on bean class




                                                36
EJB 3.0 Example
// Same example, EJB 3.0

@Stateless public class PayrollBean
       implements Payroll {

    @Resource DataSource empDB;

    public void setBenefitsDeduction (int empId, double
    deduction) {
      ...
      Connection conn = empDB.getConnection();
      ...
    }

    ...
}
                                                     37
Dependency Injection
• Annotations
  > @EJB
     > References to EJB business interfaces
     > References to Home interfaces (when accessing
       EJB 2.1 components)
  > @Resource
     > Almost everything else
  > Number of annotations is simplified from EJB 3
    specification early draft
• Injection can also be specified using deployment
  descriptor elements
                                                       38
EJB 3.0 Client Example
// EJB 3.0 client view

@EJB ShoppingCart myCart;

   ...

   Collection widgets = myCart.startToShop(“widgets”);



   ...




                                                    39
EJB 3.0 & Persistence




                        40
Persistence Model in EJB 3.0

 • Entities are simple Java classes
    > Concrete classes—support use of new
    > Getter/setter “property” methods or persistent
      instance variables
    > No required bean interfaces
    > No required callback interfaces
 • Usable as “detached” objects in other application
   tiers
    > No more need for DTOs
 • Single API in JavaEE, Java SE


                                                       41
EntityManager

• EntityManager serves as untyped “home”
  for entity operations
   > Methods for lifecycle operations
     > Persist, remove, merge, flush, refresh, etc.
  > Similar in functionality to Hibernate Session,
    JDO PersistenceManager, etc.
  > Manages persistence context
     > Both transaction-scoped and extended persistence contexts




                                                             42
Persistence Focus: O/R Mapping
• Ease-of-use facility for Java developers mapping
  domain object model to a relational database
• Developer is aware of mapping between
  DB schema and domain object model
  > Developer is in control of mapping
  > Developer can rely on mapping and its semantics
• Mappings may be expressed using metadata
  annotations or XML
  > Default mappings provided



                                                      43
JPA – Entity Class
   import javax.persistence.*;

   @Entity
   public class Person {
      @Id private String name;
      private int visits;

       public Person() { }

       public Person(String name) {
          this.name = name;
       }

       public int incrementVisit() {
          return visits++;
       }
   }
                                       44
Persistence Entity Example (Contd.)
 ...


 // Relationship between Customer and Orders
 @OneToMany
 public Collection<Order> getOrders() {
   return orders;
 }
 public void setOrders(Collection<Order> orders) {
   this.orders = orders;
 }


                                                45
Persist Operation
public Order createNewOrder(Customer customer) {
  // Create new object instance – transient state
  Order order = new Order(customer);

  // Transitions new instances to managed. On the
  // next flush or commit, the newly persisted
  // instances will be inserted into the database table.
  entityManager.persist(order);
  return order;


                                                46
Find and Remove Operations
public void removeOrder(Long orderId) {
  Order order =
      entityManager.find(Order.class, orderId);

    // The instances will be deleted from the table
    // on the next flush or commit. Accessing a
    // removed entity has undefined results.
    entityManager.remove(order);
}

                                                 47
Persistence DEMO




                   48
JavaEE Tour

Petr Blaha
Sun Microsystems, Inc


                        49

Intro in JavaEE world (TU Olomouc)

  • 1.
    JavaEE Tour Petr Blaha SunMicrosystems, Inc 1
  • 2.
    Agenda • Java World introduction • JavaEE (Why to use this technology, APIs) • Dive in Enterprise Java Beans • Demo • Q&A 2
  • 3.
    Java • First implementationreleased in 1995 (1.1) • Java compiled to bytecode -> JVM • Basic Philosophy > Object-oriented > Platform independent > Automatic memory management • Current version 6 3
  • 4.
    The Java™ Platform multipleconfigurations built for different types Java Technology Java Technology Workgroup High-End Enabled Devices Enabled Desktop Server Server 4
  • 5.
    The Java TM Platform Java 2 Platform Micro Edition (JavaMETM) Optional Packages Optional Packages Personal Personal Java 2 Java 2 Basis Profile Profile Enterprise Standard Edition Edition Foundation Profile MIDP (JavaEE) (JavaSE) Java CDC CLDC Card APIs JVM KVM CardVM * Under development in JCP 5
  • 6.
    What Is theJavaEE?  Open and standard based platform for  developing, deploying and managing  n-tier, Web-enabled, server-centric, and component-based enterprise applications 6
  • 7.
    Evolution of EnterpriseApplication Development Frameworks 7
  • 8.
    Single Tier (Mainframe-based) •Dumb terminals are directly connected to mainframe • Centralized model (as opposed distributed model) • Presentation, business logic, and data access are intertwined in one monolithic mainframe application 8
  • 9.
    Single-Tier: Pros &Cons • Pros: > No client side management is required > Data consistency is easy to achieve • Cons: > Functionality (presentation, data model, business logic) intertwined, difficult for updates and maintenance and code reuse 9
  • 10.
    Two-Tier SQL request Database SQL response • Fat clients talking to back end database > SQL queries sent, raw data returned • Presentation,Business logic and Data Model processing logic in client application 10
  • 11.
    Two-Tier • Pro: > DB product independence (compared to single-tier model) • Cons: > Presentation, data model, business logic are intertwined (at client side), difficult for updates and maintenance > Data Model is “tightly coupled” to every client: If DB Schema changes, all clients break > Updates have to be deployed to all clients making System maintenance nightmare > DB connection for every client, thus difficult to scale > Raw data transferred to client for processing causes high network traffic 11
  • 12.
    Three-Tier (RPC based) SQL RPC request request Database RPC response SQL response • Thinner client: business & data model separated from presentation > Business logic and data access logic reside in middle tier server while client handles presentation • Middle tier server is now required to handle system services > Concurrency control, threading, transaction, security, persistence, multiplexing, performance, etc. 12
  • 13.
    Three-tier (RPC based):Pros & Cons • Pro: > Business logic can change more flexibly than 2-tier model > Most business logic reside in the middle-tier server • Cons: > Complexity is introduced in the middle-tier server > Client and middle-tier server is more tightly- coupled (than the three-tier object based model) > Code is not really reusable (compared to object model based) 13
  • 14.
    Three-Tier (Web Server) SQL HTML request WEB request Server Database HTML response SQL response • Browser handles presentation logic • Browser talks Web server via HTTP protocol • Business logic and data model are handled by “dynamic contents generation” technologies 14
  • 15.
    Three-tier (Web Serverbased): Pros & Cons • Pro: > Ubiquitous client types > Zero client management > Support various client devices > J2ME-enabled cell-phones • Cons: > Complexity in the middle-tier still need to be addressed 15
  • 16.
    Trends • Moving fromsingle-tier or two-tier to multi- tier architecture • Moving from monolithic model to object- based application model • Moving from application-based client to HTML-based client 16
  • 17.
    Outstanding Issues &Solution • Complexity at the middle tier server still remains • Duplicate system services still need to be provided for the majority of enterprise applications > Concurrency control, Transactions > Load-balancing, Security > Resource management, Connection pooling • How to solve this problem? > Commonly shared container that handles the above system services > Proprietary versus Open-standard based 17
  • 18.
    Proprietary Solution • Use"component and container" model > Components captures business logic > Container provides system services • The contract between components and container is defined in a well-defined but with proprietary manner • Problem of proprietary solution: Vendor lock-in • Example: Tuxedo, .NET 18
  • 19.
    Open and StandardSolution J2EE • Use "component and container" model in which container provides system services in a well- defined and as industry standard • JavaEE is that standard that also provides portability of code because it is based on Java technology and standard-based Java programming APIs 19
  • 20.
    J2EE is End-to-EndSolution Firewall J2EE Application Client Server Enterprise Enterprise Information JavaBeans™ Client Systems (EIS): Client Relational Database, Web Enterprise Legacy Client Server JavaBeans Applications, JSP, ERP Systems Servlets Client HTML/XML Other Services: JNDI, JMS, Enterprise Client Middle JavaMail™ Information Tier Tier Tier 20
  • 21.
  • 22.
    J2EE 1.4 APIsand Technologies • J2SE 1.4 • Servlet 2.4 • JAX-RPC • JSP 2.0 • Web Service for J2EE • EJB 2.1 • J2EE Management • JAXR • J2EE Deployment • Connector 1.5 • JMX 1.1 • JACC • JMS 1.1 • JAXP 1.2 • JTA 1.0 • JavaMail 1.3 • JAF 1.0 22
  • 23.
    The J2EE Challenge TM • J2EE is enormously powerful > The industry standard for robust enterprise apps • But that power sometimes gets in the way > Too difficult to get started > Even simple apps need boring boilerplate • Can we keep the power, but make typical development tasks simpler? • YES: and that is the focus of Java EE 5! 23
  • 24.
    EoD Improvements inJava EE 5 TM • POJO-based programming > More freedom, fewer requirements • Extensive use of annotations > Reduced need for deployment descriptors • Resource Injection > Inversion of control • New APIs and frameworks 24
  • 25.
    Annotations in JavaEE 5 TM • Making extensive use of annotations > For defining and using web services > To map Java classes to XML > To greatly simplify EJB development > To map Java classes to databases > To specify external dependencies > To reduce need for deployment descriptors 25
  • 26.
    Java EE 5Major Features TM • Simplified web services support • More web service standards support • Greatly simplified EJBTM development • New persistence API • Easy web applications with JavaServerTM Faces 26
  • 27.
    Java EE 5Platform • JSR 220 (EJB 3.0) • JSR 224 (JAX-WS 2.0) • JSR 222 (JAXB 2.0) • JSR 252 (JavaServer Faces 1.2) • JSR 52 (JSTL 1.1) • JSR 181 (WS Annotations) • JSR 245 (JSP 2.1) 27
  • 28.
  • 29.
    What is EJBTechnology? • A server-side component technology • Easy development and deployment of Java technology-based application that are: > Transactional, distributed, multi-tier, portable, scalable, secure, … 29
  • 30.
    Why EJB Technology? •Leverages the benefits of component-model on the server side • Separates business logic from system code > Container provides system services • Provides framework for portable components > Over different J2EE-compliant servers > Over different operational environments • Enables deployment-time configuration > Deployment descriptor 30
  • 31.
  • 32.
    Enterprise JavaBeans Enterprise JavaBeans Synchronous communication Asynchronous communication Session Bean Entity Bean Message-Driven Bean Stateless Stateful 32
  • 33.
    EJB 2.1 Example //EJB 2.1 public class PayrollBean implements javax.ejb.SessionBean { SessionContext ctx; DataSource empDB; public void setSessionContext(SessionContext ctx) { this.ctx = ctx; } public void ejbCreate() { Context initialContext = new InitialContext(); empDB = (DataSource)initialContext.lookup( “java:comp/env/jdbc/empDB”); } 33
  • 34.
    EJB 2.1 Example //EJB 2.1 (cont.) public void ejbActivate() {} public void ejbPassivate() {} public void ejbRemove() {} public void setBenefitsDeduction (int empId, double deduction) { ... Connection conn = empDB.getConnection(); ... } ... } // NOTE deployment descriptor needed 34
  • 35.
    EJB 2.1 Example <session> <ejb-name>PayrollBean</ejb-name> <local-home>PayrollHome</local-home> <local>Payroll</local> <ejb-class>com.example.PayrollBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> <resource-ref> <res-ref-name>jdbc/empDB</res-ref-name> <res-ref-type>javax.sql.DataSource</res-ref-type> <res-auth>Container</res-auth> </resource-ref> </session> ... <assembly-descriptor> ... </assembly-descriptor> 35
  • 36.
    Bean Classes •In EJB 3.0, session beans, message-driven beans are ordinary Java classes > Container interface requirements removed > Bean type specified by annotation or XML • Annotations > @Stateless, @Stateful, @MessageDriven > Specified on bean class 36
  • 37.
    EJB 3.0 Example //Same example, EJB 3.0 @Stateless public class PayrollBean implements Payroll { @Resource DataSource empDB; public void setBenefitsDeduction (int empId, double deduction) { ... Connection conn = empDB.getConnection(); ... } ... } 37
  • 38.
    Dependency Injection • Annotations > @EJB > References to EJB business interfaces > References to Home interfaces (when accessing EJB 2.1 components) > @Resource > Almost everything else > Number of annotations is simplified from EJB 3 specification early draft • Injection can also be specified using deployment descriptor elements 38
  • 39.
    EJB 3.0 ClientExample // EJB 3.0 client view @EJB ShoppingCart myCart; ... Collection widgets = myCart.startToShop(“widgets”); ... 39
  • 40.
    EJB 3.0 &Persistence 40
  • 41.
    Persistence Model inEJB 3.0 • Entities are simple Java classes > Concrete classes—support use of new > Getter/setter “property” methods or persistent instance variables > No required bean interfaces > No required callback interfaces • Usable as “detached” objects in other application tiers > No more need for DTOs • Single API in JavaEE, Java SE 41
  • 42.
    EntityManager • EntityManager servesas untyped “home” for entity operations > Methods for lifecycle operations > Persist, remove, merge, flush, refresh, etc. > Similar in functionality to Hibernate Session, JDO PersistenceManager, etc. > Manages persistence context > Both transaction-scoped and extended persistence contexts 42
  • 43.
    Persistence Focus: O/RMapping • Ease-of-use facility for Java developers mapping domain object model to a relational database • Developer is aware of mapping between DB schema and domain object model > Developer is in control of mapping > Developer can rely on mapping and its semantics • Mappings may be expressed using metadata annotations or XML > Default mappings provided 43
  • 44.
    JPA – EntityClass import javax.persistence.*; @Entity public class Person { @Id private String name; private int visits; public Person() { } public Person(String name) { this.name = name; } public int incrementVisit() { return visits++; } } 44
  • 45.
    Persistence Entity Example(Contd.) ... // Relationship between Customer and Orders @OneToMany public Collection<Order> getOrders() { return orders; } public void setOrders(Collection<Order> orders) { this.orders = orders; } 45
  • 46.
    Persist Operation public OrdercreateNewOrder(Customer customer) { // Create new object instance – transient state Order order = new Order(customer); // Transitions new instances to managed. On the // next flush or commit, the newly persisted // instances will be inserted into the database table. entityManager.persist(order); return order; 46
  • 47.
    Find and RemoveOperations public void removeOrder(Long orderId) { Order order = entityManager.find(Order.class, orderId); // The instances will be deleted from the table // on the next flush or commit. Accessing a // removed entity has undefined results. entityManager.remove(order); } 47
  • 48.
  • 49.
    JavaEE Tour Petr Blaha SunMicrosystems, Inc 49