Get the online training

Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com

Web Service

Introduction to EJB3

  • Server side re-usable components that enable rapid application development
  • Factor out common services from application development
  • Distribution and remote invocation (interface with other services)
  • Transaction management (one unit of work)
  • Thread management
  • Persistence (related to database)
  • Security (JAAS)
  • Scalability
  • User can just concentrate on application code!

The three types of Beans

  • Session Beans (~service layer)
    • Provide synchronous (request-response conversation) client access to business services
    • Can be stateless (shared) or stateful (one per client)
    • Have NO persistent state
  • Entity Beans
    • Represent persistent components in the business model (database tables and columns)
    • Students, employees, documents, etc.
    • Shared between clients, but access is synchronized
  • Message Driven Beans (not efficient for real-time)
    • Provide asynchronous access to business services (a queue)
    • Invoked by messages instead of distributed method call
    • Clients do not interact directly with them

Stateless Session Beans
  • Execute on behalf of one client at a time
  • Re-entrant, executes logic that does not keep state across invocations
  • When done servicing one client, gets released so it can service another
  • A small pool of beans can be created to service many clients – scalable!
  • A client may make multiple concurrent invocations – each invocation will get a different instance from the pool to process the request

Stateful Session Beans
  • Converse with clients across invocations and time
  • Are managed by one and only one client
  • Can not be switched between invocations
  • Can hold state of the conversation (like the contents of a shopping cart)
  • May be passivated (serialized, moved to secondary storage) as required
  • State may not be maintained across server restarts
  • Not as scalable, can only process one invocation at a time and may or may not be clustered
  • Note:  should always have @remove annotation at the end.

What is a Container? (application container)
  • The fundamental part of an EJB server
  • Manages the Beans
  • Deployment
  • Lifecycles – instantiation and pooling
  • Execution threads
  • All client access goes through it
  • Provides integration of services (naming, transactions, etc.)
  • Intercepts calls and injects the service infrastructure
  • Client invocations are decoupled through a proxy
  • The proxy routes all calls through the container
  • The service code is applied before the business code is executed (JBoss interceptors)
  • The container calls the bean implementation directly
  • Supplies the bean implementation with a EJBContext object which provides details of the environment and current invocation

Deployment Descriptor ejb-jar.xml
  • Now optional in EJB3
  • Can be used to complement or override information provided by annotations
  • Contains metadata for the beans
  • Type of bean
  • Name of class
  • Environment properties
  • Transactional and security requirements
  • Portable across vendors – part of the JEE specification

Deployment Descriptor weblogic-ejb--jar.xml
  • Optional Weblogic specific extension
  • Connect local bean name to global JNDI context

EJB Packaging
  • ejb-jar.xml (optional)
  • weblogic-ejb-jar.xml    (optional)
  • class files in package subdirectories

Java Annotations
  • EJB3 adds the ability to use ‘runtime’ annotations instead of deployment descriptors 
  • Allows self-describing code
  • Formalizes the code generation that was being done by tools like xdoclet
  • Must recompile if changed
  • Best of both worlds - can still be overridden by XML descriptors

Goals of EJB3 Persistence
  • Remove EJB3 framework from Domain Objects (for example:  tables in a database)
  • Take advantage of the new Java annotations feature
  • Reduce the amount of deployment descriptors
  • Provide sensible default values for deployment
  • Simplify environmental dependencies with Dependency Injection (via the proxy to ensure that at runtime the reference is not null – null pointer exception)
  • Increase the reusability of EJB components by moving closer to JavaBeans or POJO models
  • Overhaul the persistence model
  • Enable lightweight domain object models
  • Support inheritance and polymorphism
  • Address O/R(object to relational database) mapping configuration
  • Enhance support for EJB-QL(query language), dynamic queries (on an object) and native SQL

Enterprise Bean Business Interfaces

  • Define normal Java interface’s
  • Define a class that implements one or all of the interfaces
  • Annotate the interface or implementation bean with @Local or @Remote to explicitly define your local and remote business interfaces
  • If your implementation bean declares a single, non-annotated interface it is assumed to be the business interface and @Local
  • Annotate any callback methods that are required
  • @PostConstruct, @PreDestroy (SLSB, SFSB, MDB)
  • @PostActivate, @PrePassivate (SFSB)
  • Code any XML descriptor overrides that may be needed  usually found in subdirectory …  for example:
  • \source\resources\deployment\<project code>\ejb\META-INF\ejb-jar.xml or \persistence.xml
  • \source\resources\deployment\<project code>\metadata\application.xml

public interface MyService
    public void validateName( String name ) throws DataValidationException;

@Stateless(name = "hello", mappedName = "hello", description = "hello")
public class MyServiceBean implements MyService
    public void validateName( String name ) throws DataValidationException
        if( name == null )
            throw new DataValidationException( “Name can not be null”);

        if( name.length() > 35 )
            throw new DataValidationException( “Name > 35 characters”);

EJB3 Client Example
Default global JNDI proxy name based upon interface (global -> MyService)

public class client
    public static void main( String[] args ) throws Exception
 Properties p=new Properties();

      Context   naming  = new InitialContext();
      MyService service = (MyService) naming.lookup.lookup("hello#MyService");
      service.validateName( “Patrick Murphy” );

Dependency Injection (at time of deployment)

  • Allows removal of code to do JNDI lookups
  • Container initializes fields or calls setter methods

public class MyServiceBean
    @EJB( name=“SomeOtherService” )
    private otherService;

    private EJBContext ejbContext;

    @Resource( name=“java:/D6501DS” )
    private dataSource;

    public void validateName( String name ) throws DataValidationException
        if( name == null )
            throw new DataValidationException( “Name can not be null”);

EJB3 Interceptors

public class ServiceLogger
    public void log( InvocationContext ctx ) throws Exception
        log.info( ctx.getMethod().getName() + “ called” );
        return ctx.proceed();       

@Interceptors(ServiceLogger.class )
public class MyServiceBean
    public void validateName( String name ) throws DataValidationException
        if( name == null )
            throw new DataValidationException( “Name can not be null”);

        if( name.length() > 35 )
            throw new DataValidationException( “Name > 35 characters”);

  • Transaction is a unit of work
  • Beans are enrolled in transactions by the container
  • Transaction requirements can be set for the whole bean or per method
  • Possible Transaction Attributes:
  • Required – always runs in a transaction (either enrolls in an existing one or will start a new one), this is the default if not specified
  • RequiresNew – always runs in a new transaction (any existing transaction is suspended while the method is called)
  • Supports – enrolls in a transaction if one already exists
  • Mandatory – must be called within an existing transaction
  • NotSupported – can not be run in a transaction (any existing transaction will be suspended while the method runs)
  • Never – can not be called within a transaction

Transaction Example
@TransactionAttribute( TransactionAttributeType.REQUIRED )
public class MyServiceBean
    public void validateName( String name ) throws DataValidationException
        if( name == null )
            throw new DataValidationException( “Name can not be null”);

        if( name.length() > 35 )
            throw new DataValidationException( “Name > 35 characters”);

  • Commit happens automatically if nothing forces a rollback
  • If an error occurs, you can force a rollback by getting the EJBContext reference and calling the setRollbackOnly() method
  • Checked Exceptions can be annotated to cause automatic rollback
  • Runtime Exceptions always force rollback but can be annotated to be unwrapped
  • User can use the XML descriptors to add the attribute to existing Exception classes

@ApplicationException ( rollback=true )
public class MyException
    public MyException( String message )
        super( message );
External XML descriptors can be used to add additional metadata to existing classes.


Weblogic Domain Creation

  • After installation of  OracleEclipse weblogic server is also installed.
  • To use the weblogic server user need to configure the weblogic server in the eclipse.
  • For this differrent profile can be created on the server.
  • From Oracle Weblogic-->Weblogic Server--->
  • Select Tools--->Configuration Wizard

  • In this wizard select option Create a new Weblogic domain.
  • Click on the next button.

  • Select first option.
  • Click on the next button.

  • You can enter here your domain name or let it be deafult.
  • Similarly Domain location can be given or let it be default.
  • Click on the next button.

  • Add here user name and password.
  • Password must have one numeric value with character value.

  • Select the required jdk.
  • Select either sun jdk or jrockit

  • Here don't change any option.
  • Click on the next button.

  • Click on the create button.
  • This will start window for domain creation.

  • This is creating domain.
  • After its 100% click on the finish button.

Server Configuration in the Eclipse

  • Now we will configure the server in the eclipse.
  • For this start the eclipse.
  • Open the javaEE perspective.
  • In the bottom window, rt. click 
  • Select  the New Server

  • Select Oracle Weblogic Servre 11gR1
  • Click on the next button.

  • Now we need to select the profile.
  • Click on the browse.
  • Select the required server.

New Server

  • Now we will define the weblogic server.
  • Click the browse button.
  • Select the created domain path.
  • Click on the finish button.

  •  Now our server is showing the Weblogic server.