Friday, June 20, 2008

Developing Web Services Using EJB 3.0

The specification Web Services for Java EE, JSR 109 defines two ways of implementing a web service. One way is based on the Java class programming model -- the web service is implemented by a Java class that runs in a web container. The other way is based on the Enterprise JavaBeans (EJB) programming model -- the web service is implemented as a stateless session bean that runs in an EJB container. A previous Tech Tip, Developing Web Services Using JAX-WS, described how to develop a web service using the Java class programming model and Java API for XML Web Services (JAX-WS) 2.0, JSR 224. In the following tip, you'll learn how to develop a web service using JAX-WS and the EJB programming model. In particular, you'll learn how to use an EJB 3.0 stateless session bean to implement a Calculator service -- the same Calculator service that was covered in the previous Tech Tip.

A sample package accompanies this tip. It demonstrates a standalone Java client accessing the EJB 3.0-based Calculator service. The example uses an open source reference implementation of Java EE 5 called GlassFish. You can download GlassFish from the GlassFish Community Downloads page.

Writing the EJB 3.0 Stateless Session Bean Class

Let's start by creating the stateless session bean for the service. One of the significant improvements in the Java EE 5 platform is a much simpler EJB programming model as defined in the Enterprise JavaBeans 3.0 Specification, JSR-220. One of the simplifications is that a bean implementation class is no longer required to implement the javax.ejb.SessionBean or javax.ejb.EntityBean interface. You can declare a class a session bean or entity bean simply by annotating it. For example, you can declare a class a stateless session bean by annotating it with the @Stateless annotation.

EJB 3.0 does specify additional rules for the bean implementation class:

  • It must be declared public and must have a default constructor that doesn't take any arguments.
  • It must not be final or abstract and must be a top-level class.
  • It must not define a finalize() method.

Another simplification in EJB 3.0 is that a component interface or home interface is no longer required for a session bean. The one interface a session bean needs is a business interface that defines the business methods for the bean. Unlike business methods in a component interface, the business methods in a business interface are not required to throw java.remote.RemoteException. However the business methods can define throws clauses for arbitrary application exceptions. The EJB 3.0 business methods should not be static and final.

Given these simplifications and rules, here is a stateless session bean for the Calculator class that conforms to the EJB 3.0 programming model (you can find the source code for the Calculator class in the endpoint directory of the installed sample package):

package endpoint;

import javax.ejb.Stateless;

@Stateless
public class Calculator {

public Calculator() {}
public int add(int i, int j) {
int k = i +j ;
System.out.println(i + "+" + j +" = " + k);
return k;
}
}

Because the EJB 3.0 bean doesn't need to implement the javax.ejb.SessionBean interface, it no longer needs to include unimplemented lifecycle methods such as ejbActivate and ejbPassivate. This results in a much simpler and cleaner class. Various annotations defined in EJB 3.0 reduce the burden on developers and deployers by reducing or eliminating the need to write a deployment descriptor for the component.

Marking the EJB 3.0 Bean as a Web Service

To mark a bean as a web service simply annotate the class with the @WebService annotation. This is an annotation type defined in the javax.jws.WebService package, and is specified in Web Services Metadata for the Java Platform, JSR 181. Here is the code for Calculator class marked as a web service:

package endpoint;

import javax.ejb.Stateless;
import javax.jws.WebService;

@Stateless
@WebService
public class Calculator {

public Calculator() {}
public int add(int i, int j) {
int k = i +j ;
System.out.println(i + "+" + j +" = " + k);
return k;
}
}

Marking a Java class with a @WebService annotation makes it a service implementation class. Note that you don't have to implement a service endpoint interface. According to the JSR 109, you only need to provide a javax.jws.WebService-annotated service implementation bean. Deployment tools can then be used to generate a service endpoint interface, as well as a WSDL document, using JAX-WS rules for Java WSDL mapping.

Packaging the Web Service

A web service based on the EJB programming model needs to be packaged as a JAR file. Using the @WebService annotation, you only need to package the service implementation bean class (with its dependent classes, if any) and the service endpoint interface class (if explicitly provided). Additionally, the @Stateless annotation frees you from packaging ejb-jar.xml. By comparison, in the JAX-RPC style of packaging web services based on EJB 2.0 or earlier, you were responsible for providing the service endpoint interface class, the service implementation bean class (and dependent classes), generated portable artifacts, the JAX-RPC mapping file, and a web services deployment descriptor (webservices.xml and ejb-jar.xml).

With JSR 224, JSR 109, JSR 181 and JSR 220, an application server deployment tool can generate all the necessary artifacts such as a deployment descriptor (if not explicitly provided by the user) for deploying the web service. These artifacts, bundled in the EJB JAR file, are deployed in an EJB container. A deployer can choose to overwrite values specified by the @WebService and @Stateless annotations by explicitly providing any of the previously-mentioned artifacts and packaging them in the EJB module at the time of deployment. For this tip, the following files are packaged in the EJB module to be deployed:

  endpoint/Calculator.class
endpoint/jaxws/Add.class
endpoint/jaxws/AddResponse.class

The rest of the deployment artifacts are generated by the application server (in this case, GlassFish).

Writing the Client

After you deploy the web service, you can access it from a client program. A client uses a @WebServiceRef annotation to declare a reference to an EJB 3.0-based web service. The @WebServiceRef annotation is in the javax.xml.ws package, and is specified in JAX-WS 2.0 Web Services Metadata for the Java Platform, JSR 181. If you examine the source code JAXWSClient, the client program used in this tip (you can find the source code for JAXWSClient in the client directory of the installed sample package), you'll notice the following:

   @WebServiceRef(wsdlLocation=
"http://localhost:8080/CalculatorService/Calculator?WSDL")
static endpoint.CalculatorService service;

The value of the wsdlLocation parameter in @WebServiceRef is a URL that points to the location of the WSDL file for the referenced service. (The @WebServiceRef annotation supports additional properties that are optional. These optional properties are specified in section 7.9 of the JAX-WS 2.0 specification.) The static variable named service will be injected by the application client container.

Looking further at the source code for JAXWSClient, you'll notice the following line:

endpoint.Calculator port = service.getCalculatorPort();

The service object provides the method, getCalculatorPort, to access the Calculator port of the web service. Note that both endpoint.CalculatorService and endpoint.Calculator are portable artifacts that are generated by using the wsimport utility. The wsimport utility is used to generate JAX-WS artifacts (it is invoked as part of the build-client step when you run the example program.)

After you get the port, you can invoke a business method on it just as though you invoke a Java method on an object. For example, the following line in JAXWSClient invokes the add method in Calculator:

int ret = port.add(i, 10);

Running the Sample Code

A sample package accompanies this tip. It demonstrates the techniques covered in the tip. To install and run the sample:

  1. If you haven't already done so, download GlassFish from the GlassFish Community Downloads page.
  2. Set the following environment variables:
  3. GLASSFISH_HOME: This should point to where you installed GlassFish (for example C:\Sun\AppServer)

    ANT_HOME: This should point to where ant is installed. Ant is included in the GlassFish bundle that you downloaded. (In Windows, it's in the lib\ant subdirectory.)

    JAVA_HOME: This should point to the location of JDK 5.0 on your system.

    Also, add the ant location to your PATH environment variable.

  4. Download the sample package for the tip and extract its contents. You should now see the newly extracted directory as /ttmar2006ejb-ws, where is the directory in which you installed the sample package. For example, if you extracted the contents to C:\ on a Windows machine, then your newly created directory should be at C:\ttmar2006ejb-ws. The ejb-techtip directory below ttmar2006ejb-ws contains the source files and other support file for the sample.
  5. Change to the ejb-techtip directory and edit the build.properties files as appropriate. For example, if the admin host is remote, change the value of admin.host from the default (localhost) to the appropriate remote host.
  6. Start GlassFish by entering the following command:
  7.       /bin/asadmin start-domain domain1

    where is the directory in which you installed GlassFish.

  8. In the ejb-techtip directory, execute the following commands:
  9.       ant build

    This creates a build directory, compiles the classes, and puts the compiled classes in the build directory. It also creates an archive directory, creates a JAR file, and puts the JAR file in the archive directory.

          ant deploy

    This deploys the JAR file on GlassFish.

          ant build-client

    This generates portable artifacts and compiles the client source code.

          ant run

    This runs the application client and invokes the add operation in the Calculator service 10 times, adding 10 to the numbers 0-to-9. You should see the following in response:

          run:

    [echo] Executing appclient with client class as
    client.JAXWSClient
    [exec] Retrieving port from the service
    endpoint.CalculatorService@159780d
    [exec] Invoking add operation on the calculator port
    [exec] Adding : 0 + 10 = 10
    [exec] Adding : 1 + 10 = 11
    [exec] Adding : 2 + 10 = 12
    [exec] Adding : 3 + 10 = 13
    [exec] Adding : 4 + 10 = 14
    [exec] Adding : 5 + 10 = 15
    [exec] Adding : 6 + 10 = 16
    [exec] Adding : 7 + 10 = 17
    [exec] Adding : 8 + 10 = 18
    [exec] Adding : 9 + 10 = 19

  10. To undeploy the EJB Module from GlassFish, execute the following command:
  11.       ant undeploy

About the Author

Manisha Umbarje is a member of the product engineering group for the Sun Java System Application Server.

Copyright (c) 2004-2005 Sun Microsystems, Inc.
All Rights Reserved.

SCBCD 5.0 Free Tutorials and Guide

This Blog lists all the free Tutorials and Guides available for the SCBCD 5.0 certification exam.

http://java.boot.by/scbcd5-guide - A must read notes for SCBCD 5.0.
http://www.geocities.com/rkbalgi/bcd5_notes.txt - Quick Revision notes for SCBCD 5.0

Common Articles for EJB 3.0

http://java.sun.com/javaee/5/docs/api/
http://jcp.org/aboutJava/communityprocess/final/jsr220/index.html
What is new in EJB 3.0
EJB 3.0 Articles from JavaBeat
http://www.theserverside.com/tt/books/wiley/masteringEJB3/index.tss

Commercial Mock Exams for SCBCD 5.0

300 SCBCD 5.0 Mock Exam Questions

SCBCD 5.0 Books - Pro EJB 3: Java Persistence API

EJB 3.0 sets a new precedent. It has made huge advances in ease of development, and its drastically simplified programming model has been widely acclaimed.

Mike Keith, EJB 3.0 co-specification lead, and Merrick Schinariol, reviewer of EJB 3.0, offer unparalleled insight and expertise on the new EJB 3.0 persistence specification, in this definitive guide to EJB 3.0 persistence technology. Expect full coverage and examination of the EJB 3.0 spec from these expert authors, including:

  • The new EntityManager API
  • The new features of EJB Query Language (EJB QL)
  • Basic and advanced object-relational mapping
  • Advanced topics like concurrency, locking, inheritance, and polymorphism

Assuming a basic knowledge of Java, SQL, JDBC, and some J2EE experience, Mike Keith and Merrick Schinariol will teach you EJB 3 persistence from the ground up. After reading it, you will have an in-depth understanding of the EJB 3.0 Persistence API and how to use it in your applications.

Buy this book from Amazon

SCBCD 5.0 Mock Exam Questions

SCBCD 5.0 Books - Enterprise JavaBeans 3.0

If you're up on the latest Java technologies, then you know that Enterprise JavaBeans (EJB) 3.0 is the hottest news in Java this year. In fact, EJB 3.0 is being hailed as the new standard of server-side business logic programming. And O'Reilly's award-winning book on EJB has been refreshed just in time to capitalize on the technology's latest rise in popularity.

This fifth edition, written by Bill Burke and Richard Monson-Haefel, has been updated to capture the very latest need-to-know Java technologies in the same award-winning fashion that drove the success of the previous four strong-selling editions. Bill Burke, Chief Architect at JBoss, Inc., represents the company on the EJB 3.0 and Java EE 5 specification committees. Richard Monson-Haefel is one of the world's leading experts on Enterprise Java.

Enterprise JavaBeans 3.0, 5th Edition is organized into two parts: the technical manuscript followed by the JBoss workbook. The technical manuscript explains what EJB is, how it works, and when to use it. The JBoss workbook provides step-by-step instructions for installing, configuring, and running the examples from the manuscript on the JBoss 4.0 Application Server.

Although EJB makes application development much simpler, it's still a complex and ambitious technology that requires a great deal of time to study and master. But now, thanks to Enterprise JavaBeans 3.0, 5th Edition, you can overcome the complexities of EJBs and learn from hundreds of practical examples that are large enough to test key concepts but small enough to be taken apart and explained in the detail that you need. Now you can harness the complexity of EJB with just a single resource by your side.

Buy this book from Amazon

SCBCD 5.0 Mock Exam Questions

SCBCD 5.0 Books - Mastering Enterprise JavaBeans 3.0

An invaluable tutorial on the dramatic changes to Enterprise JavaBeans (EJB) 3.0

Featuring myriad changes from its previous versions, EJB 3.0 boasts a very different programming and deployment model, with nearly every aspect of development affected. Even the most experienced EBJ and J2EE developers will need to relearn how to best use EJB to develop mission-critical applications. This author team of experts has taken their combined skills in architecture, development, consulting, and knowledge transfer to explain the various changes to EJB 3.0 as well as the rationale behind these changes. You'll learn the concepts and techniques for authoring distributed, enterprise components in Java from the ground up.

Covering basic through advanced subjects, Mastering Enterprise JavaBeans 3.0 is more than 50 percent new and revised. Four new chapters and one new appendix cover the latest features of this new release, and in-depth coverage of the Java Persistence API and the entities defined therein is provided. The authors' main goal is to get you programming with EJB immediately. To that end, you'll learn:
* How to implement EJB 3.0 beans, with emphasis on session beans (stateful and stateless) and message-driven beans
* Both basic and advanced concepts (such as inheritance, relationships, and so on) of Java Persistence API defined entities
* How to develop and deploy EJB 3.0 Web services
* How to secure EJB applications
* How to integrate EJB applications with the outside world via the Java EE Connector technology
* Tips and techniques for designing and deploying EJB for better performance
* How clustering in large-scale EJB systems works
* Best practices for EJB application design, development, and testing

The companion Web site provides all the source code, updates to the source code examples, and a PDF version of the book.

Wiley Technology Publishing Timely. Practical. Reliable.

Buy this book from Amazon

SCBCD 5.0 Mock Exam Questions

SCBCD 5.0 Books - EJB 3 in Action

EJB 3 in Action tackles EJB 3 and the Java Persistence API head-on, providing practical code samples, real-life scenarios, best practices, design patterns, and performance tuning tips. This book builds on the contributions and strengths of seminal technologies like Spring, Hibernate, and TopLink.

EJB 3 is the most important innovation introduced in Java EE 5.0. EJB 3 simplifies enterprise development, abandoning the complex EJB 2.x model in favor of a lightweight POJO framework. The new API represents a fresh perspective on EJB without sacrificing the mission of enabling business application developers to create robust, scalable, standards-based solutions.

EJB 3 in Action is a fast-paced tutorial, geared toward helping you learn EJB 3 and the Java Persistence API quickly and easily. For newcomers to EJB, this book provides a solid foundation in EJB. For the developer moving to EJB 3 from EJB 2, this book addresses the changes both in the EJB API and in the way the developer should approach EJB and persistence.

Buy this book from Amazon

SCBCD 5.0 Mock Exam Questions

Wednesday, May 7, 2008

SCBCD 5.0 Exam Takers FeedBack

Was easier than I expected it to be. I did not encounter any drag & drop questions, and I felt pretty comfortable. Questions were very straightforward, and there was not a lot of unnecessary ambiguity. It felt like you either knew it, or you didn't. I scored lowest on General EJB 3.0 Enterprise Bean Knowledge and Persistence Units and Persistence Contexts (66% on both). Not sure what happened on General knowledge, but I know that I didn't study a whole lot of Persistence Unit/Contexts so that was just fine with me. I scored 100% on EJB 3.0 Overview, Java Persistence Entity Operations, Transactions, Exceptions, and Security Management, which ironically were the subjects I felt weakest in but turned out to know quite well. - Dustin Johnson


Almost 50% of the questions were about JPA.
Just 1 Drag&Drop question (I'm lucky because this type of question can't be reviewed!)
4 questions about Security (I failed 3: for me it was a difficult part of the exam).
CHATEAUVIEUX