Tuesday, November 22, 2011

JAX-WS SOAP Web Services - code first

In this post I am going to show you how to create a simple Java SOAP Web Service.

As the name suggests, a web service is a kind of webified application, that is, an application typically delivered over HTTP (Hyper Text Transport Protocol). A web service is thus a distributed application whose components can be deployed and executed on distinct devices.

Web services can be divided into two groups, SOAP-based and REST-style.
SOAP originally stood for Simple Object Access Protocol but, by serendipity, now may stand for Service
Oriented Architecture (SOA) Protocol. Whatever SOA may be, web services play a central role in the SOA approach to software design and development.  For now, SOAP is just an XML (EXtensible Markup Language) dialect in which documents are messages. In SOAP-based web services, the SOAP is mostly unseen infrastructure. For example, in a typical scenario, called the request/response message exchange pattern (MEP), the client’s underlying SOAP library sends a SOAP message as a service request, and the web service’s underlying SOAP library sends another SOAP message as the corresponding service response. The client and the web service source code may provide few hints about the underlying SOAP.

Except in test mode, the client of either a SOAP-based or REST-style service is rarely a web browser but rather an application without a graphical user interface. The client may be written in any language with the appropriate support libraries. Indeed, a major appeal of web services is language transparency: the service and its clients need not be written in the same language. Language transparency is the key to web service
interoperability; that is, the ability of web services and requesters to interact seamless despite differences in programming languages, support libraries, and platforms.

If a SOAP-based web service written in Java can have a Perl or a Ruby consumer, there must be an intermediary that handles the differences in data types between the service and the requester languages.
XML technologies, which support structured document interchange and processing, act as the intermediary. For example, in a typical SOAP-based web service, a client transparently sends a SOAP document as a request to a web service, which transparently returns another SOAP document as a response.


Calculator Web Service Example:


This is a simple SOAP web service that exposes four methods that are the main calculation operation. All the required libraries to compile, execute and consume Web Services are part of Standard Java 6, that supports JAX-WS (Java API for XML-Web Services).

A SOAP-based web service could be implemented as a single Java class but, following best practices, there should be an interface that declares the methods, which are the web service operations, and an implementation, which defines the methods declared in the interface. The interface is called the SEI: Service Endpoint Interface. The implementation is called the SIB: Service Implementation Bean. The SIB can be either a POJO or a Stateless Session EJB (Enterprise Java Bean).

The picture below shows the SEI (Service Endpoint Interface) for the Calculator Web Service.
It exposes the four web service's methods: add, substract, multiply, divide.






















The annotation @WebService signals that this is the SEI (Service Endpoint Interface).
@WebMethod signals that each method is a service operation.

The @SOAPBinding annotation impacts the under-the-hood construction of the service contract, the WSDL  (Web Services Definition Language) document. In my interface I used default values for this annotation, so it could be omitted. It specifies message style (DOCUMENT or RPC), encoding (LITERAL or SOAP ENCODED) and parameter style (WRAPPED or BARE).

Next picture shows the SIB (Service Implementation Bean) that implements the methods listed by the previous interface:


























The @WebService property endpointInterface links the SIB (this class) to the SEI (com.faeddalberto.calculator.CalculatorWSImpl). Note that the method implementations are not annotated as @WebMethods because those were already defined as web service methods in the interface.

The two files are compiled in the usual way from the current working directory, which in this case is immediately above the subdirectory "com". The symbol % represents the command prompt:

% javac com/faeddalberto/calculator/*.java


Now that we have successful compiled our web service we need to invoke, from the working directory,  the wsgen utility that comes with Java 6: 


% wsgen –cp . com.faeddalberto.calculator.CalculatorWSImpl

This utility generates some artifacts: java types needed by the Endpoint.publish to generate the service’s WSDL.
 The simplest way to publish a web service in a development/test environment is using a simple Java SE Application.

















This application publishes the web service whose SIB is com.faeddalberto.calculator.CalculatorWSImpl. For now, the service is published at network address 127.0.0.1., which is localhost, and the publication path is /calculator, an arbitrary name.
The Endpoint class has an overloaded publish method. In this two-argument version, the first argument is the  publication URL as a string and the second argument is an instance of the service SIB, in this case  com.faeddalberto.calculator.CalculatorWSImpl.
The application runs indefinitely, awaiting service requests. It needs to be terminated at the command prompt with control-C  or the equivalent.
Once the applicatation is started, open a browser to the URL  http://127.0.0.1/calculator?wsdl  to view the service contract, the WSDL document. This is an easy test to determine whether the service has deployed successfully. If the test succeeds, a client then can be executed against the service.

If everything is going well during the web service publication, you will see the following WSDL (Web Service Descriptor Language) on your browser page: 


In one of my next posts I'll describe the various parts of an WSDL document.

Associated to the Web Service contract there is also an XSD document describing the types for every request and response. If you open a browser to the URL http://127.0.0.1/calculator?xsd=1 you can see this: 


The types defined by the previou XSD are add, substract, multiply and divide (for the requests) and the same type name with the string Response attached for the web service responses. 
If you scroll above in the post you'll see that the wsgen utility used to create artifacts has created these types as Java classes: it means that that utility uses JAX-B to create java types associated to xsd elements needed by the web service to create the WSDL document and to marshal and unmarshal requests and responses. 

In full production mode, a Java Application Server such as BEA WebLogic, GlassFish, JBoss, or WebSphere might be used. To deploy our web service into an application server we need to create the WAR (Web Archive), and to do so we need to invoke the jar utility:

% jar cvf calculator.war WEB-INF

in which calculator.war is the name of the war we are creating and WEB-INF is the folder into which we have our class files to put into the war. Once created we can deploy it in the application server we choose and restart it. As we've done with our simple Jave SE application, once the applicatation server is started, open a browser to the URL  http://127.0.0.1/calculator?wsdl  to view the service contract, the WSDL document. This is an easy test to determine whether the service has deployed successfully.



Now that we have our web service up and running its time to call it and verify that it works.
We need now to create a web service client, and we can do it in different ways.
I show you a dynamic client and a static client both developed as a simple Java SE application but the same clients could also be used in a Java EE application Servlet or another utility class.

Dynamic client:

The first client I show you Is the dynamic solution:


This java class uses a URL object with a query string pointing to the WSDL location.
It then creates an XML qualified name, which has the syntax namespace URI:local name. A URI is a Uniform Resource Identifier and differs from the more common URL in that a URL specifies a location, whereas a URI need not specify a location. In short, a URI need not be a URL. In this example, the namespace URI is provided in the WSDL, and the local name is the SIB class name CalculatorWSImpl  with the word Service appended. The local name occurs in the service section, the last section of the WSDL document.
Once the URL and QName objects have been constructed and the Service.create method has been invoked, the statement of interest:

CalculatorWS calculator = service.getPort(CalculatorWS.class);

executes. In the WSDL document, the portType section describes, in the style of an interface, the operations included in the web service. The getPort method returns a reference to a Java object that can invoke the portType operations. The port object reference is of type com.faeddalberto.calculator.CalculatorWS, which is the
SEI type.

The Java client invokes the web service methods; and the Java libraries generate and process the SOAP messages exchanged transparently to enable the successful method invocations.


Static client:

In this section we will develop a standalone, static web service client to the Calculator web service
developed above. First all the static artifacts needed are generated using the wsimport tool. Note that the Calculator web service must be running when generating the artifacts, in order for wsimport to be able to access the WSDL document of the service.

% wsimport -p com.faeddalberto.calculator.staticclient -keep http://127.0.0.1/calculator?wsdl

This utility generates various classes in the subdirectory com.faeddalberto.calculator.staticclient (the -p flag stands for package). These classes make it easier to write a client against the service.
The list of the generated artifacts: 


Three points about these generated source files deserve mention. First, the interface CalculatorWS declares the very same methods as the original SEI. The methods are the web service operation add, substract, multiply, divide. Second, the class CalculatorWSImplService has a no-argument constructor that constructs the very same Service object as the original Java client DynamicCalculatorClient. Third, CalculatorWSImplService encapsulates the getcalculatorWSImplPort method, which returns an instance of type CalculatorWS, which in turn supports invocations of the four web service operations. Together the two generated types, the interface CalculatorWS and the class CalculatorWSImplService, ease the task
of writing a Java client against the web service. Next picture shows a client that uses the client-support code from the wsimport utility:


















This client is functionally equivalent to the previous, but this client is far easier to write. In particular, trouble some yet critical details such as the appropriate QName and service endpoint now are hidden in the wsimport-generated class. The idiom that is illustrated here works in general for writing clients with help from WSDL-based artifacts such as CalculatorWS and CalculatorWSImplService:

  • First, construct a Service object using one of two constructors in the wsimport generated class, in this example client.CalculatorWSImplService. The no-argument constructor is preferable because of its simplicity. However, a two-argument constructor is also available in case the web service’s namespace (URI) or the service endpoint (URL) have changed. Even in this case, however, it would be advisable to regenerate the WSDL-based Java files with another use of the wsimport utility.
  • Invoke the get...Port method on the constructed Service object, in this example, the method getCalculatorWSImpllPort. The method returns an object that encapsulates the web service operations declared in the original SEI.


Next picture shows the result for this client:


This was just a simple web service. There are different other ways of writing web services and clients against them, I'll show you on my next posts. 






Monday, November 14, 2011

Spring 3 with Hibernate, Maven 2 and Apache Tiles

In this post I show you how to create a java mavenized application using Spring MVC 3 and Hibernate.
I am using Springsource Tool Suite (STS) that is an Eclipse-like IDE that semplifies the development of Mavenized applications with Spring framework.

Once created a new Maven Web project through the wizard, we need to modify the pom.xml file that is the Maven configuration file that allows us to define the application name, developers, company informations, etc.
But, most important, it allows us to define the libraries required to develope the application and some Maven plugins, such as the one that builds and compiles the application.


In the first part of the pom file we can find information such as the application name, version, and the developers that work on it.
Then, we have the dependencies, that are the libraries required to develop the application. Among these, there are Junit and Mokito (used for testing purposes), log4j used for logging purposes, Apache Tiles that is the apache library to create structured web pages made of "jsp fragments" (I will show you later how to define pages based on tiles). Then we have the validation library used by Hibernate to validate data inserted on web page forms.
We can then find a set of dependencies for the Spring framework (core, expressions, bean, aop, context, web, test, orm) used to control all the application tiers. After these, Hibernate library used for the Object Relational Mapping and query the database. Then we have AspectJ that is used to define aspects to control crosscutting concerns of the application.
Lastly I have defined the build plugin of maven that it uses to build the application and package it in the format defined in the first part of the pom.


Now that we have defined the libraries needed for the development of our application, we can define the web.xml file that handles the requests from the clients and defines other important files for the application management.


From the web.xml file we can see that the application is managed by Spring framework.
We have defined 2 listeners:

  • the first is the Log4jConfigurationListener that loads the log4j configuration file which location is defined in the context-param named  "log4jConfigLocation" and its location is inside the devconn folder in the root path of the application server; 
  • the second listener is the ContextLoaderListener that is used by Spring to load its configuration files. The associated context-param, loads a list of spring configuration files: applicationContext-aspect.xml in which I have defined some aspects that manage crosscutting concerns; applicationContext-data.xml in which I have defined beans that have to do with database (datasource, hibernate session factory, and dao classes); applicationContext-mail.xml which defines beans to send email. 
Under the definition of listeners, we find the definition of a servlet managed by the Spring DispatcherServlet  which is associated to another spring configuration file that defines the beans that manage the user requests and other web utilities who's name is spring-mvc-servlet.xml
Lastly I have defined the taglib location for the definition of tiles.

The next step is the definition of the spring-mvc-servlet.xml that manages the user requests: 


First of all we can see the import od XML Schema Definitions for the different Spring components used in the configuration file. Then we have the definition of the location for the static resources such as images, css... . 
Then we define that the mvc components are annotation-driven, it means that there is not the definition of Spring Controller beans in xml configuration files but those components are defined using Spring annotations (I will show you later). If we want automatic generation of proxies, we will use the tag <aop:aspectj-autoproxy/> through the AOP namespaces. 
After the definition of base-package we have the definition of  two beans about the configuration (which defines the configuration file) and resolution of Tiles. 
Lastly we have the definition of some beans about the message bundle and internationalization

The next step is the definition of a Spring Controller that is the handler for a user request, and I show you the controller for the user registration process: 


The first instruction in the above picture is the @Controller annotation that defines this class as a Spring controller. The second instruction defines the attributes that will be added to the HttpSession. 
Then we have another annotation, that is the @RequestMapping annotation and defines the path at which this controller will be called. 
The controller has three instance variables; these are injected to the controller as dependencies at construction time by the Spring framework that searches on his context configuration files for  beans definitions that have the same type and name of the one required by the controller. The constructor has the @Inject annotation that asks Spring to find and inject the required beans. 
Then we have two methods both preceded by the @RequestMapping annotation that defines the Http request method, and the first one answers to a GET request while the second answers to a POST request at the same address, that is the one defined above.
The first method inserts some attributes into the model object such as a new DevProfile object that has to be filled by the registration form and some other attributes containing objects needed to define the registration form. 
The second method receives the registration form, and has some input parameters related to the filled form. We can see the @Valid annotation before the DevProfile object that is used for validation purposes based on rules defined in the DevProfile entity class. If one or more of these validation rules is not satisfied the response returns to the input page showing the errors, else it saves the DevProfile into the database and after  sending a registration confirmation email, shows a login page as a result of a successful registration. 
Both the methods return a String that represents the name of the view to be showed. 
Spring searches the view definition corresponding to the returned String through the TilesViewResolver defined precedently in the spring-mvc configuration file. 

The next step is the definition of the tiles and the corresponding views made of jsp fragments. 


As we can see from the above image, every tile definition is made of many jsp fragments and other attributes such as CSS files and the page title. The first definition is called baseLayout and defines exactly a base layout that the other definition extend and modify based on their purposes. Continuing the analization of the baseLayout definition, we see that it defines a page template with a jsp page (that I show you later). The template is the definition of a page layout, that we can see in the picture below: 


The attributes added on the definition are the page title, the css style for the page content, the header of the page called top, the left side, the body called content and the footer.
The other tiles definitions, as I wrote earlier, extend this baseLayout definition and override values based on the content that has to be displayed on the resulting page. 

I show you now the jsp page template:


First of all at the top of the page there is the import of the tiles tag lib that we defined in the web.xml file.
As we can see, the image above also illustrates the attributes that we have defined precedently in the tiles configuration file. Inside the head tag, we have the page title attribute and the import of the css defined in the tiles configuration file and other default css files. 
Inside the body tag we can find the jsp fragments top, left, content and bottom. 

Now I show you the body part of the registration tile, that contains the registration form. 


At the top of the page we have the tag libs import (jsp core, spring, and spring form). Using the form tag of the spring form tag library we then define the registration form in which can find the modelAttribute that is the new DevProfile object we inserted into the model object in the RegistrationController and define the HTTP method attribute as POST that is used by the framework to call the method we've defined in the controller and annotated with the RequestMapping annotation with a POST value for the method. attribute. 
The message tag of the spring tag lib is used to show a label which value to be displayed is read from the message bundle defined in the spring context file. 
I have separated the personal information and account information with two fieldset. The first one contains personal informations such as name, surname, gender, date of birth in which name and surname are simple input text fields, while gender and birthday fields are made with spring select tags that use some of the attributes inserted into the model object on the RegistrationController class. 
The second fieldset contains account informations email and password for the user that wants to register. 
You can also find spring form errors tag for every field that requires validation. If the values inserted in the field does not pass the validation, the tag shows the error under that field. 
Lastly we have the confirmation button that once clicked sends the request to the RegistrationController's method. 


Now I show you the definition of a fragment of the DevProfile entity class that is a simple java POJO with validation annotation over some fields through which it is possible to manage validation on web forms.


As you can see, with simple annotations over the fields we can control form validation. There is not the need to tell you what the annotations mean because you can just read these and understand on your own that the name’s size must be between 3 and 25, Gender could not be empty, etc…

Now is the time to introduce AOP with Aspectj to control crosscutting concerns such as logging. I have, indeed, used an aspect to manage logging on controllers.
First of all, as you remember, in the web.xml I defined an applicationContext-aspect.xml configuration file into which I have defined aspect beans. Let's see the configuration file: 


The picture above shows the configuration of a bean used as an aspect for logging purposes.
We define aspects using the spring aop XML Schema components. Inside the <aop:config> tag we define the different components of an aspect: the pointcut tag defines where the advice should be called, in my case the expression “execution (* com.faeddalberto.devconn.controller.*.*(..)) “  tells aspectj to call the advice every time a method with any number of parameters of the classes in the com.faeddalberto.devconn.controller package is called. After the definition of the pointcut we find in the configuration the definition of the loggingAspect with two advices, one before and one after the execution of an application method, called joinpoint. We can obtain the same result using one only advice, called around that is called before entering the joinpoint method and after exiting it.
Let’s now give a look at the class defined as aspect:


 As you can see it is a simple Java class with two methods used for logging purposes. Both methods have a parameter that is JoinPoint. It has some utility methods that give us the opportunity to figure out which is the class that has been called and its method name and some other utilities.

Another application configuration file that I listed in the web.xml file is the applicationContext-data.xml that is used to define database related beans and Hibernate session factory bean. Let’s give it a look:



The first important thing in this context file is the jndi-lookup tag: it searches for a component with a name defined in the jndi-name attribute using jndi lookup. We are using this way to find and define the dataSource that configures the database connection.
Another important bean definition is the sessionFactory, that is the Hibernate most important bean to which we inject the datasource defined earlier and a list of mapping resources files (Object Relational Mapping), I am showing only two of the orm files I have in my project. We than define hibernate properties: I am only defining the dialect to be used to query the database. We know that in the java code we use HQL that is Hibernate Query Language to define queries; these queries are then translated using the dialect here into SQL to query the database in a language understandable by it.
After the definition of the session factory we define the transaction manager injecting the session factory bean.
Lastly I show you the definition of two beans, that are the DAO classes for two entities, into which we can find the methods used to perform CRUD operations.

In the next picture I’ll show you the ORM file for the DevProfile entity:



In the picture above I am mapping the DevProfile class to the profile database table defining the table columns associated with the java fields, the corresponding data type and the relations with other database tables mapped to other java classes using one-to-one or one-to-many or many-to-one tags and set tag to define a collection of related columns.

 The next part of the application that I want to show you is the implementation of DAO, let's start:


In the picture above we have the interface that lists the main operations on entities. The <T> is a placeholder for the type you pass in. In other words, whatever Tis when you declare the interface, that's what you can use with methods. Let's give a loot at the implementation of this interface: 


The picture above, shows the IDAO implementation, I called it AbstractDao because it is a common implementation that would be extended by the entities DAOs as needed. The EntityDAO will then have a constructor with 3 parameters: tableName, orderFieldName and entityClass. The methods in this class are simple methods that execute the Hibernate operations to Create, Read, Update, Delete, Flush, FindById, Merge, etc... 

Next I show you the extended DAO for the DevProfile entity: 


In the image above, I have created the DevProfileDao to execute the previous methods on the DevProfile entity, the only thing I did is creating a constructor passing the parameters to the super (AbstractDao) and if I need any other query, I do create new methods in this class. 

Next I show you the unit test for the RegistrationController: 


Finally I show you the registration page and the login page of the application:


Next is the registration page with error fields: 


The next picture is the login page, showed when registration is successfull: 





Tuesday, August 30, 2011

EJB 3 Security

The Java EE/EJB security framework provides both declarative and programmatic security.
The most basic ideas in security are Authentication and Authorization.

Authentication: Authentication is the process of verifying user identity. The most common method of authentication is by checking username and password.

Authorization: Authorization is the process of determining wether a user has access to a particular resource or task, and it is accomplished once a user is authenticated.

EJB 3 and Java EE security
Java EE security is largely based on Java Authentication and Authorization API (JAAS). JAAS essentially separates the authentication and authorization system from the Java EE application.

JAAS is designed so that both the authentication and authorization steps can be performed at any Java EE tier, including the web and EJB tiers. However, most Java EE applications are web accessible and share an authentication system across tiers. JAAS fully leverages this reality and once a user is authenticated at any Java EE tier, the authentication context is passed through tiers whenever possible, instead of repeating the authentication step. The Principal object we represents this sharable, validated authentication context.

A successful authentication results in a valid user Principal. At this point, the Principal is associated with one or more roles. For each secured web/EJB tier resource, the application server checks if the principal/role is authorized to access the resource.

EJB authentication and authorization

Like transaction management, authentication can be either declarative or programmatic, each of which provides a different level of control over the authentication process. In addition, like the transaction management, security applies to session beans and MDBs, and not the JPA entities.

Declarative security
In the next picture I show how declarative security works in my CartManagerBean. It includes a cancelItem method that only ADMIN can use.


This chunk of code, shows some of the security annotations used for declarative security:
javax.annotation.security.DeclareRoles, javax.annotation.security.RolesAllowed, and  javax.annotation.security.PermitAll. Two other annotations that we have not used but will disifcuss are javax.annotation.security.DenyAll and javax.annotation.security.RunAs.

DeclareRoles: There are different ways of declaring roles, one of those is using the DeclareRoles annotation. This annotation applies either at class level or the method level and consists of an array of role names. In the above image I declared that CarlManagerBean uses ADMIN and BUYER roles. If we never declare roles, the container will authomatically build a list of roles by inspecting the @RolesAllowed annotation. Roles at deployment time must be mapped to groups in the runtime security environment.

RolesAllowed: This method can be applied on either an EJB business method or an entire class. When applied to the entire class, it tells the container which roles are allowed to access any method. On the other hand, when applied on a method, we declare a list of roles that can access that particular method. In the previous code I declare that only ADMIN role can access the cancelItem() method.

PermitAll & DenyAll: We can use PermitAll annotation to declare that any role can access the entire class or an EJB business method. We used this annotation on the showCart() method to instruct that any role can retrieve and see all the Items of the cart. You should use this annotation carefully especially at class level to not leave security holes in the application. DenyAll annotation does the opposite of the PermitAll. It renders the functionality inaccessible by any role. It could be useful if you consider that your application may be deployed in wide-ranging environments. You can invalidate methods or classes that might be inappropriate for a particular environment without changing the code but only using the DenyAll annotation. When applied at the method level, as the RolesAllowed annotation, it overrides the class level authorization settings.


The three security annotations, @PermitAll, @DenyAll, and @Role-
Allowed, cannot simultaneously be applied to the same class or the
same method.


RunAs: This annotation comes in hand if you want dinamically assign a role to the Principal in scope of an EJB method invocation. You want to do this for example if you want to invoke an EJB from your method but the other EJB requires a role that is different from the one that is in scope.


As you can see, declarative security gives you access to a powerful authentication framework while staying mostly out of the way. If you have ever rolled out your own security or authentication system, one weakness might have crossed your mind already. The problem is that although you can authenticate a role using declarative security, what if you need to provide security settings specific to individuals, or even simple changes in method behavior based on the current Principal’s role? This is where programmatic EJB security steps onto the stage.


Using EJB programmatic security
Programmatic security provides direct access to the Principal and to check the Principal's role in the code. Those methods are made available by the EJB context.



In the above code we first injects the EJB context. We use the isCallerInRole() method of the EJBContext to see if the underlying authenticated principal has the ADMIN role. If it does not, we throw a  java.lang.SecurityException notifying the user about the authorization violation. Otherwise, the bid cancellation method is allowed to proceed normally.

isCallerInRole() & getCallerPrincipal()
Programmatic security is made up of the previously mentioned methods. These methods are defined in the javax.ejb.EJBContext interface.
Talking about the isCallerInRole() method, the context behind the scenes retrieves the Principal object associated with the current thread and checks if one of the roles matches the one you provided.
The getCallerPrincipal() method gives you direct access to the java.security.Principal representing the current authentication context.
The only interesting method in the Principal object is the getName() method, that most of the times is the name of the login validated user. Note, though, that there is not guarantee on what the Principal name might return. Depending on your environment it could return the group name, the role name or something in relation with the security role it belongs to.

Wednesday, June 22, 2011

EJB 3 Transactions

Transactions in EJB 3 are provided through the Java Transaction API (JTA).
For the most part a developer uses the javax.transaction.UserTransaction interface, this is because the container takes care of most transaction management. The developer simply tells the container where the transaction begins and ends (transaction demarcation) and wether to rollback or commit.
There are two ways of managing transactions: CMT (Container-manager Transactions) and BMT (Bean-managed Transactions). The first one is a declarative transaction with annotations or the deployment descriptor. The BMT, on the other hand, requires the developer to manage transactions programmatically. 
In this version of EJB only session beans and message driven beans support BMT, while entity doesn't dipend directly on CMT or BMT but can plug indifferently into any transaction environment while inside of a container. 

Container-managed Transactions: 
In container-managed transactions, the container starts, commits or rollbacks the transaction on our behalf. The start and end of a transactions are always marked the start and end of EJB business methods. 
All we have to do is tell the container to manage the transaction by using annotations or deployment descriptors. By default the container assumes the we use CMT to manager transactions. 

I show you now an example on how to use CMT by using annotations. 


In this picture we can see how to set a container managed transaction for our session bean. We have used the annotation @TransactionManagement specifiyng the type as CONTAINER. If we don't use this annotation the container assumes that we want to use CMT anyway. 



In the pics above I used some of the TransactionAttributes we could use to annotate the CMT methods.
Although the container manages the transaction on our behalf we still need to tell him how to do so. Let's consider for example that the transaction we use on our method has been started from the client that has called our method that is another EJB business method...or maybe our method has been called from the web container and is the method that has to start a new transaction to accomplish the business. So how the container acts? Does it uses the same transaction of the method that is calling or does it starts another transaction to be used on our method? And what if any of the methods does not support a transaction? The @TransactionAttribute tells the container how to handle all these situations. 
I describe the values that this annotation can have below:

REQUIRED: This is the most used attribute type. This attribute type means that the EJB method must always be executed within a transaction. If a transaction does not exist when the method is called than the container starts a new transaction before the method is called and finish it when the method returns. If the method is called from a transactional context, the method joins the transaction.
REQUIRES_NEW: This attribute value means that the container must create a new transaction every time the method is invoked. If the method is invoked outside a from a transactional context, the container creates a new transaction. On the other hand, if the method is called from a transactional context, the container pauses that transaction and creates a new transaction to execute the method. At the end of the method the transaction is either committed or rolled back and the transaction previously paused is resumed. 
SUPPORTED: This attribute means that the method accepts whatever the caller context is: if the caller has a transaction it joins the transaction to execute the method, else if it is not transactional the method is executed on the same context without a transaction.
MANDATORY: This attribute means that the client must have a transactional context before calling this method otherwise the container throws an EJBTransactionRequiredException. This attribute is used when you want that the client receives a rollback whenever something goes wrong during this method execution. 
NOT_SUPPORTED: A method annotated with this attribute value, doesn't accept to be execute on a transactional context. If a client with a transactional context calls the method, the client's transaction will be paused to execute the method and then resumed after the method execution. 
NEVER: This method's attribute means that the method annotated with it can't be invoked from a transactional context, else the container throws an EJBException.

Because of the fact that an MDB could not be called directly by a client but is the container to invoke it when a messages arrives, it can only support REQUIRED and NOT_SUPPORTED transaction attributes, because there isn't a client that can manage the caller's transaction to execute the business logic inside the MDB class.



If the business conditions arise, the CMT method could ask the container to roll back the transaction as soon as possible. We could do that by using the setRollbackOnly() method from the SessionContext object.
It is worth to say that the transaction is not rolled back immediately, instead a flag is checked and the transaction is rolled back before it ends.
From the picture above, we can see that we ask the container to rollback the transaction before throwing the DatabaseException. Before calling the setRollbackOnly method of the SessionContext, you must be sure the method is executing in a transaction context, and you could be sure of that if the method has a TransactionAttributeType with the value MANDATORY, REQUIRED or REQUIRES_NEW. If there is not a transaction context, calling this method results in an IllegalStateException.
You could use another method of the SessionContext object to know if the underlying transaction has been marked to rollback, it is the getRollbackOnly. This method returns a boolean value telling you if the transaction has been rolled back or not.
This method is very useful in the case you have a very long transaction to execute; calling this method before execute the transaction saves a lot of time if the transaction has been just rolled back.

Bean-managed transactions:
The limit of a container-managed transaction is that you are limited to having the transaction boundaries set at the beginning and end of a method and relying on the container to determine when a transaction starts, commits or rolls back.
On the other hand the bean-managed transactions allows the programmer to determine all these details programmatically, in a way similar to JDBC transaction model. Over this kind of transaction management, the container must be much more aware of the underlying JTA Transaction primarily the javax.transaction.UserTransaction interface.

In the same picture I show you how to say the container that it hasn't to worry about because the transaction because we are managing it:


As you can see from the picture we annotated the bean with the TransactionManagement annotation specifying the attribute type to BEAN, meaning the programmer manages the underlying transaction programmatically.
We are also injecting a resource: the UserTransaction interface that will be used to manage the transaction from his methods (begin, commit, rollback the main). The UserTransaction interface could also be get by JNDI lookup in this way:

This way is used when you need to use it in a nonmanaged class or a EJB helper class or in the web tier where dependency injection is not supported.

You could also get the UserTransaction by calling the getUserTransaction() method of the EJBContext. This way is used when you're using the SessionContext or MessageContext for some other purpose and using the resource injection results redundant. You could use it only if you're in a Bean Transaction Management Type else it throws an IllegalStateException. You cannot use the setRollbackOnly and getRollbackOnly methods of the EJBContext because these could only be used in a Container Managed Transaction Type, else it throws an IllegalStateException.


In the following picture I am going to show you the use of the main UserTransaction methods to manage the transaction:


From the picture you can see that in a Bean Managed Transaction method we don't need to set any attribute as e do for the Container Managed methods, because we are managing the transaction programmatically and through the UserTransaction methods we could start, commit or rollback it according to the business we do want to generate.
Calling the begin method we are associating a new transaction at the current thread; if we do call the begin method twice before committing or rolling back the transaction the container would throw the NotSupportedException because Java does not support nested exceptions. The commit and rollback methods removes the transaction associated to the current thread: the commit method sends a success signal to the underlying transaction manager, while the rollback method abandons the transaction.
The UserTransaction interface has other interesting methods that could be used to improve the management of the transaction. We could find the setRollbackOnly method that flags the transaction to rollback; it also has the counterpart of the getRollbackOnly method that we can find on the CMT transaction, it is the getStatus() and returns the status of the current transaction.
Another interesting method that could improve the performance of the application is the setTransactionTimeout that allows us to specify, in seconds, the transaction timeout. It is set by default to different values depending on the application server.