Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Building reliable distributed systems J2EE and JBoss Clustering Giorgia Lodi [email protected] Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Outline • J2EE specification • An introduction to JBoss application server – JBoss 5.x architecture – How to install and run it • The JBoss Clustering Service – The clustering framework – Automatic discovery of clustered nodes • How JBoss uses JGroups for group communication – Distributed cluster-wide hot deployment – HA-JNDI – Fail-over and load balancing • At RMI • At HTTP – Clustering Enterprise Java Beans Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Java 2 Enterprise Edition • J2EE technology provides a component-based approach to the design, development, assembly and deployment of enterprise applications • J2EE offers a multi-tiered distributed application model – The ability to reuse components – Integrated eXtensible Markup Language (XML)-based data interchange – A unified security model – Flexible transaction control Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Distributed Multi-tiered Applications • J2EE application logic is divided into components according to function – Application components • can be installed on different machines depending on the tier in the multi-tiered J2EE environment • Four tiers – Client-tier – Web-tier – Business tier – Enterprise information system (EIS)-tier Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Distributed Multi-tiered Applications Client tier! Application Client! Web tier! Business tier! EIS tier! Browser! Facelet/JSP/ Servlet! Enterprise Beans! DB! Client machine! J2EE Server machine! Enterprise Beans! DB! Database Server machine! Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE containers • Runtime environments – They host application components • Application components – use their protocols and methods for interacting with other components and platform services – never interact directly with other J2EE components • Provide the required middleware services to the application components they host – A federated view of the underlying J2EE APIs Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Types of containers • Different containers depending on the kind of application component they host – Application client container – Applet container • manages the execution of applets. Consists of a Web browser and Java Plug-in running on the client together – Web container • manages the execution of JSP page and servlet components for J2EE applications – Enterprise JavaBeans (EJB) container • manages the execution of enterprise beans for J2EE applications Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE components • A J2EE component is a functional software unit • Five types of components: – Application clients – Web clients – Java Servlet – JavaServer Pages (JSP) – JavaServer Faces (JSF) – Enterprise Java Beans (EJBs) • J2EE components written in Java and compiled in the same way as any program in Java • J2EE components are assembled into a J2EE application and deployed to production Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Application clients • Run on a client machine • Exhibit a graphical user interface (GUI) – Swing or Abstract Window Toolkit (AWT) APIs – command-line interface • They may directly access enterprise beans running on the business tier • They may communication with a servlet running on the Web tier by opening a HTTP connection Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Web Clients and Applets • Web pages (HTML,XML…) generated by Web Components • Web browser – it renders the pages received from the server • Sometimes called thin clients Applets • Small client applications written in Java – execute in the JVM installed in the Web browser • Necessary – Java Plug-in and security policy file in order to successfully execute the applet in Web browsers Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Web Components: Servlets • Java objects that dynamically process requests and construct responses – Serve as a HTTP-aware middle layer that resides on the server side • They know how to communicate with both the clients, in HTTP, and EJBs with Remote Method Invocation (RMI) – Typically take a HTTP request as input, parse its data, perform some logic, and then construct a response to the client – They are not scripts; the HTML part is embedded inside the Java code • response.write(“<html> <body> Hello Guys!! </ body></html>”); Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Web Components: Servlets • The javax.servlet and the javax.servlet.http provide interfaces and classes for writing servlets • When implementing a generic service – use the GenericServlet class provided with the Java Servlet API • When handling HTTP-specific services – use the HttpServlet class • provides methods such as doGet and doPost Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Servlet life cycle • Controlled by the Web container • When a request is mapped to a servlet, the container performs the following steps – If an instance of the servlet does not exist • Loads the servlet class • Instantiates an instance of the servlet class • Initializes the servlet instance by calling the init method – Invokes the service method, passing a request and response object • Service method can be the service method of the GenericServlet or a doMethod (e.g., doGet, doPost) of the HTTPServlet Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Servlet Example public class MyServlet extends HTTPServlet { ……… public void init(ServletConfig config) throws ServletException { super.init(config); System.out.println(“Servlet initialized”) } public void destroy() { super.destroy(); System.out.println(“Servlet destroyed”); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ………… } } Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Web Components: Java Server Pages (JSP) • Text-based documents – allow developers to create Web contents with both static and dynamic components • static content expressed in any text-based format (HTML, XML …) • dynamic content constructed by JSP elements • Provide a more natural approach to creating static contents • HTML pages with special embedded JSP tags – tags can contain Java code • NO Java classes – files with .jsp extension (they are not compiled like common Java programs) Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Java Server Pages (JSP) • A JSP engine parses the .jsp and creates a Java servlet source file (translation) – The source file is then compiled into a class file (compilation) • Both the translation and compilation phases can yield errors – If an error occurs while the page is being translated (e.g., if the translator encounters a malformed JSP element) • The server returns a ParseException and the servlet class source file is empty or incomplete – If an error occurs while the JSP page is being compiled (e.g., due to a syntax error in a scriptlet tag) • The server returns a JasperException Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JSP Example <html> <head> <title> My JSP Example </title> </head> <body> JSP Hello word <br><br> <%! public String writeThisTest() { String testToWrite=“Hello Guys!!”; return testToWrite; } %> <br> <%= writeThisTest() %> </body> </html> Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JavaServer Faces • Based on Facelets – Facelets is a powerful but lightweight page declaration language that is used to build JavaServer Faces views – Facelets views are usually created as XHTML pages • In a typical JavaServer Faces application, each page of the application connects to a backing bean – A type of managed bean • Annotation @ManagedBean • A constructor and get and set methods Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Business Components • The Enterprise Java Beans (EJBs) of the J2EE specifications • Handle the business code – i.e. the logic that meets the needs of a business domain • Retrieve data from J2EE clients, process it and send it to the EIS tier (and vice versa) • Three kinds of EJBs (in old J2EE specifications) – Session Beans – Entity Beans – Message Driven Beans • New J2EE specification – Entity Beans have been deprecated Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE applications • J2EE applications packaged in Enterprise Archive (EAR) files – EAR files are standard Java Archive (JAR) files with .ear extension • The EAR file contains J2EE modules – J2EE modules (four types) • one or more J2EE components for same container type • a component Deployment Descriptor (DD) for that type Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE modules • EJB module – contains .class files for EJBs and an EJB DD – EJB module packaged as JAR file (.jar extension) • Web module – contains JSP files, .class files for servlet, HTML files and a Web DD – Web module packaged as JAR file with .war extension • Resource adapter module – contains Java interfaces, classes and libraries and the resource adapter DD – Resource adapter module packaged as JAR file (.rar extension) • Application client module – contains .class files and an application client DD – Application client module packaged as JAR file (.jar extension) Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Deployment Descriptors (DDs) • A XML document – describes a component’s deployment settings (e.g. transactional information, database mapping, security roles) • Used to inform the container about how to manage the bean and its life cycle • Can be changed without modifying the bean source code – it contains declarative information – at run time the J2EE server reads the DD and acts upon the component accordingly • Different DDs depending on the J2EE modules Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica DD example <?xml version=“1.0” encoding=“UTF-8”?>! <ejb-jar>! <description>Entity Bean Example </description>! <display-name>Entity Beans</display-name>! <enterprise-beans>! <!-- Entity Beans -->! <entity>! <display-name>Container Managed Persistence Player</displayname>! <ejb-name>CMPPlayer</ejb-name>! <home>entity.ejb.PlayerHome</home>! <remote>entity.ejb.Player</remote>! <ejb-class>entity.ejb.CMPPlayerBean</ejb-class>! <prim-key-class>java.lang.String</prim-key-class>! <primkey-field>playerId</primkey-field>! <cmp-field><field-name>name</field-name></cmp-field>! …! </entity> …! Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE middleware services • Robust suite of middleware services – the services rely on the Java 2 Standard Edition (J2SE) Technologies included in J2EE • Enterprise Java Beans (EJBs) – Defines how server-side components are written • Java Servlets and Java Server Pages (JSPs) Java ServerFaces (JSF) – Defines and manages servlets JSPs Facelets • Java Remote Method Invocation (RMI) and RMI-IIOP – RMI allows for inter-process communication – RMI-IIOP is a portable extension of RMI that uses the InternetInter-ORB Protocol (IIOP) for CORBA integration Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE middleware services • HTTP – HTTP client-side API defined in the package java.net – HTTP server-side API defined by servlets and JSPs interfaces – HTTPs: HTTP over SSL • Java DataBase Connectivity (JDBC) – It is a relational database bridge that allows developers to invoke SQL commands from Java methods – Generally used by EJBs but even servlet or JSP page can use it to access the database directly – Composed by two parts: an application-level interface used by applications for accessing database and a service provider interface to attach JDBC drivers to the J2EE platform • Java Message Service (JMS) – It allows application components to create, send, receive and read messages – It enables distributed communication that is loosely coupled, reliable, and asynchronous Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE middleware services • Java Naming and Directory Interface (JNDI) – provides methods for associating attributes with objects, searching for objects using attributes – independent of any specific implementations • JNDI used to access multiple naming and directory services (e.g. LDAP, DNS, NIS…) • Java Transaction API (JTA) – provides methods for managing transactions (e.g. begins, rollbacks, commits) • JavaMail – Used to send e-mail notifications Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE middleware services • Java API for XML Processing (JAXP) – supports the processing of XML documents using either Document Object Model (DOM) or Simple API for XML Parsing (SAX) – enables applications to parse and transform XML documents • Java Authentication and Authorization Service (JAAS) – provides a way for J2EE application to authenticate and authorize a specific user or group of users to run it Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE middleware services • Web Service management – provides support for both web service clients and web service endpoints – includes • Java API for XML-RPC (JAX-RPC): supports for web services calls using the SOAP/HTTP protocol • SOAP with Attachments API for Java (SAAJ): provides support for manipulating low-level SOAP messages • Web Services – defines the deployment of web services clients and web service endpoints – Defines the implementation of web service endpoints using enterprise beans • Java API for XML Registries (JAXR): provides client access XML registry servers (UDDI) – NEW: Restful web services Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE middleware services • J2EE Connector Architecture (JCA) – used by tools vendors and system integrators to create resource adapters • resource adapters are software components that allow J2EE components to access and interact with enterprise information systems, plugged into any J2EE product • resource adapters are useful to manage details of middleware integration to existing systems • Java IDL – sun Microsystem’s Java-based implementation of CORBA – allows for integration with other languages (J2EE fully compatible with CORBA) Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE overall architecture …! Web Container! EJB Container! J2SE! Java MAIL! JNDI! JTA! JCA! Application client container! JDBC! J2SE! JMX! J2EE Server! Java MAIL! JNDI! JNDI! J2SE! JTA! JCA! Web Srvcs! JMS! SAAJ! JAXR! JAXRPC! Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE application example Web tier [Servlets/ JSPs/JSF] H T T P customer H T T P S browse select secure purchase J2EE Server Business tier [EJBs] catalog J D Book B Shopping order C cart Java Mail Mail server Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Types of EJBs • In the past, 3 types of EJBs – Session Beans • Associated to a client • Represent business interactions – Entity Beans • Persistent • Represent business objects – Message Driven Beans • Act as an entry points for asynchronous messages • No interfaces defined, only bean class • Today – Only Session Beans – Message Driven Bean Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Session Beans • Useful for describing interactions with clients • They do not represent shared data in the database but they can access shared data • In the past two types of Session Beans: – Stateless Session Beans • They do not maintain state across method invocations • Examples: credit card verifier – Stateful Session Beans • Dedicated to one client for the life of the bean instance • Act as client agents: retain state on behalf of the client • Example: checking account balance • Today – Singleton Session Beans • Instantiated once per application and exist for the lifecycle of the application • Offer similar functionality to stateless session beans – However only one singleton session bean per application, as opposed to a pool of stateless session beans • Maintain their state between client invocations but are not required to maintain their state across server crashes or shutdowns. Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica When to use Session Beans • Stateful session beans are appropriate if – A specific interaction between the bean and a client – The bean needs to hold information about the client across method invocations – The bean mediates between the client and the other components of the application, presenting a simplified view to the client • Stateless session beans are appropriate if – You want to improve performance – The bean’s state has no data for a specific client – In a single method invocation, the bean performs a generic task for all clients – The bean implements a web service • Singleton session beans are appropriate if – State needs to be shared across the application – A single enterprise bean needs to be accessed by multiple threads concurrently – The bean implements a web service Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Entity Beans • Represent business objects in a persistent storage – e.g., accounts, orders, customers • They model data – object oriented view of a database • Have a primary key – Each entity bean may be retrieved in much the same manner you search records with a primary key in a database • Can be shared by multiple clients – As they are persistent and reachable by any client • they suffer from all the same types of problems associated with concurrent access of a shared resource • Deprecated – New Persistence API in J2EE 6 specifications Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Message Driven Beans (MDBs) • Can consume and process messages – designed to consume messages from topics or queues • Act as a JMS message listener – they implement only one method onMessage() • Process only JMS messages (EJB 2.0) • A message-driven bean’s instances retain no data or conversational state for a specific client • All instances of a message-driven bean are equivalent – this allows the EJB container to assign a message to any message-driven bean instance • The container can pool these instances to allow streams of messages to be processed concurrently. When to use them • To receive messages asynchronously • When consuming JMS messages – impossible to write session or entity beans that respond to JMS messages Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Persistence • No persistence for Stateless Session Beans and Message Driven Beans • Stateful Session Beans can be passivated – the state is defined by Java Serialization • Entity Beans are persistent – In the past, two types of persistence • Bean Managed Persistence (BMP) • Container Managed Persistence (CMP) • EJBQL query language – Today, Java Persistent API • Java Persistence Query Language (JPQL) Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Entity Relationships • Support – One-to-one • Each entity instance is related to a single instance of another entity – One-to-many • An entity instance can be related to multiple instances of the other entities – Many-to-one • Multiple instances of an entity can be related to a single instance of the other entity – Many-to-many • The entity instances can be related to multiple instances of each other • There exist specific Java Annotation that can be used to specify a relationship – Es: @OneToMany Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Transactions • Container Managed Transactions (CMT) – Managed automatically by the EJB Container – No use of API – In DD the beans and the methods involved in the transaction are specified – Supported by all bean types – The container • maps the transactions to DB transactions • begins a transaction immediately before an EJB’s method starts • commits the transactions just before the method exits – Each method is associated with a single transaction. Nested or multiple transactions are not allowed within a method Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Transactions • Bean Managed Transactions (BMT) – Managed by the bean developer – Supported by the Session Beans and the Message Driven Beans only – Developers must decide whether to use JDBC or JTA transactions N.B: Use them only when necessary!! Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Summary of EJB container responsibilities • Design of EJBs as single-threaded components (no worry about thread synchronization with concurrent client accesses) – EJB container instantiates multiple instances of components to serve concurrent client requests • Advantages: no need to worry about deadlock inside application code • EJB container uses management methods to alert beans when middleware events take place Client code! Enterprise ! Bean! Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Enterprise Java Beans (EJBs) version 3.0 Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica EJB 3.0 specification • The container does more work and the developers do less work compared to previous version 2.1 • Decreases the number of programming artifacts for developers to provide • Reduces the complexity of the entity bean programming model Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica EJB 3.0: advantages • Fewer number of classes and interfaces – In old specification two interfaces were required for EJBs • Home interface • Component interface – In the new specification • POJO/POJI-based components – Abstract bean classes replaced with Plain Old Java Objects (POJOs) – Component and Home interfaces replaced with Plain Old Java Interfaces (POJIs) » Interfaces are optional Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica EJB 3.0: advantages • Deployment descriptors are optional – Use of Java metadata annotations • Simplification of APIs for accessing bean’s environment – JNDI lookups are no longer necessary • New persistence APIs Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Annotations • Metadata – Additional definition that can be attached to an element within the code in order to further characterize it – Can be applied to methods, variables, constructors, package declarations, and so on – Begin with @ sign followed by the annotation name • Annotation name may be followed by annotation data – EJB 3.0 has defined annotations for use in EJB development • The specification has also defined metadata to annotate deployment information within the code Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Deployment Descriptor: optional • Deployment descriptors are redundant as developers can use annotations in lieu of them • Deployment metadata can be included in the EJB code – At deployment time, the metadata can be used to provide the appropriate behaviour to the bean • Remember: they are optional – The bean developer can • Put all the deployment information in deployment descriptors • Distribute deployment information across the bean class and the deployment descriptor • Use only annotations • Deployment descriptors override annotations Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Simplifying APIs access • Client applications for EJB 2.1 obtain a reference to entity and session bean objects using the JNDI name • EJB 3.0 clients obtain them using annotations Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica From 2.1 to 3.0: interfaces //Remote Interface EJB 2.1 BookCatalog.java import java.rmi.RemoteException; import javax.ejb.EJBObject; public interface BookCatalog extends EJBObject { public String getEdition(String title) throws RemoteException; } //Home Interface EJB 2.1 BookCatalogHome.java import java.rmi.RemoteException; import javax.ejb.EJBObject; import javax.ejb.CreateException; public interface BookCatalogHome extends EJBHome { public BookCatalog create() throws RemoteException, CreateException; } // EJB 3.0 BookCatalog.java import javax.ejb.Remote @Remote public interface BookCatalogRemote { public String getEdition (String title); } Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica 2.1 bean class // BookCatalogBean.java import javax.ejb.SessionBean; import javax.ejb.SessionContext; public class BookCatalogBean implements SessionBean { private SessionContext ctx; public String getEdition(String title){ if(title.equals("Java & XML")) return new String("2nd edition"); if(title.equals("Java and XSLT")) return new String("1st edition"); } public void ejbCreate(){} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext ctx) {this.ctx=ctx;}} Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica 3.0 Bean Class //BookCatalogBean.java EJB 3.0 Session Bean import javax.ejb.Stateless @Stateless public class BookCatalogBean implements BookCatalogRemote { public BookCatalogBean() {} //Constructor with no args public String getEdition(String title){ if(title.equals("Java & XML")) return new String("2nd edition"); if(title.equals("Java and XSLT")) return new String("1st edition"); }} Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Alternatively…. //BookCatalogBean.java EJB 3.0 Session Bean import javax.ejb.Stateless @Stateless @Remote public class BookCatalogBean { public String getEdition(String title){ if(title.equals("Java & XML")) return new String("2nd edition"); if(title.equals("Java and XSLT")) return new String("1st edition"); } Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica 2.1 deployment descriptor <?xml version="1.0"?> <!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'> <ejb-jar> <enterprise-beans> <session> <ejb-name>BookCatalogEJB</ejb-name> <jndi-name>ejb/BookCatalog</jndi-name> <home>BookCatalogHome</home> <remote>BookCatalog</remote> <ejb-class>BookCatalogBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> </session> </enterprise-beans> </ejb-jar> Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica 3.0 deployment descriptor • I do not need it! Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Client accessing 2.1 session bean import javax.naming.InitialContext; public class BookCatalogClient { public static void main(String[] argv){ try { InitialContext ctx=new InitialContext(); BookCatalogHome catalogHome = (BookCatalogHome) ctx.lookup(”ejb/BookCatalog"); BookCatalog catalog = (BookCatalog) catalogLocalHome.create(); String title="Java and XML"; String edition = catalogLocal.getEdition(title); System.out.println("Edition for Title: ” + title + " " + edition); }catch(Exception e){}}} Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Client accessing 3.0 session bean public class BookCatalogClient { @Inject BookCatalogBean; BookCatalogBean catalogBean; String title="Java and XML"; String edition=catalogBean.getEdition(edition); System.out.println("Edition for Title: " + title + " " + edition); } Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Other types of injections • @EJB – Used to inject in particular EJB stubs – @EJB public BookCatalogBean catalogBean; • @Resource – Used to inject dependencies on resources in general Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica 2.1 entity bean import javax.ejb.*; public abstract class BookBean implements EntityBean { private String title; private String author; public public public public abstract abstract abstract abstract String getTitle(){return title;} void setTitle(String title){this.title=title;} void setAuthor(String author){this.author=author;} String getAuthor(){return author;}} public String ejbCreate(String title,String author) throws javax.ejb.CreateException { setTitle(title); setAuthor(author); return null; } //other ejb life cycle methods } Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Accessing entity instances in EJB 3.0 • javax.persistence.EntityManager API is used for creating, finding, updating and deleting entity instances • You can inject an instance of EntityManager in a session bean and use persist or find method to create or query entity bean objects Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica 3.0 Entity import javax.persistence.*; @Entity @Table(name=“BOOK”) @NamedQuery(name="findByAuthor", queryString = "SELECT DISTINCT OBJECT(obj) FROM Book obj WHERE obj.author = ?1") public class BookBean implements java.io.Serializable { private String title; private String author; public BookBean(){} public BookBean(String title){this.title=title; } @Id @Column(name=“title”) (use @GeneratedValue if you want the container to manage the auto increment of primary keys) public String getTitle(){return title;} public void setTitle(){this.title=title;} @Column(name=“author”) public void setAuthor(String author){this.author=author;} public String getAuthor(){return author;} } Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Accessing entity instances in EJB 3.0: an example … @PersistenceContext private EntityManager em; private BookBean bb; public BookBean findByPrimaryKey(String title) { return ((BookBean) em.find(BookBean.class,title)); } public BookBean finderAuthor (String auth) { return (BookBean) em.createNamedQuery(“findByAuthor”) .setParameter(1, auth).getSingleResult(); } public void createBook(String title, String author) { if (bb == null) bb = new BookBean(); bb.setTitle(title); bb.setAuthor(author); em.persist(bb); }… Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Persistence deployment descriptor • It is called persistence.xml • It is included in the META-INF directory • It looks like <persistence> <persistence-unit name="manager1"> <jta-data-source>java:/DefaultDS</jta-data-source> <provider>org.hibernate.ejb.HibernatePersistence< /provider> <properties> <property name="hibernate.dialect” value="org.hibernate.dialect.MySQLDialect"/> </properties> </persistence-unit> </persistence> Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica J2EE application servers • Middleware platforms that implement the J2EE specifications – Open source • JBoss (JBoss group) • JOnAS (ObjectWeb consortium) • Geronimo (Apache Software Foundation) – … – Commercial • BEA Web Logic • IBM WebSphere – … – Other component-based technologies • Corba Component Model (CCM) • Microsoft .Net • The most popular open-source application server is JBoss – Many versions available • • • • • 3.x 4.x 5.x 6.0 7.0 Beta Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JBoss 4.x Application Server • Collection of middleware services for communication, persistence, transactions, security, and clustering • Services interoperate by means of a microkernel, i.e., Java Management eXtension (JMX) – JMX provides Java developers with a common software bus • Allows them to integrate components (e.g., modules, containers) – Components are declared as Managed Beans (MBeans) services • Implementation of manageable resources in JBoss • Represented by Java objects that expose interfaces • Consisting of methods to be used for invoking the MBeans Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JBoss 5.x Application Server • It uses the microcontainer – It is a refactoring of JBoss's JMX Microkernel to support direct Plain Old Java Object (POJO) deployment and standalone use outside the JBoss application server – It allows the application server to integrate enterprise services with a Servlet/JSP and EJB containers, deployers and management utilities in order to provide a standard Java EE environment • If you need additional services – simply deploy these on top of Java EE to provide the functionality you need – Since it is very lightweight and deals with POJOs it can be also used to deploy services into a Java ME runtime environment • New possibilities for mobile applications to take advantage of enterprise services without requiring a full J2EE application server Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JBoss 5.x Application Server Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JBoss Installation • You should have already installed java J2DK (latest versions) • Set the JAVA_HOME to point where java is installed • Download the JBoss Application server – You can download the src code and build it • jboss-XXX-src.tar.gz – You can download the software already built (unzip the file) • jboss-XXX.zip Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica How to run and shutdown JBoss Run • cd jboss-XXX/bin – ./run.sh (under Linux) or run.bat (under Windows) • You are running the default server • There exist three server confs: – Minimal • starts the core server container without any of the enterprise services – Default • all the basic services of the J2EE specifications – All • default conf + IIOP + clustering and load balancing services • New two configurations since JBoss AS 5 – Standard • Deployment isolation properties, specific juddi implementation, … – Web • New experimental lightweight configuration created around JBoss Web Shutdown • You can terminate the server by using ctrl-c Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JBoss Clustering Service Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Why Clustering? • It allows developers to run an application on several parallel servers while providing a single view to application clients • It is crucial for – Fault tolerance • If one or more servers fails, the application is still accessible via the surviving servers – Load Balancing • Load is distributed across different servers – Scalability • Performance can be improved by simply adding more nodes to the cluster and performing load balancing – Highly availability • The clustering infrastructure supports the redundancy needed for high availability • It is obtained through load balancing and fault tolerance as well Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Why JBoss Clustering? • Transparent – No stub re-compiling! – Client does not know about clustering – Cluster is maintained automatically – Modular/stack approach • Open source – No extra cost to activate clustering Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Overview of Clustering functionalities R1 R3 Failover Load Balancing R3 R2 R1 R3 R2 Public network Private network State Replication Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Running JBoss Clustering • Use JBoss’ “all” configuration – run.bat -c all – ./run.sh -c all • The “all” configuration contains everything needed for clustering – It has all the libraries for clustering • E.g., JGroups.jar, etc. Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Modular/stack approach JBossCache HA-Remoting Farming Messaging Hibernate Distributed State jBpm Entity SFSB HTTP Session HA-JNDI Distributed RPC, Membership HASingleton Distributed Replicant DRM Manager JGroups HAPartition Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Clustering divided in 3 parts • Cluster communication (inside cluster) – Based on JGroups – Method calls across all cluster nodes • HA-JNDI, Farming, etc… • Client-cluster communication – Formerly HA-RMI – Load balancing and failover logic for fat clients • State replication (inside cluster) – JBoss Cache • HTTP session, SFSBs, DistributedState Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Clustering divided in 3 parts • Cluster communication (inside cluster) – Based on JGroups – Method calls across all cluster nodes • HA-JNDI, Farming, etc… • Client-cluster communication – Formerly HA-RMI – Load balancing and failover logic for fat clients • State replication (inside cluster) – JBoss Cache • HTTP session, SFSBs, DistributedState Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Cluster definition • A JBoss cluster (or partition) consists of a set of nodes – Nodes communicate with each other and work toward a common goal – A node in JBoss is a JBoss server instance – More than one JBoss server instance can be deployed in one single machine • Pay attention to the service ports: they must be changed! Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JGroups Channels • Communication between nodes is handled by the JGroups group communication library • Two main components – Channel – Protocol stack • A JGroups Channel – Tracks who is in the cluster – Enables reliable exchanging of messages between the cluster members – JGroups channels with the same configuration and name dynamically discover each other and form a group – Nodes can be dynamically added to or removed from clusters at any time • by starting or stopping a Channel with a configuration and name that matches the other cluster members • In essence, a JBoss cluster is a set of AS server instances each of which is running an identically configured and named JGroups Channel Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JGroups Channels • On a same network, even for the same service, we may have different clusters – In order to differentiate them, each cluster must have an individual name Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JGroups Configuration • It is built on top of a stack of network communication protocols – Protocols provide transport, discovery, reliability and failure detection, and cluster membership management services Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JGroups Configuration in old JBoss versions • cluster-service.xml file in /deploy folder – Describes configuration for the default cluster partition • JGroups configurations appear as a nested attribute in cluster related MBean services • PartitionConfig attribute in the ClusterPartition MBean is an XML string – Describes and configures the JGroups stack of protocols – All the JGroups configuration data is contained in the <Config> element under the PartitionConfig attribute – Default configuration uses UDP with IP multicast • multicast identified by address and port number Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JGroups Configuration in old JBoss versions <mbean code="org.jboss.ha.framework.server.ClusterPartition" name="jboss:service= {jboss.partition.name:DefaultPartition}"> ... <attribute name="PartitionConfig"> <Config> <UDP mcast_addr="${jboss.partition.udpGroup:228.1.2.3}" mcast_port="${jboss.hapartition.mcast_port:45566}” tos="8” … … <PING timeout="2000" down_thread="false" up_thread="false" num_initial_members="3"/> <MERGE2 max_interval="100000” down_thread="false" up_thread="false" min_interval="20000"/> …… <FD timeout="10000" max_tries="5" down_thread="false" up_thread="false" shun="true"/> <VERIFY_SUSPECT timeout="1500" down_thread="false" up_thread="false"/> ……… <pbcast.STATE_TRANSFER down_thread="false" up_thread="false"/> … … Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JGroups configurations in new JBoss version • Cluster directory in /deploy folder – Describes configuration for the default cluster partition – It includes jgroups-channelfactory.sar which in turn embodies the xml configuration files of JGroups in the META-INF directory • jgroups-channelfactory-stacks.xml – with the JGroups stack configurations • jgroups-channelfactory-jboss-beans.xml – Defines the bean JChannelFactory and uses the previous file for the JGroups stack configuration – It includes the address used to determine the name node Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JGroups Channels • By default JBoss uses four separate JGroups Channels – Two broad categories • The Channel used by the general purpose HAPartition service • Three Channels created by JBoss Cache for special purpose caching and cluster wide state replication Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica HA Partition • HAPartition is a general purpose service used for a variety of tasks in AS clustering • It is an abstraction built on top of a JGroups Channel • It provides support for making/receiving RPC invocations on/from one or more cluster nodes • It supports a distributed registry of which clustering services are running on which cluster members • It provides notifications to interested listeners when the cluster membership changes or the clustered service registry changes • It is the core of many clustering services – – – – – smart client-side clustered proxies EJB 2 SFSB replication and entity cache management Farming, HA-JNDI, … Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica HA Partition: example <mbean code="org.jboss.ha.framework.server.ClusterPartition" name="jboss:service=DefaultPartition"> <! -- Name of the partition being built --> <attribute name="PartitionName"> ${jboss.partition.name:DefaultPartition}</attribute> <! -- The address used to determine the node name --> <attribute name="NodeAddress">${jboss.bind.address}</attribute> <! -- Determine if deadlock detection is enabled --> <attribute name="DeadlockDetection">False</attribute> <! -- Max time (in ms) to wait for state transfer to complete. Increase for large states --> <attribute name="StateTransferTimeout">30000</attribute> <! -- The JGroups protocol configuration --> <attribute name="PartitionConfig”>... ... </attribute> </mbean> Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica HA Partition • In order for nodes to form a cluster, they must have – the exact same PartitionName and the PartitionConfig elements • Changes to these elements on some nodes of the cluster but not all nodes would cause the cluster to split Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Types of deployments • JBoss’ staff recommends use of homogeneous deployment – Each application component replicated in all clustered nodes • Requests do not need to span on different nodes • Potentially, heterogeneous deployment is also allowed – Application components can span on different nodes • Not recommended for lack of distributed transaction manager for example in old JBoss versions • In new JBoss version a distributed transaction manager has been introduced Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Homogeneous deployment • Realized using JBoss farming service – application copied into JBoss /farm directory Node2 Node1 Copy .ear in /farm ear Node3 Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Clustering JNDI • The client obtains a HA-JNDI proxy object and invokes JNDI lookup services on the remote server through the proxy • On the server side, the HA-JNDI service maintains a cluster-wide context tree – The tree is always available as long as there is one node left in the cluster – Each node in the cluster also maintains its own local JNDI context tree Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Clustering JNDI Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Clustering JNDI • A remote client does a lookup through HA-JNDI – If the binding is available in the cluster-wide JNDI tree, return it – If the binding is not in the cluster-wide tree, delegate the lookup query to the local JNDI service and return the received answer if available – If not available, the HA-JNDI service asks all other nodes in the cluster if their local JNDI services own such a binding – If no local JNDI service owns such a binding, a NameNotFoundException is finally raised Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Clustering divided in 3 parts • Cluster communication (inside cluster) – Based on JGroups – Method calls across all cluster nodes • HA-JNDI, Farming, etc… • Client-cluster communication – Formerly HA-RMI – Load balancing and failover logic for fat clients • State replication (inside cluster) – JBoss Cache • HTTP session, SFSBs, DistributedState Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JBoss Clustering Configurations • Two types of clustering configurations – JBoss fat client clustering – JBoss thin client clustering Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JBoss Fat Client Clustering • Client uses smart proxies • HA smart proxy has logic inside – Load Balancing policies, e.g., RoundRobin – Failover capabilities • HA smart proxy logic can be pluggable – User can define his/her own logic • Failover policy • Load balancing based on weight or load Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JBoss Thin Client Clustering • Front end load balancing mechanism – Hardware • JBoss group suggests F5 BIG-IP – Software • Apache + JBossWeb – Apache mod_jk/mod_proxy – mod_cluster » This latter fully integrated in JBoss AS6 – Tomcat Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Fail-over and load balancing: RMI • RMI fail-over and load balancing (fat client clustering) – Clustering logic included into the client stubs (HA-RMI) – Stub contains the list of available clustered nodes + load balancing policy • Random • Round Robin • First Available – If cluster topology changes, next client invocation server piggybacks new list of target nodes • Works only on remote invocations – The list of target nodes is maintained automatically, using JGroups – The client stub • • • • receives a reply from the invoked server unpacks the list of target nodes from that reply updates the current list of target nodes with the received one terminates the client RMI Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Fail-over and Load Balancing: RMI Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica HA RMI: Interceptors • When the stub’s interface is invoked, the invocation is translated from a typed call to a de-typed call • The de-typed invocation is passed through a set of clientside interceptors • The load balancing and failover mechanisms are located in the last interceptor of the chain Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Fail-over and load balancing: RMI WEB Container EJB Containers JVM JBoss JVM RMI fail-over and load balancing are possible!! Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Fail-over and load balancing: RMI WEB Container EJB Containers JBoss JVM RMI Fail-over and load balancing do not apply!!! Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Clustering divided in 3 parts • Cluster communication (inside cluster) – Based on JGroups – Method calls across all cluster nodes • HA-JNDI, Farming, etc… • Client-cluster communication – Formerly HA-RMI – Load balancing and failover logic for fat clients • State replication (inside cluster) – JBoss Cache • HTTP session, SFSBs, DistributedState Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica JBoss Cache • JBoss Cache is a fully featured distributed cache framework that can be used standalone or in any application server environment – It caches frequently accessed Java objects in order to dramatically improve the performance of applications • it is easy to remove data access bottlenecks - such as connecting to a database • In JBoss, it provides cache services for – – – – HTTP sessions EJB 3.0 session beans EJB 3.0 entity beans Each cache service creates its own JGroups Channel • JBoss Cache is a cluster-aware cache; that is, state is always kept in sync with other servers in the cluster when there are concurrent updates – Any state stored in JBoss Cache is resilient to server crashes or restarts – It can either invalidate or update its state Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Fail-over and Load Balancing: HTTP • Session state replication handled by JBoss – in “all” JBoss conf included files for session state replication – configure HTTP session replication with JBoss Cache • Load balancing handled by external software or hardware components (thin client clustering) – typically use software components such as Apache+mod_jk – mod_cluster • Compared with the former mod_jk, mod_cluster accepts a dynamic configuration of httpd workers – This can be done through an advertise mechanism where all httpd workers communicate lifecycle events (like startup or shutdown) thus leveraging dynamic configuration of nodes Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Fail-over and Load Balancing: HTTP WEB Container EJB Containers WEB Container EJB Containers HTTP State replication JBoss JBoss JVM JVM Apache mod_jk Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Alternatively…. • If you use sticky sessions you do not need HTTP session replication • All requests coming from the same client are sent to the same node • In the example round robin policy is applied per-client JBoss Node 2 JBoss Node 1 R1 R2 R2 JBoss Node 3 R1 Apache mod_jk R1 R1 R2 Client 1 R2 Client 2 Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Sticky Session: Pros and Cons • Pros – You may disable HTTP session replication that is an expensive operation • All requests from the same clients are processed by the same server • Cons – If server that serves the requests fails, you loose your session state • It is a tradeoff and depends on the type of application you are deploying Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Hybrid solution: Sticky session and HTTP state replication • You may enable both sticky session and HTTP session replication – In case of server crash the client session is replicated in the remaining servers • Asynchronous vs synchronous HTTP replication – Synchronous: the application has to wait for the response until the state is replicated to all nodes of the cluster – In case you use sticky session, it may be better enabling an asynchronous HTTP replication that is more scalable • The application receives immediately the response and then the state is replicated to the nodes of the cluster • You can also specify the granularity of the replication for optimization purposes • Entire session • Modified attributes – More efficient than session granularity • Modified field – If size of the attribute is huge, replication of modified field is efficient Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica HTTP session replication: configuration • Session replication is enabled per web application in WEB-INF/web.xml – Add <distributable/> to your webapp • JBoss specific configurations (asynchronous vs synchronous replication) goes into WEB-INF/ jboss-web.xml • Session replication is configured in Tomcat deploy/tc5-cluster-service.xml ... <!-- Valid modes are LOCAL, REPL_ASYNC and REPL_SYNC ! --> <attribute name="CacheMode">REPL_SYNC</attribute> ... Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Hybrid: Thin and Fat Client Clustering WEB Container EJB Containers JBoss Apache mod_jk JVM WEB Container JVM EJB Containers JBoss JVM JVM Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Clustering EJBs • In general, you have to annotate your application in order to instruct the EJB container that the bean is clustered • Stateless Session Beans – As no state involved, calls can be load balanced on any node • Stateful Session Beans – It is necessary to manage the state • The states of all stateful session beans are replicated and synchronized across the cluster – Each time the state of a bean changes • JBoss Cache provides the session state replication for EJB 3.0 stateful session beans Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Clustering EJBs • Entity Beans – 2.x: do not use clustering • Introduces data synchronization problems – they do not have a distributed locking mechanism and a distributed cache – 3.0 • Entity bean clustering service deals with distributed caching and replication – Through JBoss Cache Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica Troubles • If you are not able to successfully run JBoss clustering, it does not mean that it does not work ! – Network issues (firewall, multicast disabled, etc.) – JGroups issues • JGroups comes with a handy set of Trouble Shooting tools Università di Roma “La Sapienza” Dipartimento di Informatica e Sistemistica References • Java EE 6 Tutorial available at http://download.oracle.com/ javaee/6/tutorial/doc/ • Bela Ban, “JBoss Clustering Overview”, 2006 • JBoss Application Server 4.x, Chapter 16. Clustering, “High Availability Enterprise Services via JBoss Clusters”, available online at – http://docs.jboss.org/jbossas/jboss4guide/r4/html/cluster.chapt.html • Brian Stansberry, Galder Zamarreno JBoss Application Server 5, “Clustering Guide”, November 2008 • Any other problem? www.google.com