Saturday, August 28, 2010

JSF 2 templating

In this post I want to share my knowledge about JSF 2 templating. Most of this post are source codes, but if you are novice and don't know how to start, and where to put the source code, here you go.

0. Download Netbeans and setup the project.

Install Netbeans and run it. I use version 6.9. In Netbeans, go to File -> New Project... and then choose Java Web and Web Application. Click Next.


In next window choose project name, optionally directory where to store it, and set the project as the main project.


In the next window leave <None> in enterprise application and choose web server. Default should be ok, the same about context path.


Check JavaServer Faces. In Libraries tab select Registered Libraries and JSF 2.0.

1. Simple template and it's client. <ui:insert> and <ui:define>

Ok, we'll create simpliest template possible. In Web Pages create new .xhtml file, let's name it headerFooter.xhtml. It's our template containing header, footer, and place for some content between them.


You can let Netbeans create it for you along with nice CSS files, you can also select one of predefined template layouts. Click File ->  New File -> JavaServer Faces -> Facelets Template. Our template code:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Header-Footer Template</title>
    </h:head>
    <h:body>
        <div id="top">
            Here goes our header
        </div>
        <div id="content" class="center_content">
            <ui:insert name="content">Content</ui:insert>
        </div>
        <div id="bottom">
            And here footer
        </div>
    </h:body>
</html>
Now create template client. It is a page which uses the template. Let's call it templateClient.xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
                template="./headerFooter.xhtml">
    
    <ui:define name="content">
        content
    </ui:define>

</ui:composition>
In template there is <ui:insert> tag. This is a named place where content from template client goes, and it's name in this case is content. In client, there is <ui:composition>. It uses template given as tags attribute, and has <ui:define> tags, with the same name as <ui:insert> in template. So what's in <ui:define> tag is inserted in place of <ui:insert> with the same name. You can run your project (in Netbeans right-click on project and select Run) and see the templated page at http://localhost:8080/JsfTemplating/faces/templateClient.xhtml Any content surrounding <ui:composition> tag is ommitted.

Template client can also be a template. Just put some <ui:insert> tag inside of <ui:define> block. E.g.
<ui:define name="content">
    <div class="info">
        Here goes some additional info, which is not in the header nor in the footer, but we need it on some pages.
    </div>
    <ui:insert name="innerContent">
</ui:define>

2. Decorate

We can also insert parts of markup in our pages. If you have piece of code which you put on some pages and it's always the same, you can separate it to a file and just insert it in the pages. <ui:decorate> tag is used for this:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets">
    <body>
        Some page text
        <ui:decorate template="./disclaimer.xhtml"/>
    </body>
</html>
Content of disclaimer.xhtml is injected where <ui:decorate> tag is. Don't add <?xml ... ?> declaration or doctype there, or it is going to be inserted in the middle of your page, which is not desirable. You can also use standard templating in disclaimer.xhtml. You can put <ui:insert> there and <ui:define> in page which uses it.

3. Include

Another method to attach some piece of markup is <ui:include>. This one also lets us pass some parameter to the piece of code we want to include, and this parameter can be managed bean. Lets say we have bean with information about some documents:
@ManagedBean
public class Paper {

    private String author;
    private String title;

    //getters and setters omitted
}
Piece of code to display information about a book is prepared in book.xhtml file:
<div xmlns="http://www.w3.org/1999/xhtml">
    Book "#{book.title}" by #{book.author}
</div>
Now in any other JSF page we can use it:
<ui:include src="./book.xhtml">
    <ui:param name="book" value="#{tomSawyer}" />
</ui:include>
I hope this post is going to be helpful to somebody. At least to me. Happy templating with JSF!

Monday, August 9, 2010

JPA Puzzle. When your entity misses some fields.

Today I encountered quite interesting problem. It wasted few hours of my life, so maybe if you read this you can save some. Example is simplified as much as possible.
@Entity
@Table(name = "PERSONS")
@NamedNativeQueries({
    @NamedNativeQuery(
        name = "getPersonBasic",
        query = "SELECT p.name, p.surname FROM persons where p.surname = ?",
        resultClass = Person.class),
    @NamedNativeQuery(
        name = "getPersonDetails",
        query = "SELECT p.name, p.surname, p.age, p.street, p.city FROM persons where p.surname = ?",
        resultClass = Person.class)
})
public class Person {
    
    private String name;

    @Id
    private String surname;

    private int age;

    private String street;

    private String city;

}

Now, in my application I am getting Person with surname "Stawicki" without details, by "getPersonBasic" query. Then I need detailed person in the same transaction, so I execute "getPersonDetails". And... I am getting Person without age, street and city. This three fields are null. Why? Do you already know? If not, look below for answer.













The problem is in cache, and in @Id which is only on surname field. First person is retrieved without details and stored in cache. Then we try to get person with details, but JPA doesn't understand difference between our queries. It queries the database, and identifies that if it builds entity from resulting ResultSet, it is going to have the same @Id as entity which is already in cache. If @Id is the same, logically it is the same entity. So it just returns it without building whole entity from ResultSet.

Tuesday, July 27, 2010

Review: Real World Java EE Patterns Rethinking Best Practices, by Adam Bien

Real World Java EE Patterns Rethinking Best Practices

"Real World Java EE Patterns" is a book targeted rather for developers with some experience with JEE. If you are a beginner, you can miss some context. If you have some experience with JEE, in this book you'll probably find solutions to problems that are familiar to you.

Adam Bien is great at explaining difficult topics. Difficult? I didn't find anything difficult in this book ;) E.g. transactions isolation is explained very clearly.

The book is very good catalog of JEE Patterns. Each pattern is described separately in similar manner. Each chapter has subchapters: "Problem", "Forces", "Solution", "Testing", "Documentation", "Consequences" and "Related Patterns". In "Problem" a reader can find short description of a problem the pattern should solve. "Forces" shows features that solution should have. "Solution" contains description of pattern, what classes it consists of and what is their responsibility. Usually accompanied by very clear and simple pieces of code. In "Testing" and "Documentation" author highlights what should we test when we use certain pattern, and what should be documented (quite obvious, isn't it?). In "Consequences" we can read about what are pros and cons of the pattern. "Related Patterns" is self explanatory. Most interesting subchapter is "Solution", and it also has sub-subchapters. One of them is "Rethinking". It is good part for experienced JEE developers. Adam shows why some patterns are obsolete. It doesn't mean you should never use it, but in most cases it is no longer necessary in JEE5 or 6. Some patterns, when moved from EJB2 to EJB3, are not adding any value, but instead are adding layer of abstraction and unnecessary complicating the system.

What I like about Adam Bien is that he is not only writing and talking about programming, but he's also programming. While reading the book, one can feel that the author has real experience with the topic. Sometimes he advices not to use what is common "best practice", when it is not necessary and is not adding any value. Good programmer should be able to balance pros and cons of possible solutions, not just blindly follow common practice.

There are small mistakes in the book, but only editor ones, like misspellings and formatting mistakes, single lines of code on next/previous page etc. Nothing really annoying, but there is room for improvement on this field.

Thank you Adam for this book!

Monday, May 31, 2010

Transaction isolation level

Recently I have read very good explanation of transaction isolation levels in "Real World Java EE Patterns. Rethinking Best Practices." by Adam Bien.

Transactions were introduced for two reasons. To make complex operations atomic (all or nothing) and to give possibility to concurrently use resources. Without transactions it is possible that two users (or more specifically actors, this can be some parts of the system, not necessarly live users) read/write the same resource simultaneously, and changes made by one of them are lost and overwriten by the other one.

Consider following example document:

Cheesecake bottom
250g crunchy bisquits
100g butter

Cheesecake top
900g cottage cheese
250g mascarpone cheese
1 lemon

Imagine one user gets the document and the other user also is getting the same document. Both users have the same data. Now both of them are editing it. One likes sweeter cake bottom, so adds "2 spoons of sugar" to the recipe, and writes changed recipe back to the database. In database now it looks like this:

Cheesecake bottom
250g crunchy bisquits
100g butter
2 spoons of sugar

Cheesecake top
900g cottage cheese
250g mascarpone cheese
1 lemon

Meanwhile second user adds "2 eggs" to cheescake top recipe and saves his version:

Cheesecake bottom
250g crunchy bisquits
100g butter
2 spoons of sugar

Cheesecake top
900g cottage cheese
250g mascarpone cheese
1 lemon
2 eggs
Change made by the first user is lost. In some cases it can lead to inconsistent data.

So that's why transactions were introduced. Transaction isolates changes made by one user from changes made by the other. There are 4 levels of transaction isolation.

Serializable

Transaction locks all necessary resources. If user wants to read or write some resource, it is locked and no one else can read or write it. This level of isolation can easly lead to deadlocks:
  1. User Ann opens transaction. Ann needs resource A, transaction locks it.
  2. User John opens another transaction. John needs resource B, transaction locks it.
  3. Ann needs resource B, but it is locked, so Ann's transaction needs to wait until it is released
  4. John needs resource A, but it is locked. John's transaction waits until it is released. Both users wait endlessly.

If John didn't need A, he finishes his transaction, B is released and Ann can finish her transaction too.

Repeatable reads

Guarantees that the same query will return the same results if executed in one transaction. Even if other transaction modifies resource meanwhile. Exception is adding - new rows can appear in query result. If another transaction deletes existing rows or modifies them, this changes are not visible.
  1. Ann opens transaction. She reads names of java4people organizers: "Stawicki" and "Gruchała".
  2. Bob opens transaction and deletes "Stawicki". Bob commits changes and closes transaction.
  3. Again Ann reads names. She gets "Stawicki" and "Gruchała".

If Bob added some name, Ann would read it too.

Read commited

The same query can return different result even in one transaction if another transaction makes changes and commits them.
  1. Ann opens transaction and reads names of java4people organizers: "Stawicki" and "Gruchała".
  2. Bob opens transaction and deletes "Stawicki".
  3. Ann reads names again. She gets "Stawicki" and "Gruchała".
  4. Bob commits his transaction
  5. Ann reads names again (still in one transaction). She gets "Gruchała".

Read uncommited

Like no transactions at all. It only gives us atomic operations. User can rollback all the changes in transaction. Changes are visible to other transactions even before commit. Of course, if transaction that made changes is rolled back, changes are not visible any more.

Saturday, May 15, 2010

After GeeCON 2010

This year GeeCON took place in Poznań which is much closer to Szczecin than Cracow. I expected it to be as good as a year before, maybe I expected too much. I don't mean it was bad, but previous year it was so great that maybe it was hard to keep this level. Or maybe I was not choosing right presentations. There were three tracks this year so choice was sometimes difficult.

Like a previous year there was "University Day" before the conference. University Day is day of workshops on various topics. I have chosen Gradle, like many other people. Too many unfortunately. Hans said there are too many attendants to make exercises for everyone, so only he coded live. I missed coding myself.

First interesting concept I heard about was Object Teams. It is a new idea of modularizing our programs, based on entities, collaborations and roles. All three look pretty much like java classes. In OOP there are objects which are data and methods. We can use objects to modularize our applications, but often connections between modules are becoming complicated. Creators of Object Teams concluded that modularization and OOP is not about modules/objects itself but about connections between them. So there are entities, which represent data. There are collaborations, that represent operations on data, and roles. In a collaboration, each entity plays some role. Everything looks pretty and neat, and I wonder if it is going to become popular in coming years. I must admit I haven't heard about it before.

Quite interesting presentation was about JSF 2.0 by Ed Burns. Nothing quite new for me, but if someone thinks JSF didn't change much since 1.2 version he should attend this presentation (or watch on GeeCON's channel on parleys.com when it becomes available ;)). Guys who created version 2.0 addressed all the problems developers were complaining about with previous versions. I remember Seam was framework which was built on JSF and addressed such problems. Now, when it is solved in JSF itself, I wonder what are differences between Seam and JSF 2.0.

On the second day Jonas Bonér was talking about actors, agents, STM and other solutions making concurrent programming much easier than threads with shared state and locks. Next time I'll need to do some concurrent programming in Java I'll definitely use something from Akka.

Vaclav Pech's presentation was quite similar. He also talked about concurrent programming with actors, but in Groovy. As usual Vaclav gave very good presentation.

Vaadin is the next thing I want to use. At work I use GWT and I don't really like it. GWT compilation is very long and asynchronous callbacks are making code more complicated. Besides most of work is done on the server anyway. Programming in Vaadin is very similar to programming in GWT, but everything is server side. Vaadin uses GWT for presentation, so it is possible to write custom components for Vaadin in GWT, but then compilation is needed only once. Damn, this could save many hours of my life.

Bruno Bossola's presentation was very good and funny. No suprise here :) Bruno talks about things that many developers really need. I agree somewhere we lost real Object Oriented programming. Bruno also mentioned a book which I feel is unfairly forgotten. "Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development" by Craig Larman. When I started working for NCDC more than few years ago, my boss put this book to company's library and recommended it to us. I read it and I feel it made me a better developer. If you put all your code into one huge class or even method, buy or borrow this book and read it. Even if it's old it's worth it. Some things don't change even in IT ;)

If I can have some hint for the organizers I'd like to suggest to make presentations longer. Many presenters didn't manage to show everything they wanted. I think 1.5 hour is minimum.

I heard food was also a problem on the first day. It didn't suffice for everybody, but I managed to grab my plate so I don't complain :)

Saturday, April 24, 2010

SzJUG member, Filip "Filus" Pająk presentation on TestNG

Recently (last Thursday) I had pleasure to attend Szczecin JUG meeting at which Filip presented TestNG. Presentation was great. I knew Filip is a perfectionist, and when he does something it is just perfect :), but I didn't know he has such great speaker talent! I felt he really cares about being understood.

Filip was very well prepared. A lot of knowledge and a lot of great examples. Examples were prepared before and were short and simple. Just what you need to understand some issue, no less and no more. I think it is better than coding "live" when something can blow up. Show example, run it and show results.

Filip claimed he is no "guru" and doesn't know TestNG very well, but as far as I remember, he knew answer to every question :). I hope it was not his last presentation at Szczecin JUG. Or maybe he'll present somewhere else now? Who knows?

Saturday, April 17, 2010

Szczecin JUG Meeting. Filip "Filus" Pająk on TestNG.

On 22nd of April 2010 Filip "Filus" Pająk will present TestNG. If you are around Szczecin, feel invited. It's free :)

Filus is experienced Java programmer and tester. When he does something, you can be sure it's going to be good. I think he'll make great presentation.

I am very glad Szczecin JUG is organising another meeting. It's been some time since the last one.

Maybe I should also present something? JavaFX? Scala?