EJB – Packaging Applications ”; Previous Next Requirement of Packaging applications using EJB 3.0 are similar to that of J2EE platform. EJB components are packaged into modules as jar files and are packaged into application enterprise archive as ear file. There are majorly three components of any enterprise application − jar − Java Application aRchive, containing EJB modules, EJB client modules and utility modules. war − Web Application aRchive, containing web modules. ear − Enterprise Application aRchive, containing jars and war module. In NetBeans, it is very easy to create, develop, package, and deploy the J2EE applications. In NetBeans IDE, select ,File > New Project >.Select project type under category,Java EE, Project type as Enterprise Application. Click Next > button. Enter project name and location. Click Finish > button. We”ve chosen name as EnterpriseApplicaton. Select Server and Settings. Keep Create EJB Module and Create Web Application Module checked with default names provided. Click finish button. NetBeans will create the following structure in project window. Right click on the Project Enterprise Application in project explorer and select Build. ant -f D:\SVN\EnterpriseApplication dist pre-init: init-private: init-userdir: init-user: init-project: do-init: post-init: init-check: init: deps-jar: deps-j2ee-archive: EnterpriseApplication-ejb.init: EnterpriseApplication-ejb.deps-jar: EnterpriseApplication-ejb.compile: EnterpriseApplication-ejb.library-inclusion-in-manifest: Building jar: D:SVNEnterpriseApplicationEnterpriseApplication-ejbdistEnterpriseApplication-ejb.jar EnterpriseApplication-ejb.dist-ear: EnterpriseApplication-war.init: EnterpriseApplication-war.deps-module-jar: EnterpriseApplication-war.deps-ear-jar: EnterpriseApplication-ejb.init: EnterpriseApplication-ejb.deps-jar: EnterpriseApplication-ejb.compile: EnterpriseApplication-ejb.library-inclusion-in-manifest: EnterpriseApplication-ejb.dist-ear: EnterpriseApplication-war.deps-jar: EnterpriseApplication-war.library-inclusion-in-archive: EnterpriseApplication-war.library-inclusion-in-manifest: EnterpriseApplication-war.compile: EnterpriseApplication-war.compile-jsps: EnterpriseApplication-war.do-ear-dist: Building jar: D:SVNEnterpriseApplicationEnterpriseApplication-wardistEnterpriseApplication-war.war EnterpriseApplication-war.dist-ear: pre-pre-compile: pre-compile: Copying 1 file to D:SVNEnterpriseApplicationbuild Copying 1 file to D:SVNEnterpriseApplicationbuild do-compile: post-compile: compile: pre-dist: do-dist-without-manifest: do-dist-with-manifest: Building jar: D:SVNEnterpriseApplicationdistEnterpriseApplication.ear post-dist: dist: BUILD SUCCESSFUL (total time: 1 second) Here you can see, that Netbeans prepares Jar first, then War and in the end, the ear file carrying the jar and war, file. Each jar,war and ear file carries a meta-inf folder to have meta data as per the J2EE specification. Print Page Previous Next Advertisements ”;
Category: ejb
EJB – Access Database
EJB – Access Database ”; Previous Next In EJB 3.0, persistence mechanism is used to access the database in which the container manages the database related operations. Developers can access database using JDBC API call directly in EJB business methods. To demonstrate database access in EJB, we need to perform the following tasks − Step 1 − Create a table in the database. Step 2 − Create a stateless EJB having business me. Step 3 − Update stateless EJB. Add methods to add records and get records from database via entity manager. Step 4 − A console based application client will access the stateless EJB to persist data in database. Create Table Create a table books in default database postgres. CREATE TABLE books ( id integer PRIMARY KEY, name varchar(50) ); Create a Model Class public class Book implements Serializable{ private int id; private String name; public Book() { } public int getId() { return id; } … } Create Stateless EJB @Stateless public class LibraryPersistentBean implements LibraryPersistentBeanRemote { public void addBook(Book book) { //persist book using jdbc calls } public List<Book> getBooks() { //get books using jdbc calls } … } After building the EJB module, we need a client to access the stateless bean, which we will be going to create in the next section. Example Application Let us create a test EJB application to test EJB database access mechanism. Step Description 1 Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB – Create Application chapter. You can also use the project created in EJB – Create Application chapter as such for this chapter to understand EJB data access concepts. 2 Create Book.java under package com.tutorialspoint.entity and modify it as shown below. 3 Create LibraryPersistentBean.java and LibraryPersistentBeanRemote as explained in the EJB – Create Application chapter and modify them as shown below. 4 Clean and Build the application to make sure business logic is working as per the requirements. 5 Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet. 6 Now create the EJB client, a console based application in the same way as explained in the EJB – Create Application chapter under topic Create Client to access EJB. Modify it as shown below. EJBComponent (EJB Module) Book.java package com.tutorialspoint.entity; import java.io.Serializable; public class Book implements Serializable{ private int id; private String name; public Book() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } LibraryPersistentBeanRemote.java package com.tutorialspoint.stateless; import com.tutorialspoint.entity.Book; import java.util.List; import javax.ejb.Remote; @Remote public interface LibraryPersistentBeanRemote { void addBook(Book bookName); List<Book> getBooks(); } LibraryPersistentBean.java package com.tutorialspoint.stateless; import com.tutorialspoint.entity.Book; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; @Stateless public class LibraryPersistentBean implements LibraryPersistentBeanRemote { public LibraryPersistentBean() { } public void addBook(Book book) { Connection con = null; String url = “jdbc:postgresql://localhost:5432/postgres”; String driver = “org.postgresql.driver”; String userName = “sa”; String password = “sa”; List<Book> books = new ArrayList<Book>(); try { Class.forName(driver).newInstance(); con = DriverManager.getConnection(url , userName, password); PreparedStatement st = con.prepareStatement(“insert into book(name) values(?)”); st.setString(1,book.getName()); int result = st.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } } public List<Book> getBooks() { Connection con = null; String url = “jdbc:postgresql://localhost:5432/postgres”; String driver = “org.postgresql.driver”; String userName = “sa”; String password = “sa”; List<Book> books = new ArrayList<Book>(); try { Class.forName(driver).newInstance(); con = DriverManager.getConnection(url , userName, password); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(“select * from book”); Book book; while (rs.next()) { book = new Book(); book.setId(rs.getInt(1)); book.setName(rs.getString(2)); books.add(book); } } catch (SQLException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } return books; } } As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log. JBoss has automatically created a JNDI entry for our session bean – LibraryPersistentBean/remote. We will be using this lookup string to get remote business object of type − com.tutorialspoint.stateless.LibraryPersistentBeanRemote JBoss Application Server Log Output … 16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryPersistentBean/remote – EJB3.x Default Remote Business Interface LibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote – EJB3.x Remote Business Interface 16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBeanRemote,service=EJB3 16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibraryPersistentBeanRemote ejbName: LibraryPersistentBean 16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryPersistentBean/remote – EJB3.x Default Remote Business Interface LibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote – EJB3.x Remote Business Interface … EJBTester (EJB Client) jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost These properties are used to initialize the InitialContext object of java naming service. InitialContext object will be used to lookup stateless session bean. EJBTester.java package com.tutorialspoint.test; import com.tutorialspoint.stateless.LibraryPersistentBeanRemote; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Properties; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBTester { BufferedReader brConsoleReader = null; Properties props; InitialContext ctx; { props = new Properties(); try { props.load(new FileInputStream(“jndi.properties”)); } catch (IOException ex) { ex.printStackTrace(); } try { ctx = new InitialContext(props); } catch (NamingException ex) { ex.printStackTrace(); } brConsoleReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { EJBTester ejbTester = new EJBTester(); ejbTester.testEntityEjb(); } private void showGUI() { System.out.println(“**********************”); System.out.println(“Welcome to Book Store”); System.out.println(“**********************”); System.out.print(“Options n1. Add Bookn2. Exit nEnter Choice: “); } private void testEntityEjb() { try { int choice = 1; LibraryPersistentBeanRemote libraryBean = LibraryPersistentBeanRemote) ctx.lookup(“LibraryPersistentBean/remote”); while (choice != 2) { String bookName; showGUI(); String strChoice = brConsoleReader.readLine(); choice = Integer.parseInt(strChoice); if (choice == 1) { System.out.print(“Enter book name: “); bookName = brConsoleReader.readLine(); Book book = new Book(); book.setName(bookName); libraryBean.addBook(book); } else if (choice == 2) { break; } } List<Book> booksList = libraryBean.getBooks(); System.out.println(“Book(s) entered so far: ” + booksList.size()); int i = 0; for (Book book:booksList) { System.out.println((i+1)+”. ” + book.getName()); i++; } } catch (Exception e)
EJB – Create Application
EJB – Create Application ”; Previous Next To create a simple EJB module, we will use NetBeans, “New project” wizard. In the example given below, We will create an EJB module project named Component. Create Project In NetBeans IDE, select File > New Project >. You will see the following screen Select project type under category Java EE, Project type as EJB Module. Click Next > button. You will see the following screen. Enter project name and location. Click Next > button. You will see the following screen. Select Server as JBoss Application Server. Click Finish button. You will see the following project created by NetBeans. Create a Sample EJB To create a simple EJB, we will use NetBeans “New” wizard. In the example given below, We will create a stateless EJB class named librarySessionBean under EjbComponent project. Select project EjbComponent in project explorer window and right click on it. Select, New > Session Bean. You will see the New Session Bean wizard. Enter session bean name and package name. Click Finish button. You will see the following EJB classes created by NetBeans. LibrarySessionBean − stateless session bean LibrarySessionBeanLocal − local interface for session bean I am changing local interface to remote interface as we are going to access our EJB in a console based application. Remote/Local interface is used to expose business methods that an EJB has to implement. LibrarySessionBeanLocal is renamed to LibrarySessionBeanRemote and LibrarySessionBean implements LibrarySessionBeanRemote interface. LibrarySessionBeanRemote package com.tutorialspoint.stateless; import java.util.List; import javax.ejb.Remote; @Remote public interface LibrarySessionBeanRemote { void addBook(String bookName); List getBooks(); } LibrarySessionBean package com.tutorialspoint.stateless; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; @Stateless public class LibrarySessionBean implements LibrarySessionBeanRemote { List<String> bookShelf; public LibrarySessionBean() { bookShelf = new ArrayList<String>(); } public void addBook(String bookName) { bookShelf.add(bookName); } public List<String> getBooks() { return bookShelf; } } Build the Project Select EjbComponent project in Project Explorer window. Right click on it to open context menu. Select clean and build. You will see the following output in NetBeans console output. ant -f C:\EJB\EjbComponent clean dist init: undeploy-clean: deps-clean: Deleting directory C:EJBEjbComponentbuild Deleting directory C:EJBEjbComponentdist clean: init: deps-jar: Created dir: C:EJBEjbComponentbuildclasses Copying 3 files to C:EJBEjbComponentbuildclassesMETA-INF Created dir: C:EJBEjbComponentbuildempty Created dir: C:EJBEjbComponentbuildgenerated-sourcesap-source-output Compiling 2 source files to C:EJBEjbComponentbuildclasses warning: [options] bootstrap class path not set in conjunction with -source 1.6 Note: C:EJBEjbComponentsrcjavacomtutorialspointstateless LibraryPersistentBean.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 1 warning compile: library-inclusion-in-archive: Created dir: C:EJBEjbComponentdist Building jar: C:EJBEjbComponentdistEjbComponent.jar dist: BUILD SUCCESSFUL (total time: 3 seconds) Start the Application Server Select JBoss application server under Servers in Services window. Right click on it to open context menu. Select start. You will see the following output in NetBeans, output under JBoss Application Server. Calling C:jboss-5.1.0.GAbinrun.conf.bat ========================================================================= JBoss Bootstrap Environment JBOSS_HOME: C:jboss-5.1.0.GA JAVA: C:Program Files (x86)Javajdk1.6.0_21binjava JAVA_OPTS: -Dprogram.name=run.bat -Xms128m -Xmx512m -server CLASSPATH: C:jboss-5.1.0.GAbinrun.jar ========================================================================= 16:25:50,062 INFO [ServerImpl] Starting JBoss (Microcontainer)… 16:25:50,062 INFO [ServerImpl] Release ID: JBoss [The Oracle] 5.1.0.GA (build: SVNTag=JBoss_5_1_0_GA date=200905221634) … 16:26:40,420 INFO [TomcatDeployment] deploy, ctxPath=/admin-console 16:26:40,485 INFO [config] Initializing Mojarra (1.2_12-b01-FCS) for context ”/admin-console” 16:26:42,362 INFO [TomcatDeployment] deploy, ctxPath=/ 16:26:42,406 INFO [TomcatDeployment] deploy, ctxPath=/jmx-console 16:26:42,471 INFO [Http11Protocol] Starting Coyote HTTP/1.1 on http-127.0.0.1-8080 16:26:42,487 INFO [AjpProtocol] Starting Coyote AJP/1.3 on ajp-127.0.0.1-8009 16:26:42,493 INFO [ServerImpl] JBoss (Microcontainer) [5.1.0.GA (build: SVNTag=JBoss_5_1_0_GA date=200905221634)] Started in 52s:427ms Deploy the Project Select EjbComponent project in Project Explorer window. Right click on it to open context menu. Select Deploy. You will see the following output in NetBeans console output. ant -f C:\EJB\EjbComponent -DforceRedeploy=true -Ddirectory.deployment.supported=false -Dnb.wait.for.caches=true run init: deps-jar: compile: library-inclusion-in-archive: Building jar: C:EJBEjbComponentdistEjbComponent.jar dist-directory-deploy: pre-run-deploy: Checking data source definitions for missing JDBC drivers… Distributing C:EJBEjbComponentdistEjbComponent.jar to [org.jboss.deployment.spi.LocalhostTarget@1e4f84ee] Deploying C:EJBEjbComponentdistEjbComponent.jar Application Deployed Operation start started Operation start completed post-run-deploy: run-deploy: run: BUILD SUCCESSFUL (total time: 2 seconds) JBoss Application Server Log Output 16:30:00,963 INFO [DeployHandler] Begin start, [EjbComponent.jar] … 16:30:01,233 INFO [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@12038795{vfszip:/C:/jboss-5.1.0.GA/server/default/deploy/EjbComponent.jar/} … 16:30:01,281 INFO [JBossASKernel] jndi:LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote 16:30:01,281 INFO [JBossASKernel] Class:com.tutorialspoint.stateless.LibrarySessionBeanRemote 16:30:01,281 INFO [JBossASKernel] jndi:LibrarySessionBean/remote 16:30:01,281 INFO [JBossASKernel] Added bean(jboss.j2ee:jar=EjbComponent.jar,name= LibrarySessionBean,service=EJB3) to KernelDeployment of: EjbComponent.jar 16:30:01,282 INFO [JBossASKernel] installing bean: jboss.j2ee:jar=EjbComponent.jar,name=BookMessageHandler,service=EJB3 16:30:01,282 INFO [JBossASKernel] with dependencies: 16:30:01,282 INFO [JBossASKernel] and demands: 16:30:01,282 INFO [JBossASKernel] jboss.ejb:service=EJBTimerService … 16:30:01,283 INFO [EJB3EndpointDeployer] Deploy AbstractBeanMetaData@5497cb{name=jboss.j2ee:jar=EjbComponent.jar, name=LibrarySessionBean, service=EJB3_endpoint bean=org.jboss.ejb3.endpoint.deployers.impl.EndpointImpl properties=[container] constructor=null autowireCandidate=true} … 16:30:01,394 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3 16:30:01,395 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean 16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibrarySessionBean/remote – EJB3.x Default Remote Business Interface LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote – EJB3.x Remote Business Interface 16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3 16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean 16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibrarySessionBean/remote – EJB3.x Default Remote Business Interface LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote – EJB3.x Remote Business Interface Create Client to Access EJB In NetBeans IDE, select File > New Project >. Select project type under category Java, Project type as Java Application. Click Next > button Enter project name and location. Click Finish > button. We have chosen name as EjbTester. Right click on project name in Project explorer window. Select properties. Add EJB component project created earlier under libraries using Add Project button in compile tab. Add jboss libraries using Add jar/folder button in compile tab. Jboss libraries can be located at <jboss installation folder>> client folder. Create jndi.properties under project say EjbTester. jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost Create package com.tutorialspoint.test and EJBTester.java class under it. EJBTester.java package com.tutorialspoint.test; import com.tutorialspoint.stateless.LibrarySessionBeanRemote; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Properties; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBTester { BufferedReader brConsoleReader = null; Properties props; InitialContext ctx; { props = new Properties(); try { props.load(new FileInputStream(“jndi.properties”)); } catch (IOException ex) { ex.printStackTrace(); } try { ctx = new InitialContext(props); } catch (NamingException ex) { ex.printStackTrace(); } brConsoleReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { EJBTester ejbTester = new EJBTester(); ejbTester.testStatelessEjb(); } private void showGUI() { System.out.println(“**********************”); System.out.println(“Welcome to Book Store”); System.out.println(“**********************”); System.out.print(“Options n1. Add Bookn2. Exit nEnter Choice: “); } private void testStatelessEjb() { try { int choice = 1; LibrarySessionBeanRemote libraryBean = (LibrarySessionBeanRemote)ctx.lookup(“LibrarySessionBean/remote”); while (choice != 2) { String bookName; showGUI(); String strChoice = brConsoleReader.readLine();
EJB – Quick Guide
EJB – Quick Guide ”; Previous Next EJB – Overview EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE platform. J2EE platform has component based architecture to provide multi-tiered, distributed and highly transactional features to enterprise level applications. EJB provides an architecture to develop and deploy component based enterprise applications considering robustness, high scalability, and high performance. An EJB application can be deployed on any of the application server compliant with the J2EE 1.3 standard specification. We”ll be discussing EJB 3.0 in detail in this tutorial. Types EJB is primarily divided into three categories; following table lists their names with brief descriptions − S.No Type & Description 1 Session Bean Session bean stores data of a particular user for a single session. It can be stateful or stateless. It is less resource intensive as compared to entity bean. Session bean gets destroyed as soon as user session terminates. 2 Entity Bean Entity beans represent persistent data storage. User data can be saved to database via entity beans and later on can be retrieved from the database in the entity bean. 3 Message Driven Bean Message driven beans are used in context of JMS (Java Messaging Service). Message Driven Beans can consumes JMS messages from external entities and act accordingly. Benefits Following are the important benefits of EJB − Simplified development of large-scale enterprise level application. Application Server/EJB container provides most of the system level services like transaction handling, logging, load balancing, persistence mechanism, exception handling, and so on. Developer has to focus only on business logic of the application. EJB container manages life cycle of EJB instances, thus developer needs not to worry about when to create/delete EJB objects. EJB – Environment Setup EJB is a framework for Java, so the very first requirement is to have a Java Development Kit (JDK) installed in your machine. System Requirement JDK 1.5 or above. Memory no minimum requirement. Disk Space no minimum requirement. Operating System no minimum requirement. Step 1 – Verify Java Installation in Your System Now open console and execute the following java command. OS Task Command Windows Open Command Console c:> java -version Linux Open Command Terminal $ java -version Mac Open Terminal machine:~ joseph$ java -version Let”s verify the output for all the operating systems − OS Output Windows java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b11) Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode) Linux java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b11) Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode) Mac java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b11) Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode) If you do not have Java installed, install the Java Software Development Kit (SDK) from www.oracle.com. We are assuming that Java 1.6.0_21 as installed version for this tutorial. Step 2 – Set JAVA Environment Set the JAVA_HOME environment variable to point the base directory location where Java is installed on your system. For example, OS Output Windows Set the environment variable JAVA_HOME to C:Program FilesJavajdk1.6.0_21 Linux export JAVA_HOME=/usr/local/java-current Mac export JAVA_HOME=/Library/Java/Home Append Java compiler location to System Path. OS Output Windows Append the string ;C:Program FilesJavajdk1.6.0_21bin to the end of the system variable, Path. Linux export PATH=$PATH:$JAVA_HOME/bin/ Mac not required Verify Java Installation using java -version command explained above. Step 3 – Download and Install NetBeans IDE Download the latest version of NetBeans IDE from netbeans.org. At the time of writing this tutorial, I downloaded Netbeans 7.3 which comes bundled with JDK 1.7 using the following link www.oracle.com OS Installer name Windows Netbeans 7.3 Linux Netbeans 7.3 Mac Netbeans 7.3 Step 4 – Setup JBoss Application Server You can download the latest version of JBoss Server from www.jboss.org. Download the archive as per the platform. Extract the Jboss to any location on your machine. OS File name Windows jboss-5.1.0.GA-jdk6.zip Linux jboss-5.1.0.GA-src.tar.gz Mac jboss-5.1.0.GA-src.tar.gz Step 5 – Configure JEE Plugins to Netbeans Open Plugin window using Tools > Plugins. Open “Available Plugin” tab and select “Java EE Base” and “EJB and EAR” under “Java Web and EE” category. Click install button. Netbeans will download and install the respective plugins. Verify plugins installation using “Installed” tab (as shown in the image given below). Step 6 – Configure JBoss Server in Netbeans Go to Services tab and right click on servers to add a new server. Add Server Instance wizard will open. Select JBoss and in next step enter the relevant details to configure server in netbeans. Once everything is configured, you will see the following screen. Step 7 – Install Database Server (PostGreSql) Download latest version of PostGreSql database server from www.postgresql.org. At the time of writing this tutorial, I downloaded PostGreSql 9.2 OS Installer name Windows PostGreSql 9.2 Linux PostGreSql 9.2 Mac PostGreSql 9.2 EJB – Create Application To create a simple EJB module, we will use NetBeans, “New project” wizard. In the example given below, We will create an EJB module project named Component. Create Project In NetBeans IDE, select File > New Project >. You will see the following screen Select project type under category Java EE, Project type as EJB Module. Click Next > button. You will see the following screen. Enter project name and location. Click Next > button. You will see the following screen. Select Server as JBoss Application Server. Click Finish button. You will see the following project created by NetBeans. Create a Sample EJB To create a simple EJB, we will use NetBeans “New” wizard. In the example given below, We will create a stateless EJB class named librarySessionBean under EjbComponent project. Select project EjbComponent in project explorer window and right click on it. Select, New > Session Bean. You will see the New Session Bean wizard. Enter session bean name and package name. Click Finish button. You will see the following EJB classes created by NetBeans. LibrarySessionBean − stateless session bean LibrarySessionBeanLocal − local interface for session bean I am changing local interface to remote interface as
EJB – Message Driven Beans
EJB – Message Driven Beans ”; Previous Next A message driven bean is a type of enterprise bean, which is invoked by EJB container when it receives a message from queue or topic. Message driven bean is a stateless bean and is used to do task asynchronously. To demonstrate use of message driven bean, we will make use of EJB-persistence chapter and we need to do the following tasks − Step 1 − Create table in database (Refer to EJB-Persistence chapter). Step 2 − Create Entity class corresponding to table (Refer to EJB-Persistence chapter). Step 3 − Create DataSource and Persistence Unit (Refer to EJB-Persistence chapter). Step 4 − Create a stateless EJB having EntityManager instance (Refer to EJB-Persistence chapter). Step 5 − Update stateless ejb.Add methods to add records and get records from database via entity manager (Refer to EJB-Persistence chapter). Step 6 − Create a Queue named BookQueue in JBoss default application directory. Step 7 − A console based application client will send message to this queue. Step 8 − Create a Message driven bean, which will use the stateless bean to persist the client data. Step 9 − EJB Container of jboss will call the above message driven bean and pass it the message that client will be sending to. Create Queue Create a file named jbossmq-destinations-service.xml if not exists in <JBoss Installation Folder> > server > default > deploy folder. Here we are creating a queue named BookQueue − jbossmq-destinations-service.xml <mbean code=”org.jboss.mq.server.jmx.Queue” name=”jboss.mq.destination:service=Queue,name=BookQueue”> <depends optional-attribute-name=”DestinationManager”> jboss.mq:service=DestinationManager </depends> </mbean> When you start the JBoss, you will see a similar entry in jboss log. … 10:37:06,167 INFO [QueueService] Queue[/queue/BookQueue] started, fullSize=200000, pageSize=2000, downCacheSize=2000 … Create Message Driven Bean @MessageDriven( name = “BookMessageHandler”, activationConfig = { @ActivationConfigProperty( propertyName = “destinationType”, propertyValue = “javax.jms.Queue”), @ActivationConfigProperty( propertyName = “destination”, propertyValue =”/queue/BookQueue”) } ) public class LibraryMessageBean implements MessageListener { @Resource private MessageDrivenContext mdctx; @EJB LibraryPersistentBeanRemote libraryBean; public LibraryMessageBean() { } public void onMessage(Message message) { } } LibraryMessageBean is annotated with @MessageDriven annotation to mark it as message driven bean. Its properties are defined as destinationType – Queue and destination – /queue/BookQueue. It implements MessageListener interface, which exposes onMessage method. It has MessgeDrivenContext as a resource. LibraryPersistentBeanRemote stateless bean is injected in this bean for persistence purpose. Build the EjbComponent project and deploy it on JBoss. After building and deploying the EJB module, we need a client to send a message to jboss queue. Example Application Let us create a test EJB application to test Message Driven Bean. Step Description 1 Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB – Create Application chapter. You can also use the project created in EJB – Create Application chapter as such for this chapter to understand EJB persistence concepts. 2 Create Book.java under package com.tutorialspoint.entity as created in EJB-Persistence chapter. 3 Create LibraryPersistentBean.java and LibraryPersistentBeanRemote as created in EJB-Persistence chapter. 4 Create jboss-ds.xml in EjbComponent > setup folder and persistence.xml in EjbComponent > src > conf folder. These folders can be seen in files tab in Netbeans as created in EJB-Persistence chapter. 5 Create LibraryMessageBean.java under a package com.tutorialspoint.messagebean and modify it as shown below. 6 Create BookQueue queue in Jboss as described above. 7 Clean and Build the application to make sure business logic is working as per the requirements. 8 Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet. 9 Now create the EJB client, a console based application in the same way as explained in the EJB – Create Application chapter under topic Create Client to access EJB. Modify it as shown below. EJBComponent (EJB Module) LibraryMessageBean.java package com.tutorialspoint.messagebean; import com.tutorialspoint.entity.Book; import com.tutorialspoint.stateless.LibraryPersistentBeanRemote; import javax.annotation.Resource; import javax.ejb.ActivationConfigProperty; import javax.ejb.EJB; import javax.ejb.MessageDriven; import javax.ejb.MessageDrivenContext; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; @MessageDriven( name = “BookMessageHandler”, activationConfig = { @ActivationConfigProperty( propertyName = “destinationType”, propertyValue = “javax.jms.Queue”), @ActivationConfigProperty( propertyName = “destination”, propertyValue =”/queue/BookQueue”) } ) public class LibraryMessageBean implements MessageListener { @Resource private MessageDrivenContext mdctx; @EJB LibraryPersistentBeanRemote libraryBean; public LibraryMessageBean() { } public void onMessage(Message message) { ObjectMessage objectMessage = null; try { objectMessage = (ObjectMessage) message; Book book = (Book) objectMessage.getObject(); libraryBean.addBook(book); } catch (JMSException ex) { mdctx.setRollbackOnly(); } } } EJBTester (EJB Client) EJBTester.java package com.tutorialspoint.test; import com.tutorialspoint.entity.Book; import com.tutorialspoint.stateless.LibraryPersistentBeanRemote; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Properties; import javax.jms.ObjectMessage; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSender; import javax.jms.QueueSession; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBTester { BufferedReader brConsoleReader = null; Properties props; InitialContext ctx; { props = new Properties(); try { props.load(new FileInputStream(“jndi.properties”)); } catch (IOException ex) { ex.printStackTrace(); } try { ctx = new InitialContext(props); } catch (NamingException ex) { ex.printStackTrace(); } brConsoleReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { EJBTester ejbTester = new EJBTester(); ejbTester.testMessageBeanEjb(); } private void showGUI() { System.out.println(“**********************”); System.out.println(“Welcome to Book Store”); System.out.println(“**********************”); System.out.print(“Options n1. Add Bookn2. Exit nEnter Choice: “); } private void testMessageBeanEjb() { try { int choice = 1; Queue queue = (Queue) ctx.lookup(“/queue/BookQueue”); QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup(“ConnectionFactory”); QueueConnection connection = factory.createQueueConnection(); QueueSession session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); QueueSender sender = session.createSender(queue); while (choice != 2) { String bookName; showGUI(); String strChoice = brConsoleReader.readLine(); choice = Integer.parseInt(strChoice); if (choice == 1) { System.out.print(“Enter book name: “); bookName = brConsoleReader.readLine(); Book book = new Book(); book.setName(bookName); ObjectMessage objectMessage = session.createObjectMessage(book); sender.send(objectMessage); } else if (choice == 2) { break; } } LibraryPersistentBeanRemote libraryBean = (LibraryPersistentBeanRemote) ctx.lookup(“LibraryPersistentBean/remote”); List<Book> booksList = libraryBean.getBooks(); System.out.println(“Book(s) entered so far: ” + booksList.size()); int i = 0; for (Book book:booksList) { System.out.println((i+1)+”. ” + book.getName()); i++; } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); }finally { try { if(brConsoleReader !=null) { brConsoleReader.close(); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } } } EJBTester performs the following tasks − Load properties from jndi.properties and initialize the InitialContext object. In testStatefulEjb() method, jndi lookup is done with the name – “/queue/BookQueue”
EJB – Timer Service
EJB – Timer Service ”; Previous Next Timer Service is a mechanism by which scheduled application can be build. For example, salary slip generation on the 1st of every month. EJB 3.0 specification has specified @Timeout annotation, which helps in programming the EJB service in a stateless or message driven bean. EJB Container calls the method, which is annotated by @Timeout. EJB Timer Service is a service provided by EJB container, which helps to create timer and to schedule callback when timer expires. Steps to Create Timer Inject SessionContext in bean using @Resource annotation − @Stateless public class TimerSessionBean { @Resource private SessionContext context; … } Use SessionContext object to get TimerService and to create timer. Pass time in milliseconds and message. public void createTimer(long duration) { context.getTimerService().createTimer(duration, “Hello World!”); } Steps to Use Timer Use @Timeout annotation to a method. Return type should be void and pass a parameter of type Timer. We are canceling the timer after first execution otherwise it will keep running after fix intervals. @Timeout public void timeOutHandler(Timer timer) { System.out.println(“timeoutHandler : ” + timer.getInfo()); timer.cancel(); } Example Application Let us create a test EJB application to test Timer Service in EJB. Step Description 1 Create a project with a name EjbComponent under a package com.tutorialspoint.timer as explained in the EJB – Create Application chapter. 2 Create TimerSessionBean.java and TimerSessionBeanRemote as explained in the EJB – Create Application chapter. Keep rest of the files unchanged. 3 Clean and Build the application to make sure business logic is working as per the requirements. 4 Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet. 5 Now create the EJB client, a console based application in the same way as explained in the EJB – Create Application chapter under topic Create Client to access EJB. EJBComponent (EJB Module) TimerSessionBean.java package com.tutorialspoint.timer; import javax.annotation.Resource; import javax.ejb.SessionContext; import javax.ejb.Timer; import javax.ejb.Stateless; import javax.ejb.Timeout; @Stateless public class TimerSessionBean implements TimerSessionBeanRemote { @Resource private SessionContext context; public void createTimer(long duration) { context.getTimerService().createTimer(duration, “Hello World!”); } @Timeout public void timeOutHandler(Timer timer) { System.out.println(“timeoutHandler : ” + timer.getInfo()); timer.cancel(); } } TimerSessionBeanRemote.java package com.tutorialspoint.timer; import javax.ejb.Remote; @Remote public interface TimerSessionBeanRemote { public void createTimer(long milliseconds); } As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log. JBoss has automatically created a JNDI entry for our session bean − TimerSessionBean/remote. We will using this lookup string to get remote business object of type − com.tutorialspoint.timer.TimerSessionBeanRemote JBoss Application Server Log Output … 16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: TimerSessionBean/remote – EJB3.x Default Remote Business Interface TimerSessionBean/remote-com.tutorialspoint.timer.TimerSessionBeanRemote – EJB3.x Remote Business Interface 16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=TimerSessionBean,service=EJB3 16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.timer.TimerSessionBeanRemote ejbName: TimerSessionBean … EJBTester (EJB Client) jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost These properties are used to initialize the InitialContext object of java naming service. InitialContext object will be used to lookup stateless session bean. EJBTester.java package com.tutorialspoint.test; import com.tutorialspoint.stateful.TimerSessionBeanRemote; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Properties; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBTester { BufferedReader brConsoleReader = null; Properties props; InitialContext ctx; { props = new Properties(); try { props.load(new FileInputStream(“jndi.properties”)); } catch (IOException ex) { ex.printStackTrace(); } try { ctx = new InitialContext(props); } catch (NamingException ex) { ex.printStackTrace(); } brConsoleReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { EJBTester ejbTester = new EJBTester(); ejbTester.testTimerService(); } private void showGUI() { System.out.println(“**********************”); System.out.println(“Welcome to Book Store”); System.out.println(“**********************”); System.out.print(“Options n1. Add Bookn2. Exit nEnter Choice: “); } private void testTimerService() { try { TimerSessionBeanRemote timerServiceBean = (TimerSessionBeanRemote)ctx.lookup(“TimerSessionBean/remote”); System.out.println(“[“+(new Date()).toString()+ “]” + “timer created.”); timerServiceBean.createTimer(2000); } catch (NamingException ex) { ex.printStackTrace(); } } } EJBTester is doing the following tasks. Load properties from jndi.properties and initialize the InitialContext object. In testTimerService() method, jndi lookup is done with the name – “TimerSessionBean/remote” to obtain the remote business object (timer stateless EJB). Then createTimer is invoked passing 2000 milliseconds as schedule time. EJB Container calls the timeoutHandler method after 2 seconds. Run Client to Access EJB Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file. Verify the following output in Netbeans console. run: [Wed Jun 19 11:35:47 IST 2013]timer created. BUILD SUCCESSFUL (total time: 0 seconds) JBoss Application Server Log Output You can find the following callback entries in JBoss log … 11:35:49,555 INFO [STDOUT] timeoutHandler : Hello World! … Print Page Previous Next Advertisements ”;