Enterprise java bean

Java-Examples

What is java

Java is a programming language originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them. Java applications are typically compiled to bytecode (class file) that can run on any Java virtual machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another. Java is as of 2012 one of the most popular programming languages in use, particularly for client-server web applications, with a reported 10 million users.[10][11] The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1991 and first released in 1995. As of May 2007, in compliance with the specifications of the Java Community Process, Sun relicensed most of its Java technologies under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java and GNU Classpath.

why we use java

Java is a programming language and computing platform first released by Sun Microsystems in 1995. It is the underlying technology that powers state-of-the-art programs including utilities, games, and business applications. Java runs on more than 850 million personal computers worldwide, and on billions of devices worldwide, including mobile and TV devices.
Why do I need Java?
There are lots of applications and websites that won't work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!

Usage

Java technology is a high-level programming and a platform independent language. Java is designed to work in the distributed environment on the Internet. Java has a GUI features that provides you better "look and feel" over the C++ language, moreover it is easier to use than C++ and works on the concept of object-oriented programming model. Java enable us to play online games, video, audio, chat with people around the world, Banking Application, view 3D image and Shopping Cart. Java find its extensive use in the intranet applications and other e-business solutions that are the grassroots of corporate computing. Java , regarded as the most well described and planned language to develop an applications for the Web. Java is a well known technology which allows you for software designed and written only once for an "virtual machine" to run on a different computers, supports various Operating System like Windows PCs, Macintoshes, and Unix computers. On the web aspect, Java is popular on web servers, used by many of the largest interactive websites. Java is used to create standalone applications which may run on a single computer or in distributed network. It is also be used to create a small application program based on applet, which is further used for Web page. Applets make easy and possible to interact with the Web page.

Enterprise JavaBeans

Enterprise JavaBeans (EJB) is a managed, server-side component architecture for modular construction of enterprise applications. The EJB specification is one of several Java APIs in the Java EE specification. EJB is a server-side model that encapsulates the business logic of an application. The EJB specification was originally developed in 1997 by IBM and later adopted by Sun Microsystems (EJB 1.0 and 1.1) in 1999[1] and enhanced under the Java Community Process as JSR 19 (EJB 2.0), JSR 153 (EJB 2.1), JSR 220 (EJB 3.0) and JSR 318 (EJB 3.1). The EJB specification intends to provide a standard way to implement the back-end 'business' code typically found in enterprise applications (as opposed to 'front-end' interface code). Such code addresses the same types of problems, and solutions to these problems are often repeatedly re-implemented by programmers. Enterprise JavaBeans are intended to handle such common concerns as persistence, transactional integrity, and security in a standard way, leaving programmers free to concentrate on the particular problem at hand. To deploy and run EJB beans, a Java EE Application server can be used, as these include an EJB container by default. Alternatively, a standalone container such as OpenEJB can be used.

Activities and Responsibilities

The EJB specification details how an application server provides the following responsibilities:
    Transaction processing
    Integration with the persistence services offered by the Java Persistence API (JPA)
    Concurrency control
    Eventing using Java Message Service and Java EE Connector Architecture
    Asynchronous method invocation
    Job scheduling
    Naming and directory services (JNDI)
    Remoting using RMI-IIOP and Web services
    Security (Java Cryptography Extension (JCE) and JAAS)
    Deployment of software components in an application server
    Additionally, the Enterprise JavaBean specification defines the roles played by the EJB container and the EJBs as well as how to deploy the EJBs in a container.

    Note that the current EJB 3.1 specification does not detail how an application server provides persistence (a task delegated to the JPA specification), but instead details how business logic can easily integrate with the persistence services offered by the application server.

Types of Enterprise Beans

The EJB architecture is based on the concept that in an enterprise computing system, database persistence-related logic should be independent of the business logic that relies on the data. This happens to be a very useful technique for separating business logic concerns from database concerns. This makes that business logic can deal with the business data without worrying about how the data is stored in a relational database. Enterprise JavaBeans server-side components come in two fundamentally different types: entity beans and session beans.

Basically entity beans model business concepts that can be expressed as nouns. For example, an entity bean might represent a customer, a piece of equipment, an item in inventory. Thus entity beans model real-world objects. These objects are usually persistent records in some kind of database. Session beans are for managing processes or tasks. A session bean is mainly for coordinating particular kinds of activities. That is, session beans are plain remote objects meant for abstracting business logic. The activity that a session bean represents is fundamentally transient. A session bean does not represent anything in a database, but it can access the database. Thus an entity bean has persistent state whereas a session bean models interactions but does not have persistent state.

Session beans are transaction-aware. In a distributed component environment, managing transactions across several components mandates distributed transaction processing. The EJB architecture allows the container to manage transactions declaratively. This mechanism lets a bean developer to specify transactions across bean methods. Session beans are client-specific. That is, session bean instances on the server side are specific to the client that created them on the client side. This eliminates the need for the developer to deal with multiple threading and concurrency. Unlike session beans, entity beans have a client-independent identity. This is because an entity bean encapsulates persistent data. The EJB architecture lets a developer to register a primary key class to encapsulate the minimal set of attributes required to represent the identity of an entity bean. Clients can use these primary key objects to accomplish the database operations, such as create, locate, or delete entity beans. Since entity beans represent persistent state, entity beans can be shared across different clients. Similar to session beans, entity beans are also transactional, except for the fact that bean instances are not allowed to programmatically control transactions. These two types of beans are meant for synchronous invocation. That is, when a client invokes a method on one of the above types, the client thread will be blocked till the EJB container completes executing the method on the bean instance. Also these beans are unable to service the messages which comes asynchronously over a messaging service such as JMS. To overcome this deficiency, the EJB architecture has introduced a third type of bean called message-driven bean. A message-driven bean is a bean instance that can listen to messages from the JMS. Unlike other types of beans, a message-driven bean is a local object without home and remote interfaces. In a J2EE platform, message-driven beans are registered against JMS destinations. When a JMS message receives a destination, the EJB container invokes the associated message-driven bean. Thus message-driven beans do not require home and remote interfaces as instances of these beans are created based on receipt of JMS messages. This is an asynchronous activity and does not involve clients directly. The main purpose of message-driven beans is to implement business logic in response to JMS messages. For instance, take a B2B e-commerce application receiving a purchase order via a JMS message as an XML document. On receipt of such a message in order to persist this data and perform any business logic, one can implement a message-driven bean and associate it with the corresponding JMS destination. Also these beans are completely decoupled from the clients that send messages.

An EJB container holds two major types of beans:


1.Session Beans  that can be either "Stateful", "Stateless" or "Singleton" and can be accessed via either a Local (same JVM) or Remote (different JVM) interface or directly without an interface,[4] in which case local semantics apply. All session beans support asynchronous execution[5] for all views (local/remote/no-interface). Message Driven Beans (also known as MDBs or Message Beans). MDBs also support asynchronous execution, but via a messaging paradigm.

Session beans

a.Stateful Session Beans
Stateful Session Beans are business objects having state: that is, they keep track of which calling client they are dealing with throughout a session and thus access to the bean instance is strictly limited to only one client at a time.In case concurrent access to a single bean is attempted anyway the container serializes those requests, but via the @AccessTimeout annotation the container can throw an exception instead. Stateful session beans' state may be persisted (passivated) automatically by the container to free up memory after the client hasn't accessed the bean for some time. The JPA extended persistence context is explicitly supported by Stateful Session Beans.
Examples
Checking out in a web store might be handled by a stateful session bean that would use its state to keep track of where the customer is in the checkout process, possibly holding locks on the items the customer is purchasing (from a system architecture's point of view, it would be less ideal to have the client manage those locks)


2.Stateless Session Beans

Stateless Session Beans[10] are business objects that do not have state associated with them. However, access to a single bean instance is still limited to only one client at a time and thus concurrent access to the bean is prohibited.[7] In case concurrent access to a single bean is attempted anyway the container simply routes each request to a different instance.[11] This makes a stateless session bean automatically thread-safe. Instance variables can be used during a single method call from a client to the bean, but the contents of those instance variables are not guaranteed to be preserved across different client method calls. Instances of Stateless Session beans are typically pooled. If a second client accesses a specific bean right after a method call on it made by a first client has finished, it might get the same instance. The lack of overhead to maintain a conversation with the calling client makes them less resource-intensive than stateful beans.
Examples
Sending an e-mail to customer support might be handled by a stateless bean, since this is a one-off operation and not part of a multi-step process. A user of a website clicking on a "keep me informed of future updates" box may trigger a call to an asynchronous method of the session bean to add the user to a list in the company's database (this call is asynchronous because the user does not need to wait to be informed of its success or failure). Fetching multiple independent pieces of data for a website, like a list of products and the history of the current user might be handled by asynchronous methods of a session bean as well (these calls are asynchronous because they can execute in parallel that way, which potentially increases performance). In this case, the asynchronous method will return a Future instance.


3.Singleton Session Beans
Singleton Session Beans[12][13] are business objects having a global shared state within a JVM. Concurrent access to the one and only bean instance can be controlled by the container (Container-managed concurrency, CMC) or by the bean itself (Bean-managed concurrency, BMC). CMC can be tuned using the @Lock annotation, that designates whether a read lock or a write lock will be used for a method call. Additionally, Singleton Session Beans can explicitly request to be instantiated when the EJB container starts up, using the @Startup annotation.
Examples
Loading a global daily price list that will be the same for every user might be done with a singleton session bean, since this will prevent the application having to do the same query to a database over and over again.


4.Message driven beans

Message Driven Beans[14] are business objects whose execution is triggered by messages instead of by method calls. The Message Driven Bean is used among others to provide a high level ease-of-use abstraction for the lower level JMS (Java Message Service) specification. It may subscribe to JMS message queues or message topics, which typically happens via the activationConfig attribute of the @MessageDriven annotation. They were added in EJB to allow event-driven processing. Unlike session beans, an MDB does not have a client view (Local/Remote/No-interface), i. e. clients cannot look-up an MDB instance. It just listens for any incoming message on, for example, a JMS queue or topic and processes them automatically. Only JMS support is required by the Java EE spec,[15] but Message Driven Beans can support other messaging protocols.[16][17] Such protocols may be asynchronous but can also be synchronous. Since session beans can also be synchronous or asynchronous, the prime difference between session- and message driven beans is not the synchronicity, but the difference between (object oriented) method calling and messaging.
Examples
Sending a configuration update to multiple nodes might be done by sending a JMS message to a 'message topic' and could be handled by a Message Driven Bean listening to this topic (the message paradigm is used here, since the sender does not need to have knowledge about the amount of consumers or their location or even their exact type). Submitting a job to a work cluster might be done by sending a JMS message to a 'message queue' and could also be handled by a Message Driven Bean, but this time listening to a queue (the message paradigm and the queue is used, since the sender doesn't have to care which worker executes the job, but it does need assurance that a job is only executed once). Processing timing events from the Quartz scheduler can be handled by a Message Driven Bean; when a Quartz trigger fires, the MDB is automatically invoked. Since Java EE doesn't know about Quartz by default, a JCA resource adapter would be needed and the MDB would be annotated with a reference to this.


5.Entity beans (deprecated)

Previous versions of EJB also used a type of bean known as an Entity Bean. These were distributed objects having persistent state. Beans in which their container managed the persistent state were said to be using Container-Managed Persistence (CMP), whereas beans that managed their own state were said to be using Bean-Managed Persistence (BMP). In EJB 3.0, Entity Beans were replaced by the Java Persistence API, which was completely separated to its own specification to allow the EJB specification to focus only on the "core session bean and message-driven bean component models and their client API".[19] Entity Beans are still available in EJB 3.1 for backwards compatibility, but they have been officially proposed to be removed from the specification (via a process called "pruning").[20] Before being actually removed from the specification, Entity Beans will first be made optional by moving them to the EJB Optional Features part of the specification in EJB 3.2.[21] Other types of Enterprise Beans have been proposed. For instance, Enterprise Media Beans (JSR 86) address the integration of multimedia objects in Java EE applications.

Session Beans: Stateful and Stateless

Session beans can be either stateful or stateless. Stateful session beans maintain conversational state when used by a client. Conversational state is not written to a database but can store some state in private variables during one method call and a subsequent method call can rely on this state. Maintaining a conversational state allows a client to carry on a conversation with a bean. As each method on the bean is invoked, the state of the session bean may change and that change can affect subsequent method calls.
Stateless session beans do not maintain any conversational state. Each method is completely independent and uses only data passed in its parameters. One can specify whether a bean is stateful or not in the bean's deployment descriptor.

Entity Beans: Container and Bean Managed Persistence

An example entity bean in a B2B application is given as follows. A purchase order is a business identity and requires persistence store such as a relational database. The various purchase order attributes can be defined as the attributes of an entity bean. Since database operations involve create, update, load, delete, and find operations, the EJB architecture requires entity beans to implement these operations. Entity beans should implement the javax.ejb.EntityBean interface that specifies the load and delete operations among others. In addition, the bean developer should specify the appropriate create and find methods on the home interface, and provide their implementation in an entity bean.
There are two types of entity beans and they are distinguished by how they manage persistence. Container-managed beans have their persistence automatically managed by the EJB container. This is a more sophisticated approach and here the bean developer does not implement the persistence logic. The developer relies on the deployment descriptor to specify attributes whose persistence should be managed by the container.
The container knows how a bean instance's fields map to the database and automatically takes care of inserting, updating, and deleting the data associated with entities in the database. Beans using bean-managed persistence do all this work explicitly: the bean developer has to write the code to manipulate the database. The EJB container tells the bean instance when it is safe to insert, update, and delete its data from the database, but it provides no other help. The bean instance has to do the persistence work itself.

EJB Container or EJB Server

Enterprise JavaBeans (EJB) Server is a component transaction server. It supports the EJB server-side component model for developing and deploying distributed, enterprise-level applications in a multi-tiered environment. It provides the framework for creating, deploying, and managing middle-tier business logic. In a three-tier environment, the client provides the user interface logic, the business rules are separated to the middle tier, and the database is the information repository. The client does not access the database directly. Instead, the client makes a call to the EJB Server on the middle tier, which then accesses the database.


The three tiers can reside on different machines or on the same machines. EJB Server is designed to reside on the same machine as the database engines it serves. Because the servers are on the same machine, EJB Server can communicate with the database using Adaptive Server's high-speed, sharedmemory JDBC driver. This approach ensures:
    . High-speed communication and data transfer, even for large data sets
    . Secure data transmission because the transfer of information from the third
tier to the middle tier does not take place over the network EJB components (or Beans) are reusable modules of code that combine related tasks (methods) into a well-defined interface. EJB components contain the methods that execute business logic and access data sources. You (or the Administrator) install the component's executable code on EJB Server. Any number of independent Java or EJB applications (clients) can use the EJBs.There are three types of Enterprise JavaBeans: stateful session Beans, stateless session Beans, and entity Beans. Each type of bean is a set of methods and is responsible for different tasks on behalf of the client.All session Bean instances are transient. They maintain a one-to-one relationship with the client. They perform tasks, and can store information in the database on the client's behalf. Stateful session Beans manage complex tasks that require the accumulation of data. Stateless session Beans manage tasks that do not store data between method calls. Entity Bean instances are persistent. They represent underlying objects, typically a particular row in a database. All three bean types work together to process a request and return information to the client.

Versions


EJB 3.1, final release (2009-12-10)


JSR 318. The purpose of the Enterprise JavaBeans 3.1 specification is to further simplify the EJB architecture by reducing its complexity from the developer's point of view, while also adding new functionality in response to the needs of the community: Local view without interface (No-interface view)
    .war packaging of EJB components
    EJB Lite: definition of a subset of EJB
    Portable EJB Global JNDI Names
    Singletons (Singleton Session Beans)
    Application Initialization and Shutdown Events
    EJB Timer Service Enhancements
    Simple Asynchrony (@Asynchronous for session beans)

EJB 3.0, final release (2006-05-11)

    JSR 220 - Major changes: This release made it much easier to write EJBs, using 'annotations' rather than the complex 'deployment descriptors' used in version 2.x. The use of home and remote interfaces and the ejb-jar.xml file were also no longer required in this release, having been replaced with a business interface and a bean that implements the interface.
    EJB 2.1, final release (2003-11-24)

      JSR 153 - Major changes:
      Web service support (new): stateless session beans can be invoked over SOAP/HTTP. Also, an EJB can easily access a Web service using the new service reference.
      EJB timer service (new): Event-based mechanism for invoking EJBs at specific times.
      Message-driven beans accepts messages from sources other than JMS.
      Message destinations (the same idea as EJB references, resource references, etc.) has been added.
      EJB query language (EJB-QL) additions: ORDER BY, AVG, MIN, MAX, SUM, COUNT, and MOD.
      XML schema is used to specify deployment descriptors, replaces DTDs


    EJB 2.0, final release (2001-08-22)

      JSR 19 - Major changes: Overall goals:
      The standard component architecture for building distributed object-oriented business applications in Java.
      Make it possible to build distributed applications by combining components developed using tools from different vendors.
      Make it easy to write (enterprise) applications: Application developers will not have to understand low-level transaction and state management details, multi-threading, connection pooling, and other complex low-level APIs.
      Will follow the "Write Once, Run Anywhere" philosophy of Java. An enterprise Bean can be developed once, and then deployed on multiple platforms without recompilation or source code modification.
      Address the development, deployment, and runtime aspects of an enterprise application's life cycle.
      Define the contracts that enable tools from multiple vendors to develop and deploy components that can interoperate at runtime.
        Be compatible with existing server platforms. Vendors will be able to extend their existing products to support EJBs.
        Be compatible with other Java APIs.
        Provide interoperability between enterprise Beans and Java EE components as well as non-Java programming language applications.
        Be compatible with the CORBA protocols (RMI-IIOP).

      EJB 1.1, final release (1999-12-17)

        Major changes:
        XML deployment descriptors
        Default JNDI contexts
        RMI over IIOP
        Security - role driven, not method driven
        Entity Bean support - mandatory, not optional
        Goals for Release 1.1:
        Provide better support for application assembly and deployment.
        Specify in greater detail the responsibilities of the individual EJB roles.

      EJB 1.0 (1998-03-24)

        Announced at JavaOne 1998,[41] Sun's third Java developers conference (March 24 through 27) Goals for Release 1.0:
        Defined the distinct "EJB Roles" that are assumed by the component architecture.
        Defined the client view of enterprise Beans.
        Defined the enterprise Bean developer's view.
        Defined the responsibilities of an EJB Container provider and server provider; together these make up a system that supports the deployment and execution of enterprise Beans.

Download EJB-jar file

Download ejb.jar
Click Here to download Ejb jar file