Skip to main content

lamine_ba's Blog

Building RESTful web services with JAX-RS, JAXB and Groovy

Posted by lamine_ba on May 20, 2012 at 11:14 AM PDT

Any intelligent fool can make things bigger, more complex, and more violent
But it takes a touch of genius and a lot of courage to move in the opposite direction.
Albert Einstein

Introduction

Ladies and Gentlemen, beyond the fact that I'm going today to share with you, most of the things a developer should know when building a JAX-RS web service with Groovy, this blog post is first and foremost a farewell to the Java language. It was a fun ride but now I think it is high time for me to move on. And how odd and ridiculous is it to build the dynamic parts of my application with a static language?

How to set up the environment?

Unless you are using Grails and its grails-jaxrs plugin or a proprietary solution, I have no answer to how to write a groovy service which gets compiled and registered at runtime within the JAX-RS system. But in the other hand, if you are asking me how to do so in my own framework, my answer would be that : " there is nothing to configure, everything has already been set up and the core classes of JAX-RS and JAXB have been transparently imported". So the next thing, Ladies and Gentlemen, is to just write a groovy service to see what we will get...

  1. CompilerConfiguration configuration=new CompilerConfiguration();
  2. ImportCustomizer customizer=new ImportCustomizer();
  3. customizer.addStarImport("javax.ws.rs""javax.ws.rs.core","javax.xml.bind.annotation");
  4. configuration.addCompilationCustomizers(customizer);

The Problem

Beyond the classical hello word service which might be written with groovy like this :

  1. @Path("/hello")
  2. class HelloWorldService {
  3.  
  4.   @GET
  5.   @Path("{name}")
  6.   def String hello(@PathParam("name") String name) {
  7.         "Hello $name"
  8.   }
  9.  
  10. }

And beyond the simple statement that any String with an embedded expression is a GString, today we are going to follow my dear friend Joe in his obsession to make the list of his customers available through REST. And in the same time, we will also look at the potential errors he might encounter in the resolution of his problem and the set of techniques he has really under his belt.

  1. class Customer {
  2.  
  3.    Long id     
  4.    String firstName
  5.    String lastName
  6.  
  7. }
  1. class CustomerDao {
  2.  
  3.    def customers=[]
  4.  
  5.    CustomerDao() {
  6.  
  7.         customers << new Customer(id:1,firstName:"Bob",lastName:"Lee")
  8.         customers << new Customer(id:2,firstName:"Jim",lastName:"Dry")
  9.         customers << new Customer(id:3,firstName:"Joe",lastName:"Hart")
  10.         customers << new Customer(id:4,firstName:"Frank",lastName:"Lucas")
  11.        
  12.    }
  13.  
  14. }

Sending Representations to the target client using the Groovy Builders

XML with MarkupBuilder

  1. @Path("/customers")
  2. class Service {
  3.        
  4.         @Produces(["application/xml"])
  5.         @GET
  6.         def getCustomers() {
  7.              def writer = new StringWriter()
  8.              def builder = new groovy.xml.MarkupBuilder(writer)
  9.              builder.customers { dao.customers.each() { entity ->
  10.                      customer(){
  11.                          id  entity.id
  12.                          firstName entity.firstName
  13.                          lastName  entity.lastName
  14.                       }
  15.                 }
  16.              }
  17.              writer.toString()
  18.         }
  19. }

Output

  1. <customers>
  2.  
  3.    <customer>
  4.      <id>1</id>
  5.      <firstName>Bob</firstName>
  6.      <lastName>Lee</lastName>
  7.    </customer>
  8.  
  9.    <customer>
  10.     <id>2</id>
  11.     <firstName>Jim</firstName>
  12.     <lastName>Dry</lastName>
  13.    </customer>
  14. ....
  15. </customers>

JSON with JsonBuilder

  1. @Path("/customers")
  2. class Service {
  3.        
  4.         @Produces(["application/json"])
  5.         @GET
  6.         def getCustomers() {
  7.              def builder = new groovy.json.JsonBuilder()
  8.              builder(customers : dao.customers)
  9.              builder.toString()
  10.         }
  11. }

Output

  1. {"customers":[{"firstName":"Bob","id":1,"lastName":"Lee"},{"firstName":"Jim","id":2,"lastName":"Dry"},
  2. {"firstName":"Joe","id":3,"lastName":"Hart"},
  3. {"firstName":"Frank","id":4,"lastName":"Lucas"},{"firstName":"Mark","id":5,"lastName":"Zuckerberg"},{"firstName":"Alexis","id":6,"lastName":"Sanchez"}]}

If you are not impressed and shocked in the same time by the brutality of Groovy, Ladies and Gentlemen, this time, I don't even know what to say to you but please always remember this : As a rule of thumb, a service should always be decoupled from the code that marshall and unmarshall the data. So if you are aware of the concept of a MessageBodyWriter, I think you know perfectly how to refactor the code. And also one more thing, maybe we can use a XmlSlurper or a JsonSlurper for the opposite operation?

XML

  1. def c = """<customer>
  2.              <id>1</id>
  3.             <firstName>John</firstName>
  4.             <lastName>Doe</lastName>
  5.           </customer>
  6.        """
  7. def customer = new XmlSlurper().parseText(c)

JSON

  1. def slurper = new JsonSlurper()
  2. def result = slurper.parseText('{"customer":{"id":"1","firstName":"John","lastName":"Doe"}}')

Using JAXB for the Marshaling/Unmarshaling

That is where the funny part is and also where all the real problems start.

  1. @XmlRootElement
  2. class Customer {
  3.  
  4.   Long id
  5.   String firstName
  6.   String lastName
  7.  
  8.  
  9. }
  1. @Path("/customers")
  2. class Service {
  3.        
  4.         @GET
  5.         @Produces([MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML])
  6.         def getCustomers() {
  7.              dao.customers
  8.         }
  9.        
  10. }

When running this example and when accessing the service through its url, here is the first explicit error we will get : A message body writer for Java class java.util.ArrayList was not found . And this error is caused by the following declaration in the Dao :

  1. class CustomerDao {
  2.  
  3.    def customers=[]
  4.  
  5. }

and by the fact that we haven't explicitly set the return type in the Service.

  1. @Path("/customers")
  2. class Service {
  3.        
  4.         @GET
  5.         @Produces([MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML])
  6.         def List<Customer> getCustomers() {
  7.             dao.customers
  8.         }
  9.        
  10. }

Groovy making the type optional does not mean that JAX-RS does it also. So Ladies and Gentlemen, you must pay attention to that. The object type and the media type will ultimately determine how to select a MessageBodyWriter or a MessageBodyReader.
Now to close this post, Let's run again the example for the last time and let's get this following error : groovy.lang.MetaClass is an interface, and JAXB can't handle interfaces. which we can easily solve by setting the XmlAccessType to NONE and by explicitly doing the mapping of the fields of the domain object by ourselves. So what you have to bear in mind here is that : There is NO MORE configuration by exception.....

  1. @XmlAccessorType(XmlAccessType.NONE)
  2. @XmlRootElement
  3. class Customer {
  4.  
  5.   @XmlElement Long id
  6.   @XmlElement String firstName
  7.   @XmlElement String lastName
  8.  
  9. }

A Service is a Module : Let's develop it from the cloud..

You can find this module deployed in my application on the cloud at this url so that you can complete your knowledge there and download it if you want.


Also don't hesitate to click on the WADL button to see everything that your service can do.


If you click on the customer : application/json link at the right or the another link, all the attributes of your entity will be listed.


And next time for sure, I will show you how to build a web client for this service and how to consume it within a JSF environment with my JAX-RS web application framework : YouControl and an Ajax library like JQuery. So until then, Ladies and Gentlemen, Have a nice week....

Documentation

No one can create something without taking inspiration somewhere........

  1. JAX-RS as the one Java web framework to rule them all?
  2. Leaving JSPs in the dust: moving LinkedIn to dust.js client-side templates
  3. Modern Web Apps using JAX-RS, MongoDB, JSON, and jQuery
  4. RESTful services with jQuery and Java using JAX-RS and Jersey
  5. Tutorial: HTML Templates with Mustache.js
  6. Client-Side MVC frameworks compared
  7. The client-side templating throwdown: mustache, handlebars, dust.js, and more
  8. Asynchronous UIs - the future of web user interfaces

 

AttachmentSize
module-controls.png8.08 KB
wadl-information.png5.09 KB
customer-info.png14.21 KB

Comments

Nice blog, it's useful! good conception in YouControl app! ...

Nice blog, it's useful!
good conception in YouControl app! i suggest you to give it a Senegalese name! ;)
wish u good continuation!

Hi Lamine, Your approach to the front end Java ...

Hi Lamine,

Your approach to the front end Java development is a breath of fresh air.
Question: is Youcontrol open source? If yes, where can I download it?

Regards,
- Juliano

If JAX-RS had an MVC framework?

Posted by lamine_ba on April 10, 2012 at 1:09 PM PDT

We build too many walls and not enough bridges.
Isaac Newton

Introduction

In my previous blog post, I have asked to many of you this question: "What JSF should become?". And since then, I was quite silent. The reason behind it, is that I was working to build a concrete implementation of this vision and today I'm glad to give you a concrete demonstration of it. So Ladies and Gentlemen, why waiting more? Let's first start with the idea you are expecting in JSF 2.2...

Multi-Templating

In a recent interview, the JSF spec lead did talk about it and as he said this feature has gone through some iterations on the EG. And the lovely templates below are really the confirmation that a JSF developer will never build the user interface of his JSF application from scratch. He will just download a template from the web and hop he will be ready to go. And that is one reason why, I totally disagree the idea of putting the templates in a jar. Frankly, If I do so, how can I edit my templates with my cloud web-based editor? And with the rise of JavaEE 7, isn't it the time to move our IDE in the cloud......

Templates

  1. Cartion
  2. Carligian
  3. Archange
  4. NYC
  5. Via Granitti
  6. Story of Glory
  7. Arlqueens
  8. Cimmanon
  9. Encholia
  10. Platine45

100.Jf_Texturia

YouControl

Let's come now to the interesting part of this blog post and I'm asking if it is possible to build a JSF application which does not save its state? No better, Is it possible to build a JSF application which has a lifecycle of one phase (Render Phase) and which has no <h:form> inside its views? No, Let's move the level higher, can one build a JSF application with a set of UI components that can render themselves on the client side? If your answer is no, I think it is high time for me to introduce you to my JAX-RS web application framework : YouControl....



If you have any doubt that this JSF application is in fact a JAX-RS application, just display the list of my modules and click on the wadl link to see it from yourselves.

To finish, JSF 2.0 has already a support for HTML5 and CSS3. If you put a <canvas> tag in your view, will Facelets complain or just your browser if this one does not support it? And at last, if you are wondering how my client side UI components are made, Just imagine yourself consuming your Customer service with Html 6 or Html 7 :

  1. @XmlRootElement
  2. public class Customer {
  3.  
  4.         private Long id;
  5.         private String firstName;
  6.         private String lastName;
  7.  
  8.         .......
  9. }
  1. @Path("/customers")
  2. public class CustomerService {
  3.        
  4.         @GET
  5.         @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
  6.         public List<Customer> getCustomers(){
  7.                 return dao.getCustomers();
  8.         }
  9. }
  10.  
  1. <c:table url="/customers">
  2.         <thead>
  3.               <tr>
  4.                 <th>ID</th>
  5.                 <th>First Name</th>
  6.                 <th>Last Name</th>
  7.               </tr>
  8.         </thead>
  9.         <tbody>
  10.                 <tr>
  11.                     <td> {{id}} </td>
  12.                     <td> {{firstName}} </td>
  13.                     <td> {{lastName}} </td>
  14.                 </tr>
  15.         </tbody>
  16. </c:table>
  17.  

If you are too lazy to design the table, set the auto-create attribute to true and let me do the Rest for you. Yes, Ladies and Gentlemen, Javascript, Json and client-side templating systems like Mustache are really awesome....

  1. <c:table url="/customers" auto-create="true"/>

I sincerely hope that at this moment, the JSF guys are asking really this question : Hey wait a minute, where is my Managed Bean?. ( #{customerBean.customer.id}, #{customerBean.customer.firstName}, #{customerBean.customer.lastName}. ..)

 

AttachmentSize
editor.PNG85.85 KB
modules.PNG39.93 KB

Comments

Before reading this, please read my response to your ...

Before reading this, please read my response to your 20111127 post.

Hello Lamine, thanks for this nice blog post.  You say,

> That is one reason why, I totally disagree the idea of putting the
> templates in a jar. Frankly, If I do so, how can I edit my templates
> with my cloud web-based editor?

Putting templates in a jar is a deploypment time expedient.  The idea is
for templates to be hosted in a maven repo.  If you want to edit them,
you'd have to manually download it and bundle it into your app, or you
could re-package it as a jar and consume it that way.

Regarding YouControl, I agree with Cay, keep at it!  I hope you find a
productive partnership coming from this work.

Thanks,

Ed

Hello, Ed Thanks for your nice comment. Yes I know, I ...

Hello, Ed

Thanks for your nice comment. Yes I know, I was very radical in my statement but it was just a way to show to the JSF users, the opposite face of the vision you have. In fact what you have read is just a projection of a near future from my perspective. So the key thing is to design the Multi-Templating feature abstract enough to let the conflicting visions to coexist......

Regarding YouControl, Yes I will keep at it while hoping to have a
productive partnership soon.......

Thanks,

Lamine

This definitely an interesting way to go. I'll definitely ...

This definitely an interesting way to go. I'll definitely take a look at it.

Ivan

Hi, I am glad you are thinking along these lines. I just had ...

Hi, I am glad you are thinking along these lines. I just had to make a service accessible to people, and I thought, heck, I just use JAX-RS and some forgettable UI. Much to my surprise, that was a smart move. Yes, I want to go the next step with JSF to use a pretty UI, but I also don't want to lose the benefits of a service-oriented interface. Keep at it!

Hi Cay, Thank you very much for your comment. It has set ...

Hi Cay, Thank you very much for your comment. It has set up the real vision which is to replace the programming model of JSF by the programming model of JAX-RS while keeping all the parts related to the UI that JSF did right (Composite components, Resource Handling, Facelets Templating, Multi-templating...).

By the way, Core Javaserver Faces is one the book where I have learned JSF. My sincere congratulations for all the good things in it....

Thanks,
Lamine

What JSF should become?

Posted by lamine_ba on November 27, 2011 at 6:03 AM PST

Perfection is achieved through times.
Anonymous

Introduction

How someone can improve if he has no clear vision of what he could become? I'm asking this tough question to myself while reading to the definition of JSF. As it is written in its specification, JavaServer Faces is a user interface framework designed to significantly ease the burden of writing and maintaining applications that run on a java application server and render their UIs back to a target client. Woow! That is really a lovely definition but is it still relevant in 2011 and beyond? Ladies and Gentlemen, are you sure that we don't need more? 

Our standard web framework is built around the greatest design patterns but it definitely lacks the fundamentals. I have read nowhere that JSF has provided any guidance to developers through the form of "development patterns". And we still have the huge pretention to ask you to use a web framework which has no standard development models coming through the form of conventions. Let me now adopt a more professional attitude in order to clarify my position with some concrete examples thus you will better understand what I'm talking about.

Views

Let's begin with this simple question. Where one must store his views? Inside a folder put in the WEB-INF or in the root directory? Shall we name this folder "pages" like Steve or "views" like Mike? No, let's name it "bobmarley" like Crazy Joe. And with this lack of convention, we have lost one possibility to have some nice automations to ease the development and to make our JSF applications homogeneous. And when someone has the requirement to move to another project to work with another team, he must always take the time to learn first their own conventions. Isn't it a waste of time and frankly does one understand the meaning of a knowledge if it cannot be shared? 

Client Side Request Forgery Protection (CSRF)

This feature is mostly specified and it will come with JSF 2.2. That is an standardization of how JSF provides CSRF protections. If you haven't read the proposal yet, here is how it will be implemented. Within the <faces-config-extension> element, a new <protected-views> element will be introduced. This element contains zero or more <url-pattern> elements

  1. <faces-config-extension>
  2.  
  3.         <protected-views>
  4.                 <url-pattern>/views/deleteBlogEntry.xhtml</url-pattern>
  5.                 <url-pattern>/views/deleteComment.xhtml</url-pattern>
  6.         </protected-views>
  7.  
  8. </faces-config-extension>

Any view that matches any of the url-patterns may only be reached from another JSF view in the same web application. And because the runtime is aware of which views are protected, any navigation from an unprotected view to a protected view is automatically subject to protection. That is really a lovely theory but in practice, it hardly means this : If you have 100 views to protect, you have 100 xml lines to write and that is really a lovely annoying stuff made for bureaucrats. I would rather have this convention combined with an url rewriting in order to have this simple automation : Any view stored in the views/protected directory is automatically protected.

And doing so, the API which has been added to the ViewHandler for a support of this feature at runtime will be now full of sense.

  1. public List<String> getProtectedViewsUnmodifiable();
  2.  
  3. public void addProtectedView(String urlPattern);
  4.  
  5. public void removeProtectedView(String urlPattern);
  6.  

Facelets Templating

Ladies and Gentlemen, have you watched "Saving Private Ryan" from Steven Spielberg. I'm using this analogy as a way to undoubtedly say that Facelets has saved the life of JSF. And I'm truly in love with its templating approach but what I hate the most is :

  1. There is no convention about where to store the template. A view can only use one template and it has a huge dependency with it. And if you are so crazy to change its location, prepare yourself for a cascading views update.
      <html xmlns="http://www.w3.org/1999/xhtml"  
         xmlns:h="http://java.sun.com/jsf/html"  
         xmlns:ui="http://java.sun.com/jsf/facelets">  
     
        <body>  
         
        <ui:composition template="/template.xhtml">
         
         </ui:composition>        
                 
        </body>  
     
    </html>
  2. There is no clear separation between the web designer and the developers. They are dependent to each other. Who is waiting for who? Such is the question.
  3. The template and its resources (css, js, images) cannot be externalized, packaged and shared.

Multi-Templating

But these complaints are no longer true with JSF 2.2 and its Multi-Templating system. But don't be too much confused with this feature. It is only an extension of the Facelets templating system for a better modeling of the concept so that :

  1. A view can use more than one template. And with this new abstraction, it cannot even guess the location of the templates. Who knows, maybe they are stored somewhere in the Cloud.
      <html xmlns="http://www.w3.org/1999/xhtml"  
         xmlns:h="http://java.sun.com/jsf/html"  
         xmlns:ui="http://java.sun.com/jsf/facelets">  
     
        <body>  
         
        <ui:composition template="#{template}">
         
         </ui:composition>        
                 
        </body>  
     
    </html>
  2.  The web designer and the developers have no dependency. No one is waiting for no one. 
  3. A template and its resources (css, js, images) can now be externalized, packaged and shared.

To finish, I think it is a well-established knowledge that in a JSF application, a view will always use a template. So I don't see any valuable reason to waste our time by writing this "<ui:composition template="#{template}"> in our views. Don't you agree that once a knowledge is set, things should be automatic? But fortunately, such will be the case for JSF 2.2.

Security Model

I will end up by a feature I'm hardly battling to have. So if you see any value in it, please leave a comment for our spec lead. But take the time to read first the conversation below :

  • Hey template authors, that is very nice to see you designing templates for us but can we delegate more work to you? Can you design the login form for us?
  • Of course, we can design it in the template or in a separate page. And we don't care about if you will use JAAS, Spring Acegi or such. The only thing we need is an authentication model coming through the form of a standard managed bean for the connection with your security logic.
  • Ahh! I understand. You want to have an abstraction like SeamLoginModule....
  1. <h:form id="login">
  2.  
  3.         <h:panelGrid columns="2">
  4.                 <h:outputLabel for="username">Username</h:outputLabel>
  5.                 <h:inputText id="username" value="#{identity.username}"/>
  6.                 <h:outputLabel for="password">Password</h:outputLabel>
  7.                 <h:inputSecret id="password" value="#{identity.password}"/>
  8.         </h:panelGrid>
  9.  
  10. <h:commandButton value="Login" action="#{identity.login}"/>
  11.  
  12. </h:form>
  13.  

And to complete the whole thing, maybe we can add to this, a view-level security in order to prevent non-authenticated users from accessing restricted views. Nonetheless, the decision does not belong to me, but undoubtedly the JSF community has a louder voice. So Ladies and Gentlemen, feel free to contribute and be hard on yourself if you want to improve. Yes, truly I love JSF but today I'm not tender with it...

 

AttachmentSize
views-folder.PNG684 bytes
views-protected-folder.PNG1.14 KB
Related Topics >>

Comments

Hello Lamine, Reading your 20120410 post, I had cause ...

Hello Lamine,

Reading your 20120410 post, I had cause to re-read your 20111127 post
and I think it's appropriate to reply first to 20111127 and then to
20120410.

First, let's look at the convention for where to put your Facelet pages.
Aside from establishing a project format convention, which is arguably
the most valuable thing maven has brought to the world, what value would
it add?  In order to make it worth doing this, there would have to be
some value over and above just establishing a convention.  For example,
let's say that we add an item to the list of conditions that cause the
FacesServlet to be automatically mapped, as shown in JSF 2.1 [1].  The
existing list is this:

    A faces-config.xml file is found in WEB-INF

    A faces-config.xml file is found in the META-INF directory of a jar
    in the application's classpath.

    A filename ending in .faces-config.xml is found in the META-INF
    directory of a jar in the application's classpath.

    The javax.faces.CONFIG_FILES context param is declared in web.xml or
    web-fragment.xml.

    The Set of classes passed to the onStartup() method of the
    ServletContainerInitializer implementation is not empty.

We can add this one

    There exists a non-empty "views" subdirectory of the web app root.

In this case, we have both created a convention and introduced a feature
that leverages that convention.  Is that sufficient value?  I'm not
sure.

Now let's look at your CSRF proposal.

This one is clearly valuable.  And, in your proposal, it depends on the
creation of a "views" concept.

On to Multi-templating.

I think the naming convention I started out my response with falls
neatly under this feature.

As far as login, yes, we certainly need to do this.

Thanks,

Ed

[1] https://maven.java.net/service/local/repositories/releases/archive/javax/faces/javax.faces-api/2.1/javax.faces-api-2.1-javadoc.jar/!/javax/faces/webapp/FacesServlet.html

Hello Ed First of all, you have to forget most of the ideas ...

Hello Ed

First of all, you have to forget most of the ideas I have shared here and you have to keep only this one : Storing the views in a "views" directory. Now the problem is how to add this feature in JSF 2.2 without breaking the backward compatibility stuff. Here is the solution, give only the behavior below to the default Facelets Resolver :

public class ViewResolver extends DefaultResourceResolver{
public URL resolveUrl(String path){
          URL url=super.resolveUrl("/views"+path);
  return url!=null?url:super.resolveUrl(path);
        }

If the user send this request : http://localhost:8080/faces/index.html. The view resolver will first try to resolve index.html in the views directory by appending "/views to the path (/index.xhtml). And if we have nothing, we come back to the original behavior with the original path....

Hi Ba, it would be great for sure!&nbsp;What about new ...

Hi Ba,

it would be great for sure! What about new versions for Spring Roo, soon supporting JSF 2.0 and Primefaces? I think it will fill some of this needs.

Check this out java.dzone.com/articles/jsf-20-spring-roo

Thanks for this great post!

Hi axcdnt, Thank you very much for this nice and clever ...

Hi axcdnt,

Thank you very much for this nice and clever comment. In this blog post, I did not write this time a conclusion because my goal was to let you discover by yourselves what JSF could be. The next step for a web user interface framework is to become a tiny web application framework that one can extend. And no framework can reach this level without having conventions. And once those standard development patterns are established, its community will better see the value and the power of app generators like Spring Roo. Yes its next versions will rock and I can't wait the one which will come with this right combination:

JSF 2.2 + Primefaces (views) + Multi-Templating (templates) + Tasks Flows (modules) + Security Model

A Tasks Flow is a module written by a web developer and like for a template, it is shareable but it would be nice if we can write its business logic with scripting languages so that we can customize it.

We are also coming soon with an integration model with JAX-RS 2.0, so be ready to add it to the stack.
 

Regards,
Lamine

 

Hi Ba! nice blog again! The concept &quot;Convention over ...

Hi Ba! nice blog again!
The concept "Convention over Configuration" than you want to adopt with JSF, will ease the web development and improve the maintainability in Java EE. I don't see any constraints to block the community in adopting these conventions quickly. The goal is to facilitate and improve the development (The Time-to-market).
Continue at this way, with some guys like you, JSF will become a great web framework.

Regards

Pape S. Diop

Hi Diop! Thanks for the nice comment. I really appreciate ...

Hi Diop!

Thanks for the nice comment. I really appreciate it. Yes with conventions, things will become more easy. JSF is already a great web framework but it could be more..

Regards

Lamine

A Multi-templating System in JSF 2.2 : what does it mean for you?

Posted by lamine_ba on November 12, 2011 at 2:25 PM PST

 

For prosperity to be sustained it must be shared.
thegatesnotes

Introduction

Ladies and Gentlemen, today, while I'm writing this blog post, I'm one-eyed. Last saturday, I woke up earlier in the morning and I noticed that I couldn't see out with my right eye. I went to see an ophtalmologist to find the cause and the solution and now I'm taking drugs. I'm sharing this crazy experience with you only because it has teached me something. That life is all about having the right vision and you can do that only if you are in the right perspective to see the things right.

Now let's come back to the subject of my blog post, a Multi-templating system in JSF 2.2 : what does it mean for you?  But before answering this question, could I have an insight of your perspective? Who are you in regard to the JSF audience? a Page Author, a Component Writer, an Application Developer, a Tool Provider or a JSF Implementor? If your role belongs to any of these categories, it is fair to call you a "Web Developer". And myself I can fairly say that you are not the primary target of this feature. We have built this Multi-templating system inspired by Joomla's, the most popular CMS in the PHP world, to correct a mistake that Java EE and its web frameworks are doing ever since.

 

Why did they put the web designers aside? Why Java EE has the ugliest user interfaces I have ever seen ? Why most of the web sites are Php-based ? Truly, in the web and in term of audience, a weak language is kicking the ass of a Platform. Woow! that is really amazing! A real remake of David and Goliath. And as a confirmation, I'm going to share with you a little part of the discussion I had yersterday with Akintayo Abiona Olusegun, a nigerian developer who has converted his PHP application into a JSF one. I asked him why he did that and also if I could have an insight of the state of art in the area of web development in his country. And below are his answers.

 


 

"I did decide to use JSF not because I have any particular problems with PHP, No. The website needs a facelift and since I have just studied JSF and all the goodness, I decided to use JSF. Primefaces is also one of the things that help my decision. Most of the things I have to write css and/or javascript (or look for plugins upon plugins for jquery) are made very easy using primefaces. Java EE 6 was the icing on the cake. It is really now very easy to do a Java EE APP compared to say 5 years ago......"

 

"Here in Nigeria, the predominant web design language is still PHP though. A few people use java for web really, Most people just either use PHP or ASP.NET. The reason is because hosting a Java APP is still very expensive and most of the independent Java developers I know can't afford it. But Java is still the most popular programming language, ALL the companies I know use Java somehow. The biggest companies here (telecoms, oil and gas and banking) are all using Java and Oracle tools, so to get a Job in these companies, Java knowledge is a MUST. But a very high percentage of the freelancers I know use PHP for web..."

 


But soon such will not be the case because a metamorphosis is happening and we were clever enough to include the web designers in the audience of the upcoming 2.2 version of JSF. And depending on the perspective you are, it means these things for you : Like for Joomla and PHP, JSF and the Java EE world are moving towards a worldwide collaborative development. A JSF developer will no longer create the user interface of his web application, he will just download a template made a template author from all over the world. And you can be sure that it will happen because it is much easier now to design a JSF template than a Joomla template. No knowledge of JSF and Java is required. Only a knowledge of html, css, javascript, photoshop and such. And you can be sure that soon we will have all these templates available to us : Joomla Templates . Very cool, no?

Let's meet in the Cloud

Let's come now to the other part of the problem and here is how I will start. Am I the only one who has the vision that once we have released an implementation of JSF 2.2 and its Multi-Templating system, these two questions will arise :

  • From a developer perspective : Where can I find templates?
  • From a template author perspective : Where can I publish free and commercial templates to make my own business?

Don't you see that if we do nothing, we will end up by having like for Joomla this awful distributed model : "Do it yourself. Build your own solution and host it on your own infrastructure and don't forget to reference your web site if you want the developers to find your templates through a Google search." So can you understand our desire to make things simple by building a service in the Cloud to connect these two entities into a central place :

  • so that a web developer can find templates easily without searching the whole web
  • so that a professional web design individual or company will not build and host a solution he cannot afford.

And to have this dream fullfilled, we are planning to collaborate with a Cloud provider so that we can push JSF and Java EE to the next level. So be ready to meet us soon in the Cloud....

JSF 2.2 : The Movie [ Coming Soon ]

Following our desire to innovate, JSF 2.2 will be the first JSR to have a video presentation. It will be made available after the Final Draft but below are some screenshots.I definitely recommend you to do the same for your project. You can use After Effects for that. Professionnal video designers are using this tool for most of the animations and the movies you are watching on TV. If you want to learn more about it and to have an insight of the video design universe, I suggest you to follow the tutorials of Andrew Kramer on his videocopilot.net web site. Definitely worth giving it a look, this guy is truly awesome....

 

 

Conclusion

Ladies and Gentlemen, everything has been said and done so I will not waste your time anymore. Let's just meet here next time for another blog post. So until then, I'm going to take my drugs. Hope I will recover soon my whole vision...

AttachmentSize
video5.PNG457.64 KB
video6.PNG246.65 KB
video1.PNG456.16 KB
video4.PNG476.11 KB
video2.PNG454.58 KB
video3.PNG371.68 KB
Related Topics >>

Comments

Hi bro, hope my message find you in good heath that allow ...

Hi bro, hope my message find you in good heath that allow you to continue to solve a big problem in JavaEE. This blog has very nicely explained. JSF2.2+PrimeFaces will biggy improve the development web in JavaEE platform. I still believed JSF and i continue to believe it, because it will be the solution.
Regards!!

Hi papesdiop Thank you very much for your nice comment and ...

Hi papesdiop

Thank you very much for your nice comment and I appreciate your prayer. Yes, continue to believe in Java EE and JSF. Having a bad start in the starting-block does not mean you cannot be the winner of the race. The JSF community, you included, is currently doing an amazing work. But more are coming. Hope to read you soon.

Regards
Lamine

Good day,&nbsp; This is a really awesome idea and it has my ...

Good day,

This is a really awesome idea and it has my vote to be included in the JSF spec. I wonder if it would be possible to have the templates externalized from the actual WAR file which has a number of advantages.

Regards,

Mark P Ashworth (http://mpashworth.wordpress.com)

Hello Mark, First of all, thank you very much for your vote ...

Hello Mark,

First of all, thank you very much for your vote and for your clever comment. Yes, having the templates externalized from the actual WAR file has a number of advantages and that is a part of a topic I have called : " The deployment scenarios ". When I have built the prototype of this Multi-templating system, I have covered and solved this problem at last. I was waiting just for people to understand the idea and I'm really glad they did it. Let's me share with you now the different deployment scenarios available to us so that you can choose the right one depending on your needs.

  1. First scenario : you have stored your templates in a directory in the war file. Can we call this : " the evident and non-efficient way ". With this model, how one can share his templates among his JSF applications?  Surely with a copy and paste? The use of this model will lead to a lot of duplication. And when a developer downloads his templates from the web on his computer, he stores them already in an external directory. So why can't he just reference in the web.xml the location of this directory to have the templates loaded by any of his JSF applications? That is one solution but it means these things for you : you are working alone and your applications are running in a local mode. And when you deploy your JSF application in a remote web server and the templates are still in your local external directory, you must also upload this directory and make the right change (location) in the web.xml. But at least, using this solution, you have a central place and any of your JSF applications hosted on this remote web server can share your templates. Thus you have no resources duplication.To finish, when you are collaborating with a team using this solution in the development of a JSF application, my suggestion is to create first a svn or a git repository for only the storage of templates.
  2. Second Scenario : Here is another cool way to externalize your templates. Did you know that you can use my own templates without having them installed on your computer? How I did that? I have a template service built with JAX-RS available worldwide. You can see it in action in my prototype. My JSF applications are using these templates remotely because each template has an url  and I can reference one of them in my web.xml. And after that, I let the two entities (JSF and JAX-RS) to talk and make my will. And with this solution I can build another template clients like an android client to view my templates on my phone. cool, no?

JSF and JAX-RS playing seamlessly

 If you find another deployment scenario, It would be nice if you can share it to us. I have also the project of an administration console so that you can manage easily your templates and set the default one at runtime without the use of the the web.xml file so that you can avoid a restart of your application and a waste of your precious time. At last, I think that you will be the guest star of one of my next blog posts because many people will not read your clever comment and my reply. Thank you again Mark

Regards
Lamine

&nbsp;I concur. Having the template outside the war file ...

I concur.

Having the template outside the war file means you can change the LAF of your page without having to recompile the whole app. This would be very advantageous. I think this would be also be easy if one can link to the template using say href. Right now what I do is host my images and css file in apache, so that I can change the images and css files easily to change the LAF of my web page without having to recompile/re-deploy.

Thanks Lamine.

Hi trinisoftinc, Thank you very much for your nice comment. ...

Hi trinisoftinc,

Thank you very much for your nice comment. Yes, Having the template outside the war file means you can change the LAF of your page without having to recompile the whole app and this would be very advantageous. And you can be sure that you will have it. Please read my reply to Mark or wait for my next blog post. Regarding your statement "I think this would be also be easy if one can link to the template using say href", Let me reveal you that we have already this feature and it working pretty well on my prototype. We call it "Dynamic Template Selection". You can change the LAF of your application while navigating to another page of course if your add in the url the id of the template you want to use as a request parameter following this scheme : http://server/app/page.xhtml?template=id. Please see it in action in my prototype . Thanks

One page using dynamically three different templates

  1. http://jsfmtsystem.appspot.com/faces/templateDetails.xhtml?template=tbc_xen
  2. href="http://jsfmtsystem.appspot.com/faces/templateDetails.xhtml?template=pinkkitty
  3. http://jsfmtsystem.appspot.com/faces/templateDetails.xhtml?template=rockstar

Regards
Lamine

hi all . &nbsp;i ask what it is El resolver into ...

hi all .

i ask what it is El resolver into JSF .

I study JSF self me and i not understand .

Tank you all.

naciu

Hi naciu45 I'm very glad to hear that you are learning JSF ...

Hi naciu45

I'm very glad to hear that you are learning JSF and I like very much your approach. When you want to have a clear understanding of something, you must always try to understand first its concepts. Google can be your best friend in your learning process, just type what you are looking for in the input text or you can consider to buy a recent JSF book covering the 2.0 version of JSF. I recommend you "JSF 2.0 the complete reference" from Ed Burns. But here are some links I have found in the web. Try first to understand what is an Expression Language (EL) and after it will be very easy for you to understand what is an EL Resolver. These concepts were first introduced in JSP. 

Thanks
Lamine

Conventional UI design with Facelets and JSF 2.2

Posted by lamine_ba on October 3, 2011 at 1:54 PM PDT

 

An experience is relevant only if it can prevent you to repeat the same mistake.
Anonymous

Introduction

Make it compliant! Yes, Ladies and Gentlemen, Make it compliant! That is my tip of the day and the statement I woke up with today. Like many of you, I have read the Jsf-spec pdf file and as you may know, JSF 2.2 is coming with two major features : Faces Flows and Multi-templating. Did you see that it will be possible to package a Faces Flow and a template as a jar file, or as an exploded directory? And that it will be possible to offer faces flows and templates as re-usable components in a software repository, such as a maven repository ? In other words, the new vision of JSF is “drop in and go”. There is nothing wrong and suspicious in that strategy but I'm only curious to see how this will gonna happen if we haven't any conventions yet. You would be in a big dream if you think that my view can reuse your template if it does not bring well-known areas. Just take a look at this sample to be convinced :

Your Template

  1. <ui:insert name="windowTitle">
  2.         XEN Template
  3. </ui:insert>
  4.  
  5. <ui:insert name="top">
  6.         top design
  7. </ui:insert>
  8.  
  9. <ui:insert name="login-area">
  10.          login-area design
  11. </ui:insert>
  12.  
  13. <ui:insert name="search-area">
  14.         search-area design
  15. </ui:insert>
  16.  
  17. <ui:insert name="navigation">
  18. </ui:insert>
  19.  
  20. <ui:insert name="body">
  21. </ui:insert>
  22.  
  23. <ui:insert name="bottom">
  24.         bottom design
  25. </ui:insert>
  26.  

My view using another Template

  1. <ui:define name="title">
  2.         My View
  3. </ui:define>
  4.  
  5. <ui:define name="header">
  6.         header design
  7. </ui:define>
  8.  
  9. <ui:define name="login">
  10.          login design
  11. </ui:define>
  12.  
  13. <ui:define name="search">
  14.         search design
  15. </ui:define>
  16.  
  17. <ui:define name="menu">
  18.         menu design
  19. </ui:define>
  20.  
  21. <ui:define name="content">
  22.         content design
  23. </ui:define>
  24.  
  25. <ui:define name="footer">
  26.         footer design
  27. </ui:define>
  28.  

In other words, your template is not compliant with my application because you and I have chosen the stupid strategy of using a different name to name the same thing. Crazy no! I think it is high time to be homogeneous and to escape from this insanity by making our new components "compliant" with any JSF application . For the case of our templates, that is very easy. Let's design a template according to the basic structure of the user interface of a web application. Let's bring this simple contract and let's all use these well-know values : title, header, login, search, menu, content, footer. But if you want, we can even further reduce this list if we all agree that a view will only override the title and the content areas. And also if we all agree that the other areas minus the menu area must be designed statically in the template. Isn't it the whole idea behind customization? You don't like the design of the header, just go in the template and change it. But if you were a true web designer, you would know that this customization is even done with css. Here is now the strategy we are expecting to see in any template  :

  1. <div id="header">
  2.         common header design
  3. </div>
  4.  
  5.  
  6. <div id="footer">
  7.         common footer design
  8. </div>
  9.  

or 

  1. <div id="header">
  2.    <ui:insert name="header">
  3.         common header design
  4.    </ui:insert>
  5.  
  6. </div>
  7.  
  8.  
  9. <div id="footer">
  10.    <ui:insert name="footer">
  11.         common footer design
  12.    </ui:insert>
  13. </div>
  14.  

but not this 

  1. <div id="header">
  2.   <ui:include src="/header.xhtml"/>  
  3. </div>
  4.  
  5.  
  6. <div id="footer">
  7.    <ui:include src="/footer.xhtml"/>  
  8. </div>
  9.  

nor this

  1. <div id="header">
  2.   <ui:insert name="header"
  3.         <ui:include src="/header.xhtml"/>  
  4.   </ui:insert>
  5.  
  6. </div>
  7.  
  8.  
  9. <div id="footer">
  10.   <ui:insert name="footer"
  11.         <ui:include src="/footer.xhtml"/>  
  12.  </ui:insert>
  13. </div>
  14.  

The design technique above must only be applied for the menu area because a menu is the only thing a template cannot come with

  1. <div id="menu">
  2.  
  3.   <ui:insert name="menu"
  4.         <ui:include src="/menu.xhtml"/>  
  5.   </ui:insert>
  6.  
  7. </div>
  8.  

We are also expecting the menu to be designed like this, with <ul> and <li> 

menu.xhtml

  1. <ui:composition xmlns="http://www.w3.org/1999/xhtml"  
  2.      xmlns:h="http://java.sun.com/jsf/html"  
  3.      xmlns:ui="http://java.sun.com/jsf/facelets">
  4.                  
  5.      <ul>
  6.               <li>
  7.                         <h:link value="Home" outcome="index"/>
  8.                  </li>
  9.                
  10.                 <li>
  11.                         <h:link value="Templates" outcome="templates"/>
  12.                        
  13.                 </li>
  14.                
  15.                 <li>
  16.                         <h:link value="Gallery" outcome="gallery"/>
  17.                 </li>
  18.                
  19.                 <li>
  20.                         <h:link value="About" outcome="about"/>
  21.                 </li>
  22.                
  23.                 </ul>
  24.                        
  25.     </ui:composition>

So that a template author can give it its style and layout with css :

template.css

  1. #menu { height: 49px; width:978px;background: #FF7805  }
  2.  
  3. #menu ul { width: auto; float: right; list-style-type:none; }
  4.  
  5. #menu ul li{ margin: 0; padding: 0; height: 49px; float: left; position: relative; }
  6.  
  7. #menu ul li a{ color: #FFFFFF; font-weight: bold; text-decoration: none; }
  8.  
  9. #menu ul li a:hover{ background-color: rgb(245,235,207);color: #444444; }
  10.  

So that you can get according to the template the following menu :

or this one

If you are ready to follow these conventions, I'm ready to share all my templates with you and even this application ( http://jsfmtsystem.appspot.com/faces/templates.xhtml ) so that any of you can deploy it worldwide. If you download it, you will be able to manage your own repository through a nice web interface built with JSF and to share your templates with your users through REST. Yes, it has also a Template Service built with JAX-RS ( http://jsfmtsystem.appspot.com/services/templates )

Template Service (serving XML Representations)

  1. <templates>
  2.  
  3. <template>
  4. <id>1</id>
  5. <name>world_cup</name>
  6. <creationDate>2010-06-15</creationDate>
  7. <author>Themza Team</author>
  8. <authorEmail>templates@themza.com</authorEmail>
  9. <authorUrl>http://www.themza.com</authorUrl>
  10. <creationDate>2010-06-15</creationDate>
  11. <copyright>ThemZa 2009</copyright>
  12. <license>ThemZa TOS</license>
  13. <description>World Cup Heroes</description>
  14. <link>http://jsfmtsystem.appspot.com/services/templates/1</link>
  15. <thumbnail>http://jsfmtsystem.appspot.com/services/templates/1/thumbnail</thumbnail>
  16. <download>http://jsfmtsystem.appspot.com/services/templates/1/download</download>
  17.  
  18. </template>
  19.  
  20. ......
  21.  
  22. ......
  23.  
  24. </templates>

Build your own Template client

To make things funny, You can even build your own client or download my upcoming google android application to consume this service.

Using a Template Remotely

No need to download a template, your application can use it remotely. Isn't it the whole idea behind "Cloud"? You can also use this strategy to avoid resources duplication when your application is running in a clustered environment.

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app>
  3.  
  4.  
  5. <context-param>
  6.         <param-name>javax.faces.view.TEMPLATE</param-name>
  7.         <param-value>http://jsfmtsystem.appspot.com/services/templates/1</param-value>
  8. </context-param>
  9.  
  10.  
  11. </web-app>

Template Highlighting

The ui:insert tags can now be highlighted in the UI. Just send in your request the highlight parameter and set its value to true. You can see this feature in live here : Template Highlighting

Conclusion

Ladies and Gentlemen, that's all for today. But remember, having conventions is the only way for us to collaborate so that we can move fast.

AttachmentSize
mobile_client.PNG116.56 KB
template-highligh.PNG325.46 KB
Related Topics >>

Multi-Templating with JSF 2 : The Prototype

Posted by lamine_ba on August 28, 2011 at 10:24 AM PDT

Revolution is only the next step to Evolution
Anonymous

Introduction

Here we are, Yes ladies and Gentlemen, Here we are. After having shared the story with you, here is the presentation of the prototype of the multi-templating system of JSF 2.2. Meanwhile, an application has been deployed worldwide with google app engine and below are the instructions on how to use it both remotely and locally. We sincerely hope that you will enjoy this concept and as always we value your comments.

How to use the application remotely?

  1. With your browser point to this url : http://jsfmtsystem.appspot.com/ to display the home page and because of the configuration below,
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <web-app>
    3.  
    4.  
    5. <context-param>
    6.         <param-name>javax.faces.view.TEMPLATE</param-name>
    7.         <param-value>rockstar</param-value>
    8. </context-param>
    9.  
    10.  
    11. </web-app>

    the rockstar template is selected

     

  2. If you want to select another template, click on the templates link to display the templates list.

  3. Point your cursor on the name of one template to see its thumbnail or click on it to select this template
  4. Wanna see the templates gallery? click on the gallery link to display it. To enlarge a thumbnail, just click on it. To select a template, click on the name.
  5. To finish, you have an about link to show the About page which says that the JSR 344 EG is working very hard to give you an outstanding new version of JavaServer Faces. So please, be patient and be ready to check it out once available..

    Multi-Templating System

    Author(s): JSR 344 Expert Group
    Version: 1.0
    Requirements: JSF 2.2
    Description: Change the look and feel of your JSF applications.

 

How to run the application locally with maven and the embedded glassfish plugin ?

  1. With svn, check out the application at this url : https://svn.java.net/svn/jsf-extensions~svn/branches/SPEC_532_MODULAR_JSF
  2. With maven, run mvn package embedded-glassfish:run to deploy the application
  3. And finally with your browser point to this url : http://localhost:8080/app/

Conclusion

Ladies and Gentlemen, we wish you a nice try and undoubtedly, Reuse is the only way to speed up development and boost productivity. Be sure that soon we will move to a higher concept like Application as a Template...

AttachmentSize
rockstar.PNG401.66 KB
templateslist.PNG458.47 KB
daydream.PNG864.64 KB
gallery.PNG193.5 KB
Related Topics >>

Comments

If you want to see this in JSF 2.2, please vote for the ...

If you want to see this in JSF 2.2, please vote for the corresponding issuetracker issue: java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-971.

Multi-Templating with JSF 2 : The Story

Posted by lamine_ba on June 5, 2011 at 1:56 PM PDT

One thing can have several representations but each of the representations means the same thing.
Everything is an object and every object has a virtual representation.
You don't believe me! Well, look at your shadow...
Anonymous

Introduction

When describing a feature, one must always show to his readers the set of contexts in which its use can bring a significant value . If you can't do that, there is no way to convince the users to give it a try . The feature I'm about to present is called "Multi-templating with JSF 2" and to further open the presentation, I'm starting today with a simple question. Does it make sense to have a dynamic templating system inside of the Java Server Faces Framework? What are the set of contexts in which its application can bring a significant value to its users? The answer is self evident for those who are in the right perspective to see the rationale of this idea. For the others, it might be wise to take the time to find it through the story of this web designer. Let's start by reading his profile.

The Profile

name : Jim
Job : Web designer
Skills : HTML, CSS, Javascript, JSP, Facelets, Photoshop, Illustrator

The Story

Jim is working with a team of 19 web developers and they have the mission to build web applications using the JSF framework. The separation of concerns has been made as easy as to assign to Jim the simple task to design the master page and to define the look and feel of the web user interface. The web developers in the other hand, have the heavy task to build the application logic broken into a set of modules and to create the views that use the master page. Since the release of JSF 2.0 and the advent of its resource handling mechanism, the life of Jim has never been so easy. Where to store the css, the js and the images files was not anymore his question.

And since he has found the right convention with his team about the right place to store the master page (facelets template), their integration process has never been so easy. The root directory has been chosen.

  1.   <html xmlns="http://www.w3.org/1999/xhtml"  
  2.      xmlns:h="http://java.sun.com/jsf/html"  
  3.      xmlns:ui="http://java.sun.com/jsf/facelets">  
  4.  
  5.     <body>  
  6.      
  7.     <ui:composition template="/template.xhtml">
  8.  
  9.      
  10.      </ui:composition>        
  11.              
  12.     </body>  
  13.  
  14. </html>

And Jim, like any perfect innocent was living in a perfect world until.........

The Mutation

Until his boss came one day with a new requirement : their JSF applications must now be able to change dynamically their look and feel. And Jim to wonder how he could achieve this miracle without a little bit of programming. He has already understood that changing dynamically the look and feel of an application means only building several themes for this application. And that a theme is nothing more than what he calls a master page or a template. And that for each template, he has only to create a facelets page and the resources (css, js,images) it needs and store them in the right places.

But what Jim didn't know was, the right places he thought , were not in fact the right places to meet a clean separation. The proof is the message he was getting. His IDE was warning him that there is a file that already exists in the selected destination and if he wants to overwrite it

And Jim to exclaim "oh what a bad and monolithic approach!" and Jim to ask "Hey how to be modular? How to avoid resources name collision?". And surprisingly the inspiration which came to him was to create a folder for each template and to surprisingly store the whole thing in a directory named "templates".

But what Jim didn't know was, all he did were just the beginning of a great inspiration. And again he couldn't help asking himself "Hey If a template has a thumbnail, who can stop me to build a template gallery for one to see what it looks like?"

And to complete his work, Jim brought the rule that a template must always have a metadata for one to know its designer.

  1. <template>
  2.  
  3.         <name>Roses</name>
  4.         <version>1.0</version>
  5.         <creationDate>05/06/2011</creationDate>
  6.         <author>Jim DRY</author>
  7.         <authorEmail>jim@yahoo.com</authorEmail>
  8.         <authorUrl>http://www.web-design.org</authorUrl>
  9.         <description>Blogstyle JSF Template</description>
  10.  
  11. </template>
  12.  

You want to become famous! wait for the release of JSF 2.2 and its multi- templating system so you can like Jim, design and share your templates with the JSF community. And maybe someday I will blog about you to share your story....

Dynamic Resolution of a template

  1. <html xmlns="http://www.w3.org/1999/xhtml"  
  2.     xmlns:h="http://java.sun.com/jsf/html"  
  3.     xmlns:ui="http://java.sun.com/jsf/facelets">  
  4.  
  5.     <body>  
  6.      
  7.     <ui:composition template="#{template}">
  8.  
  9.      
  10.      </ui:composition>        
  11.              
  12.     </body>  
  13.  
  14. </html>
  15.  

Selecting a template at startup

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app>
  3.  
  4.  
  5. <context-param>
  6.         <param-name>javax.faces.view.TEMPLATE</param-name>
  7.         <param-value>mybusiness</param-value>
  8. </context-param>
  9.  
  10.  
  11. </web-app>

The Movie

For a better illustration of this feature, you can watch the video presentation of my project "Metamorfaces". I have created this video with After Effects and some plugins like Trapcode and Knoll Light Factory. The sounds have been composed by my little brother
.

The Prototype

Things are getting long and I'm getting tired. The presentation of the prototype will be the subject of my next blog post. So until then, ladies and gentlemen, have a good night.....

AttachmentSize
dialog.PNG10.46 KB
templating-structure2.PNG8.38 KB
templating-structure3.PNG10.97 KB
template-gallery.PNG115.69 KB
templating-structure4.PNG14.66 KB
template-list.PNG51.26 KB
Related Topics >>

Moonlight Thoughts

Posted by lamine_ba on May 21, 2011 at 1:32 PM PDT

In computer science, in the context of data storage and transmission, serialization is the process of converting a data structure or object into a format that can be stored and "resurrected" later in the same or another computer environment. Java provides automatic serialization which requires that the object be marked by implementing the java.io.Serializable interface. Implementing the interface marks the class as "okay to serialize. There are no serialization methods defined on the Serializable interface, but a serializable class can optionally define methods with certain special names and signatures that if defined, will be called as part of the serialization/deserialization process. The language also allows the developer to override the serialization process more thoroughly by implementing another interface, the Externalizable interface, which includes two special methods that are used to save and restore the object's state.

Wikipedia

Introduction

Last week, while letting a beautiful moon shine, my friend Bob and I were discussing. We didn't find in that evening, any interesting subject other than my previous blog post, which was if you remember, the writing expression of a skeleton. The skeleton of a solution. The solution of how to "implement a cascading dropdown using the JSF framework". And today, coming again with the tremendous desire to share, my friend Bob and I are very pleased to give you a replay of that conversation so you can touch our moonlight thoughts. Furthermore, when all things are said and done, what else from an ending whisper than to fall into a deep silence and let the story begin...

The Conversation

Me: Hey Bob! Have you read my last blog post on java.net?

Bob: Which one? the one talking about how to implement a cascading dropdown with JSF 2?

Me : Yes this one. In the case you read it, did you have your question answered?

Bob: I'm really sorry, I can't remember what it was. Could you be more accurate?

Me: Of course, bob. Last time, you were asking me what was the correlation between an UISelectOne component and a bean put in any scope
after having asked you why I was getting this validation error.

Bob: Oh yeah! I can still remember this one and like I often say to my coworkers, the solution comes always when the question is better asked.
In the way it is designed, the validation of the value of an UISelectOne or an UISelectMany component will always fail when
having your bean put in the request scope.

  1. public class UISelectOne extends UIInput {
  2.  
  3. protected void validateValue(FacesContext context, Object value) {
  4.  
  5.         // Skip validation if it is not necessary
  6.         super.validateValue(context, value);
  7.  
  8.         if (!isValid() || (value == null)) {
  9.             return;
  10.         }
  11.  
  12.         // Ensure that the value matches one of the available options
  13.         boolean found = SelectUtils.matchValue(getFacesContext(),
  14.                                                this,
  15.                                                value,
  16.                                                new SelectItemsIterator(context, this),
  17.                                                getConverter());
  18.  
  19.         boolean isNoSelection = SelectUtils.valueIsNoSelectionOption(getFacesContext(),
  20.                                                this,
  21.                                                value,
  22.                                                new SelectItemsIterator(context, this),
  23.                                                getConverter());
  24.  
  25.         // Enqueue an error message if an invalid value was specified
  26.         if ((!found) ||
  27.             (isRequired() && isNoSelection)) {
  28.             FacesMessage message =
  29.                 MessageFactory.getMessage(context, INVALID_MESSAGE_ID,
  30.                      MessageFactory.getLabel(context, this));
  31.             context.addMessage(getClientId(context), message);
  32.             setValid(false);
  33.         }  
  34.     }
  35. }

JSF like any logical system is unable to validate a value against a list of values which becomes unavailable at the end of the request.Your only advice could be to keep the state and that is exactly what it does when the bean is put in the view scope.

Me: But bob, do you see any reason why the value is not validated against the tree? Aren't the set of valid values simply children of the UISelectOne?

Bob: Yes they are but let me show you where the problem is. No one can do a value comparison against the UISelectItems component because we only save the value expression which means a regeneration of the data model through a costly EL evaluation at any phase we need the data. One must now question why we cannot replace in the tree an UISelectItems by a list of UISelectItem? Having not myself the answer, I leave it to your appreciation.

Me: And I'll forward it to Ed Burns. Now let's come back to the ViewScope. As you state, the only advice we can give to JSF is to keep the state and all of this reminds me the UISaveState component from MyFaces Tomahawk project. Does it work the same?

Bob: The Tomahawk t:saveState tag provides an alternative "view" scope. It allows objects to be associated with the current JSF view, so that they are kept alive while the user stays on the same view, but are automatically discarded when the user moves to another view. Note that the t:saveState tag does require that all the objects it stores are Serializable or implement the JSF StateHolder interface.When JSF is configured to use "client-side-state-saving"

  1. <context-param>
  2. <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
  3. <param-value>client</param-value>
  4. </context-param>

then objects in "view" scope are automatically sent to the browser along with the rest of the JSF view state.However of course the network bandwidth needed does increase as the view-scoped objects must be transferred back and forth on each request. In the other hand, when JSF is configured to use "server-side-state-saving"

  1. <context-param>
  2. <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
  3. <param-value>server</param-value>
  4. </context-param>

then objects in "view" scope are automatically stored in the HttpSession along with the rest of the JSF view state.

Me : Having now the proof that we are talking about the same concept, it is self evident that I did a mistake in my previous blog post. If state saving means really Serialization, how JSF could save the state of a bean and its members if they don't implement the Serializable interface?

  1. @ManagedBean
  2. @ViewScoped
  3. public class Bean implements Serializable {
  4.  
  5. }

Bob: Very good question. The ViewScope is attached to the UIViewRoot and when the UIViewRoot state is saved, it may be serialized by the StateManager implementation.

  1. public class UIViewRoot extends UIComponentBase implements UniqueIdVendor {
  2.  
  3. private Map<String, Object> viewScope = null;
  4.  
  5. public Map<String, Object> getViewMap() {
  6.  
  7.     return getViewMap(true);      
  8. }
  9.  
  10. public Map<String, Object> getViewMap(boolean create) {
  11.  
  12.         if (create && viewScope == null) {
  13.             viewScope = new ViewMap(getFacesContext().getApplication().getProjectStage());
  14.             getFacesContext().getApplication()
  15.                   .publishEvent(getFacesContext(),
  16.                                 PostConstructViewMapEvent.class,
  17.                                 this);
  18.         }
  19.         return viewScope;  
  20. }
  21.  
  22. }

Me: Shame on my reviewer! But the real truth is that I haven't tried the solution myself until yesterday and guess what, I got this nasty java.io.NotSerializableException error

Bob: ooh! I'm really sorry for the frustration but did the CDI @Inject annotation work for you? What were your dependencies? SeamFaces or Myfaces CODI? And by the way, aren't these annotations that share the same unqualified name confusing to you?

Me: Yes from the perspective of a beginner, they are. I use SeamFaces to enable the CDI injection on my bean

Bob: and did you replace @ManagedBean by @Named ?

Me: of course, after having got a traumatic NullPointerException. You have to use the @Named annotation so that CDI is used instead of JSF but it is really intriguing why we cannot automatically map JSF managed bean annotations to CDI annotations at startup. It is high time to think about what to do with JSF's own managed bean mechanism.

Bob: Yes I agree and like it is stated in its goal, JSF is a user interface framework for Java Web applications designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client.

Me: So if I'm following you, JSF must now focus on the UI, delegate the DI task and deprecate its managed bean mechanism.

Bob: You already know my position about this debate so why talking more about it. I would rather talk about why haven't you packaged your solution into a reusable unit we can download, install and try.

Me: Oh bob! I wish I could but this feature is currently under prototyping in JSF 2.2. We call it Support for modular, reusable, fragments of a web application. My apologies for the time wasted and for the copy and paste. But believe me soon all this pain will belong to the past......

Related Topics >>

Implementing a Cascading DropDown with JSF 2

Posted by lamine_ba on May 12, 2011 at 11:42 AM PDT

The Beginning

The term " Cascading DropDown" means a dynamic dependent list boxes that allow a “child” list box to refresh when a selection is made in a “parent” list box. It is a recurrent problem in the software space which has only one solution but sadly there are several implementations of that solution.It depends on the tools you use and their limitations which can force you to invent ways that shouldn't be invented.This blog entry is all about how to implement a cascading dropdown using the JSF framework and today we have the simple requirement to display a list of countries and to update a list of cities once a country is selected. Having now the scenario, I think we can start to present the actors :

The Entities

  1. public class Country {
  2.  
  3.         private Long id;
  4.         private String name;   
  5.        
  6. }
  7.  
  8. public class City {
  9.  
  10.         private Long id;
  11.         private String name;
  12.         private Country country;
  13.        
  14. }

The DAO [Provide your own implementation]

  1. public interface Dao {
  2.  
  3. public List<Country> getCountries();
  4.        
  5. public List<City> getCities(Long country_id);
  6.  
  7. }

The Managed Bean

  1. @ManagedBean
  2. public class Bean {
  3.  
  4.         private Long country_id=0L;  // select the first option in the combo
  5.         private Long city_id=0L;    // select the first option in the combo
  6.         private @Inject Dao dao;
  7.        
  8.         public List<Country> getCountries() {
  9.                
  10.                 return dao.getCountries();
  11.                        
  12.         }
  13.        
  14.         public List<City> getCities() {
  15.                
  16.                 return dao.getCities(country_id);
  17.                        
  18.         }
  19.        
  20. ..................................................................
  21.  
  22. }

The Facelets view

  1. <html xmlns="http://www.w3.org/1999/xhtml"
  2. xmlns:f="http://java.sun.com/jsf/core"
  3. xmlns:h="http://java.sun.com/jsf/html">
  4.  
  5. <h:head>
  6.  
  7. <h:outputScript name="jsf.js" library="javax.faces"/>
  8.  
  9. </h:head>
  10.  
  11. <body>
  12.  
  13. <h:form>
  14.  
  15. <h:selectOneMenu value="#{bean.country_id}" id="countries">
  16.         <f:selectItem itemLabel="-- Select a Country -- " itemValue="0"/>  
  17.         <f:selectItems value="#{bean.countries}" var="country" itemValue="#{country.id}" itemLabel="#{country.name}"/>
  18.         <f:ajax event="change"  render="cities" />
  19. </h:selectOneMenu>  
  20.  
  21.  <h:selectOneMenu value="#{bean.city_id}" id="cities">
  22.         <f:selectItem itemLabel="-- Select a City -- " itemValue="0"/>    
  23.         <f:selectItems value="#{bean.cities}" var="city" itemValue="#{city.id}" itemLabel="#{city.name}"/>
  24.  </h:selectOneMenu>
  25.  
  26.  
  27. </h:form>
  28.  
  29. </body>
  30.  
  31. </html>

The End

And that's all. We have created a cascading dropdown without using a programmatic approach. We select a country in the first combo and automatically an ajax request is fired behind the scenes to update the other combo. This feature is really a powerful one until the idea to add a commandButton in your form to make a postback and save things, comes to you.

  1. <html xmlns="http://www.w3.org/1999/xhtml"
  2. xmlns:f="http://java.sun.com/jsf/core"
  3. xmlns:h="http://java.sun.com/jsf/html">
  4.  
  5. <h:head>
  6.  
  7. <h:outputScript name="jsf.js" library="javax.faces"/>
  8.  
  9. </h:head>
  10.  
  11. <body>
  12.  
  13. <h:form>
  14.  
  15. <h:selectOneMenu value="#{bean.country_id}" id="countries">
  16.         <f:selectItem itemLabel="-- Select a Country -- " itemValue="0"/>  
  17.         <f:selectItems value="#{bean.countries}" var="country" itemValue="#{country.id}" itemLabel="#{country.name}"/>
  18.         <f:ajax event="change"  render="cities" />
  19. </h:selectOneMenu>  
  20.  
  21.  <h:selectOneMenu value="#{bean.city_id}" id="cities">
  22.         <f:selectItem itemLabel="-- Select a City -- " itemValue="0"/>    
  23.         <f:selectItems value="#{bean.cities}" var="city" itemValue="#{city.id}" itemLabel="#{city.name}"/>
  24.  </h:selectOneMenu>
  25.  
  26. <h:commandButton action="#{bean.save}"  value="Save">
  27.  
  28. </h:form>
  29.  
  30. </body>
  31.  
  32. </html>

And boum! you get a validation error. Sadly, the combo displaying your cities is saying that the value you have picked in its list is not a valid one because this same value is not anymore in its list". Isn't it a craziness statement?. After some long and hard hours debugging the jsf.js file and looking at the tree printed in the console by my PhaseListener, I came accross no rationale idea. Everything was fine. The partial view processing and rendering were done perfectly and the state of the combo was updated and saved. And suddenly when I was about to loose hope, comes this ironical idea : "Hey put the managed bean in a higher scope".

  1. @ManagedBean
  2. @ViewScoped
  3. public class Bean {
  4.  
  5.   public String save() {
  6.  
  7.     return "next";
  8.  
  9.   }
  10. }

And definitely that was the solution and it is not ironical at all once you understand how the value of an UISelectOne is validated and what means ' to put a managed bean in the request scope'. There is a big security concern to take into account when validating the value of an UISelectOne. This security concern is summarized into this simple question : How to prevent the client side to insert values that were not valid choices? No don't worry, the JSF framework is not asking you to provide this answer. This validation has been made as transparent as to make another call of your getCities() method for a regeneration of the data model in order to do a value comparaison.

  1.  public List<City> getCities() {
  2.        
  3.      return dao.getCities(country_id);
  4.  
  5.  }

But wait a minute, the bean is created at each request and the Validation Phase is before the Update Model Values Phase. What JSF will get when running getCities() at this point of time? Just an empty list because the bean can't remember the country_id. And that is why we get this validation error ("The value is not valid") and that is why we have to put the bean in a higher scope. If we put the bean in the ViewScope, it will be removed as soon as we move to another view. Definitely the right place to put it. But wait a minute, isn't JSF calling my data access logic two times? A first call at the render phase and another call at the validation phase. That is really a big performance concern to deal with when having my data stored in a database. Then how to prevent that? Three solutions come to my mind:

  • The EG must find another way to validate the value without a regeneration of the data model
  • If the EG can't, I want to have a way to validate the value myself through a light query
  • Again if the EG can't, It is better to write your managed bean like this and let it go

 

  1. @ManagedBean
  2. @ViewScoped
  3. public class Bean {
  4.  
  5.     private Long country_id=0L;  // select the first option in the combo
  6.     private Long city_id=0L;    // select the first option in the combo
  7.     private @Inject Dao dao;
  8.     private List<Country> countries;  
  9.     private List<City> cities;
  10.  
  11.     public List<Country> getCountries() {
  12.        
  13.         if(countries==null)
  14.             countries=dao.getCountries();
  15.         return countries;
  16.     }
  17.    
  18.     public List<City> getCities() {
  19.        
  20.         if(cities==null)
  21.            cities=dao.getCities(country_id);
  22.         return cities;
  23.     }
  24.  
  25.     public void setCountry_id(Long country_id) {
  26.  
  27.            this.country_id=country_id;
  28.            cities=null;
  29.      }
  30.    
  31. }

I would like to finish this blog entry by an announcement. in JSF 2.2, the var attribute of the selectItems tag is now optional and by default its value is equal to 'item'. I look forward seeing this convention adopted by any UIComponent that accepts a var attribute.

  1. <f:selectItems value="#{bean.countries}" itemValue="#{item.id}" itemLabel="#{item.name}" />
AttachmentSize
menu1.PNG12.28 KB
menu2.PNG5.51 KB
Related Topics >>