Pages

Showing posts with label jee6. Show all posts
Showing posts with label jee6. Show all posts

Monday, May 6, 2013

Using transaction attributes in EJB 3.1 - Container Managed Transactions

When somebody refers to container managed transactions, what we understand is that the EJB container is responsible of managing transactionality for the methods inside EJB's deployed in the EJB container.

The theory behind transaction management in EJB 3.1 is not brief and probably my post would become to long if I tried to explain other important concepts. In this post I want to just focus on an important concept known as the transaction attribute.

To simplify this concept, I will refer to it, as a configuration given to a method/function within an EJB, that will tell the EJB container what to do with the incoming transaction when that method is called.

The thing that will determine what will occur with the transaction when a certain transaction attribute is used will be the transactional context from where the method was called. In other words, if the enterprise method annotated with a certain attribute was called from a non-transactional(e.g a web page) will manage the transaction differently than if it was called from a transactional context(e.g another EJB). And this is the reason why sometimes we have to choose wisely our transaction attributes.

To use transaction attributes in our EJB's its very simple, all you need to do is use an annotation:
 @Stateful  
 public class SomeBean implements SomeInterface {  
   @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)  
   public void someMethod(){  
    //...  
   }  
   //...  
 }  

Now that we know how to annotate the methods, lets see what will occur when each of the transaction attributes is used:

REQUIRES_NEW
When the calling method is not in a transaction: Starts a new transaction.
When the calling method is in a transaction:  Suspends the existing transaction and creates a new one.

REQUIRED

When the calling method is not in a transaction: Starts a new transaction.
When the calling method is in a transaction:  Executes in existing transaction.

NEVER

When the calling method is not in a transaction: It will execute with no transaction.
When the calling method is in a transaction:  It will throw an exception.

NOT_SUPPORTED

When the calling method is not in a transaction: It will execute with no transaction
When the calling method is in a transaction: It will execute with no transaction(No exception will be thrown)  

SUPPORTS

When the calling method is not in a transaction: It will execute with no transaction.
When the calling method is in a transaction:  Executes in existing transaction.

MANDATORY

When the calling method is not in a transaction:  It will throw an exception.
When the calling method is in a transaction: Executes in existing transaction(Execution continues because the caller was already in a transaction).




Sunday, April 7, 2013

How do I add a project as a dependency of another project and why would I do so? (Maven)

When working in a Java EE distributed system many times we have to manage the dependencies of each of our nodes. Our system will be full of other projects, representing different aspects of the system.


In this post I want to explain how to include a project as a dependency of another project by using an example scenario that is very common in real life: "Sharing the domain model between nodes".

As we know the domain model is the representation of the data that our system works with. To avoid inconsistencies it is a good practice, that each of the projects in our system that are supposed to interact with the domain model do so in a safe way. By interacting safely, we mean look at the domain model as a provided service that the projects use, but without the possibility of corrupting it.

One of the most common ways of achieving our goal would be, to create the domain model, as a separate project, and reference it there where it is needed. Doing this none of the distributed projects of our system will have to be responsible for the domain model, their only responsibility will be to keep the dependency updated, to make sure that they are using the very latest version.


In the following image we can see an example of what could perfectly be a class, in the domain model of a distributed system(Just a trivial example):



This is the project that contains the model and if we want to make sure that it can be use as a dependency in another project, we need to make sure it is packed in a .jar (note the content of the packaging tag in the next image).



When this program is built using the mvn clean install command, it will generate a .jar file that will be stored in the local maven repository(~/.m2). If the build process is successful we should see a message similar to this in our console(Note the message that says that the .jar was installed in the repo):


 A very important thing to understand about this process, is that future versions of this project will need to be increased and also will not have the SNAPSHOT postfix when deployed as stable version. If this process is always done manually by the developer, it possible to make mistakes and that is why in real live, many companies use special tools for building and deploying such as Jenkins and Hudson. The set of tasks and tools that allows distributed software built and deployed automatically in a safe way, is known as Continuous Integration.


Now that we have built and deployed(In this example we just deployed it in the local maven repo) our new domain model, we can reference it in another project.
In this example I will use the model in a project that represents a data access layer for a distributed system, to do so, we will need to add the dependency to the correct version of the model inside the pom.xml file:





Once we build our project we will see that the .jar that contains the model is in the class path and we can use it with no problem in this project:



 When a change is done on those projects on which other projects depend, in order to avoid versions miss matches and inconsistencies, it is a good practice to update all the versions in the dependent projects, re-build and re-deploy.

Now that we know how to add the domain model as a dependency we can add it to other projects that are part of our system(e.g a web app).

Just as a little appendix and even if is not directly related to the post, there is an excellent text about why the Data Transfer Object pattern is no longer needed in JEE in the book: Enterprise JEE Patterns. Rethinking best practices(page 273).  There is a very interesting explanation of why DTO's became superfluous when the JPA entities were introduced. 

Saturday, May 26, 2012

Clustering with Glassfish 3.1

                  

 

 Here I use the command line to create a cluster in the application server Glassfish 3.1 and add 2 instances to it.
Once the cluster is created I deploy an enterprise application and run it in both instances.

Tuesday, May 1, 2012

File realm & role based security with Glassfish 3.1






Here in this video you can see how i create a simple security realm that uses a file in a safe place in the app server to store the credentials. One thing i forgot was to show you how to logout :)
Don't worry is not very difficult, for that you can implement your own logout servlet to invalidate the session.
Here is some example of code for logging out:


1:  @WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})  
2:   public class LogoutServlet extends HttpServlet {  
3:   @Override  
4:   protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
5:    //Invalidates the session  
6:    request.getSession(false).invalidate();  
7:    // Redirects back to the initial page.  
8:    response.sendRedirect(request.getContextPath());  
9:   }  
10:   }  

Also here there is an image to show where can you enable HTTPS for the admin panel:


Note: The SSL certificate that comes with glassfish is expired that is the reason why you will see a warning message before you login.

Saturday, April 7, 2012

Using a fun chalk board to explain how a JEE6 application that uses web services should be organized

I have been studying JAX-RS the last 2 months and i found it very interesting. I wanted to create an interesting video where i explain one of the ways how the .ear application can be organized when using web services. I didn't know that Entities can behave also as JAXB objects. That make things a lot easier.
I think you will like this video, is interesting. It was to big to upload it at once so i divided.
This is the second part of the video. Here i am just showing the code, i am not programming because otherwise the recording would be too long.

I would like to know about what do you think of this architecture? What other alternatives do exist? What are the best practices? Please feel free to comment, i am very interested in reading your comments.

Friday, October 28, 2011

Configuring your eclipse JEE6 project to use JPA (Step by Step guide)


Driver definition
The driver is vendor specific and it will allow the application to connect to the database.
To create a new driver definition for your app that follow this steps in eclipse:
         1- Select Window > Preferences from the main menu bar.
        2- Expand Data Management > Connectivity and select Driver Definitions.
        3- Click Add.                 
       4-In the Name/Type tab, indicate the version of Derby on which you want to create the driver definition.

    1. Select Derby Client JDBC Driver for the non embedded version
    2. Select Derby Embedded JDBC Driver for the embedded version
    3.  (Optional) Modify the Driver Name if a driver definition with this name already exists.  
      Location of the driver in windows systems is often: C:\jeeAplicationServer\glassfishv3/javadb/lib/derbyclient.jar
      5-In the JAR List tab, highlight the default derby.jar file and click Edit JAR/Zip to indicate the fully qualified  path of the Derby JAR file.

    1. Browse to the location of the ZIP file.
    2. Click Open.
6- (Optional) In the Properties tab, modify the default properties for the driver definition template.
Options in the Properties tab vary based on database server type. You can edit or enter a property in the Value box.

7- Click Ok

NOTE: THE driver.jar is for emdebed database while driverclient.jar is for normal database(driverclient should be used)

Start the derby database from the console
To be able to work with the derby database, you need first to start it. To do so, follow this steps:
1-Open the command line and place yourself at the glassfish server bin folder
2-And then enter the command: asadmin start-database

Create a new Connection Profile

Lets say that the connection profile is the configuration that will allow you interact with the database.

1-In the Data Source Explorer tab. Right click on Database Connections and select New…
2- Select the Derby profile
3- In the name field type the name of the database(Type the same as you typed in the Properties tab when you reated the driver definition)
5- Click next
6- In the Connection Details page, pick the driver you configured before and type the correct database. Select the save password option
7- Click on Test Connection to see all is correct. (You will receive a Ping Succeeded! message if all is ok)
8-Click Finish


Create a Connection Pool
In a nutshell, a connection pool allows the database recycle the already used connections. So here is explained how to create a connection pool for the previously created connection profile.

1- Once the glassfish server is started, go to http://localhost:4848
2- At the admin panel select connection Pools and click on New…
3- In general settings; give a name to the pool, The resource type is javax.sql.DataSource and the Database Vendor is Derby and click next
4-In the step 2 of 2. Let all by default, but just edit the setting below to look like this:



5- Click on finish

Adding JPA facelet and Referencing the JDBC resource from the application
At this point GlassFish knows about a database, but we still don’t reference it from the application. Let’s do that now. So here what we do is tell our application to use all the configurations that we configured before.

1- Enable JPA in the application by including the JPA facet:
Right click on Project->Properties->And search for project facets and select JPA
2- In the persistence.xml file you should add the name of the database(datasource) as says in the image:

Create entities
Now lets see how it works all we configured. Try creating an entity with a couple of fields and annotate it with the JPA annotations.

Remember that every entity must have an @Id attribute, if it doesn’t exist you should see something like this:
Create tables from entities
How to transform our entities into tables(Object Relational Mapping) follow this steps:

1- Right click on the project and select  Generate Tables from Entities
2- If this message appears in the screen click in Add a connection to JPA project…

3- The last missing piece is to add the connection name so all JPA features can work

4- Back at the schema selection dialog, you can now choose the schema that will be used for storing the tables.
By default USER schema will be used, so click cancel.
5-If a red error that says that the schema ‘USER’ cannot be found appears, just restart(build) the application.




Tuesday, February 1, 2011

web programmers most powerful weapon

The MVC(Model View Controller) Pattern
Today the most of the existing web frameworks that exist since web 2.0 support separation of concerns by using variations of the MVC pattern. It is an architectural pattern used to isolate business logic from user interface.


Model: The model is represented by the content(often stored in a DB) and it is displayed by the view.
It should be created without concern of its look and feel.
Examples: Entities that use ORM technologies, other backup classes that are included in the domain model, EJB calls...

View:The view are all the parts of the application that the user sees. We could say that it is the model presented graphically.
Examples: XHTML, WML and others...

Controller:The controller is the part that recives the infromation from the View about the desires of the user. The controller gets, converts, validates the data, invokes bussiness logic and generates the markup for the view to display.

In the image below you can see how each part should interact.

Saturday, January 15, 2011

As novice web programmer: Why i prefer JEE 6 instead of frameworks?

Is not that i think that frameworks are not good, but let me tell you about my experience with a couple of popular frameworks:
Ive been ussing Apache Tapestry and Hibernate together, for almost 2 years and this are the 3 main reasons why i decided to switch to jee6:
  1. About tapestry i think that is a way more difficult than JSF and i think you have less information about troubleshooting and configurations on blogs, forums... 
  2. Regarding to Hibernate we know that it was the first ORM framework, but now JEE 6 came out with JPA 2.0 which enhances lots of the features and it is already included in the development kit, so it is more comfortable to work with.
  3. Finally im tired of ussing different frameworks for doing different things. In jee6 i see a great all in one tool with all the stuff i need.

I think that with JEE6 they finnally hit the spot. If you want to start enterprise programming in java JEE 6 has just all you need.





Q7DYA58BHEF9 

Share with your friends