My JSF Books/Videos My JSF Tutorials OmniFaces/JSF PPTs
JSF 2.3 Tutorial
JSF Caching Tutorial
JSF Navigation Tutorial
JSF Scopes Tutorial
JSF Page Author Beginner's Guide
OmniFaces 2.3 Tutorial Examples
OmniFaces 2.2 Tutorial Examples
JSF Events Tutorial
OmniFaces Callbacks Usages
JSF State Tutorial
JSF and Design Patterns
JSF 2.3 New Features (2.3-m04)
Introduction to OmniFaces
25+ Reasons to use OmniFaces in JSF
OmniFaces Validators
OmniFaces Converters
JSF Design Patterns
Mastering OmniFaces
Reusable and less-verbose JSF code

My JSF Resources ...

Java EE Guardian
Member of JCG Program
Member MVB DZone
Blog curated on ZEEF
OmniFaces is an utility library for JSF, including PrimeFaces, RichFaces, ICEfaces ...

[OmniFaces Utilities] - Find the right JSF OmniFaces 2 utilities methods/functions

Search on blog

Petition by Java EE Guardians

Twitter

joi, 30 iulie 2015

JavaServer Faces books collection

21 JSF books that you may want to read

JSF and Singleton design pattern

Singleton is a Creational Design Pattern with the following object structural:

The GoF (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides) book describes this pattern as "Ensure a class has only one instance and provide a global point of access to it."

A Java class is considered a singleton if:

·         it has one instance
·         provide a global point of access to it

Main aspects that you should keep in mind is that a singleton classes are:

·         not unit testable
·         not abstractable
·         not extendable

In order to respect the contract imposed by a singleton class you can write several implementations:

·         the singleton instance is created by an explicit call (in this case, you need to synchronize the creation for multithreaded environment)

public class FooSingleton {
 private static FooSingleton instance;

 // "hidden" constructor
 private FooSingleton() {}

 // obtain FooSingleton instance
 public static synchronized FooSingleton getInstance() {
  if (instance == null){
      instance = new FooSingleton();
  }
  return instance;
 }
}

·         the singleton instance is created at the same time you load the class (in this case, there is no need to synchronize the creation)

public class FooSingleton {
 private final static FooSingleton instance=new FooSingleton();

 // "hidden" constructor
 private FooSingleton() {}

 // obtain FooSingleton instance
 public static FooSingleton getInstance() {
  return instance;
 }
}

·         use a static block to obtain lazy initialization:

public class FooSingleton {
 private static FooSingleton instance=null;

 static {
        instance=new FooSingleton();
 }

 // "hidden" constructor
 private FooSingleton() {}

 // obtain FooSingleton instance
 public static FooSingleton getInstance() {
  return instance;
 }
}

·         use double‐checked locking - before locking on the singleton class and before the creation of the object:

public class FooSingleton {

 private volatile FooSingleton instance;

 // "hidden" constructor
 private FooSingleton() {}

 // obtain FooSingleton instance
 public FooSingleton getInstance() {
  if (instance == null) {
      synchronized (FooSingleton.class) {
       if (instance == null) {
           instance = new FooSingleton();
       }
      }
  }
  return instance;
 }
}

·         enum type implementation:

public enum FooSingletonEnum {
 INSTANCE;
 public void fooAction(){}
}

FooSingletonEnum foo = FooSingletonEnum.INSTANCE;

But, Java EE allows us to turn a class into a singleton via:

·         @Singleton for EJB (javax.ejb.Singleton)
                JSR-318 specification - Single thread safe and transactional shared instance. This is useful for EJBs (enterprise services) and it is managed by the EJB container.

·         @Singleton for CDI (javax.inject.Singleton)
JSR 330 specification  - In CDI this is a pseudo-scope that indicates that a bean has a single instance. CDI managed beans can be successfully used in JSF, but there is a problem with CDI managed beans annotated with @Singleton. They DON'T use proxy objects! Since there is a direct reference instead of a proxy we have some serialization issues. In order to keep the singleton state, we need to:
                - having the singleton bean implement writeResolve() and readReplace() (as defined by the Java serialization specification),
                - make sure the client keeps only a transient reference to the singleton bean, or
                - give the client a reference of type Instance<X> where X is the bean type of the singleton bean.

·         @ApplicationScoped  for CDI (javax.enterprise.inject.ApplicationScoped)
JSR 229 specification - The CDI application scope which guarantee that the class is instantiated only once. This is preferable because is much simpler to develop, test and maintain. So, when CDI is available, use this for having a singleton "surrogate" that provides a single instance and application scoped data.

·         @ApplicationScoped  for JSF (javax.faces.bean.ApplicationScoped)
JSR 314 specification - The JSF application scope which guarantee that the class is instantiated only once - JSF as framework guarantee that only one instance will be created and reused during web application's lifetime. Again, this is preferable because is much simpler to develop, test and maintain.

See: JSF singleton vs application scoped managed bean - differences?

JSF uses singletons for different purposes. Some cases are mentioned below:

 -the JSF entry point, FacesServlet 
 -the Application and lifecycle instances
  -the JSF phase listeners
 -the navigation and view handlers

miercuri, 29 iulie 2015

Java EE 8 comes with Ozark



JSF and EJBs Facade design pattern sample

Facade is a Structural Design Pattern with the following object structural:


The GoF (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides) book describes this pattern as “providing a unified interface to a set of interfaces in a subsystem.

Mainly the Facade design pattern is meant to hide a complex code (as a system/subsystem code) and to provide an unique entry point for it via an interface. There are several purposes for implementing this design pattern, and one of them is for providing a rough‐grained access to available services. Services are combined in a business logic, and form a "unit of work" easy to access.


For example, let's suppose that we want to find out the final price of a product based on the following logic:

·         check the product availability and get the product initial price
·         check the discount availability and apply a discount
·         check the delivery availability and apply delivery taxes

For each of these tasks we have a separate stateless session bean, as follows (these are the EJBs services to combine):

·         check the product availability and get the product initial price - InventoryProduct:

@Stateless
public class InventoryProduct {

 public boolean productIsAvailable(String product) {
  // some business logic here
  return true;
 }

 public int productCost(String product) {
  // some business logic here
  return 120; // initial product cost is $120
 }
}

·         check the discount availability and apply a discount - DiscountProduct:

@Stateless
public class DiscountProduct {

 public boolean discountPeriodOfTheYear(){
  // some business logic here
  return true;
 }

 public int applyDiscount(String product){
  // some business logic here
  return 100; // after the discount the product price is $100
 }
}

·         check the delivery availability and apply delivery taxes - DeliveryProduct:

@Stateless
public class DeliveryProduct {

 public boolean freeDeliveryPeriodOfTheYear() {
  // some business logic here
  return false;
 }

 public int taxDelivery(int price){
  // some business logic here
  return 103; // for $100 we add $3 delivery costs
 }
}

Further these three services should be used to create the below business logic (this is the "unit of work"):

public int orderProduct(String product) {
 if (inventoryProduct.productIsAvailable(product)) {
     int price = inventoryProduct.productCost(product);
     int discount_price = discountProduct.discountPeriodOfTheYear() ? discountProduct.applyDiscount(product) : price;
     int final_price = deliveryProduct.freeDeliveryPeriodOfTheYear() ? discount_price : deliveryProduct.taxDelivery(discount_price);

     return final_price;
 }
 return -1;
}

We take this method and place it in another stateless session bean named, FacadeProduct. Basically, this bean is the design pattern implementation. Here, we inject our services and define the orderProduct(), so when the client order a product, he knows nothing about our subsystem:

@Stateless
public class FacadeProduct {

 @Inject
 private InventoryProduct inventoryProduct;

 @Inject
 private DeliveryProduct deliveryProduct;

 @Inject
 private DiscountProduct discountProduct;

 public int orderProduct(String product) {
  if (inventoryProduct.productIsAvailable(product)) {
      int price = inventoryProduct.productCost(product);
      int discount_price = discountProduct.discountPeriodOfTheYear() ? discountProduct.applyDiscount(product) : price;
      int final_price = deliveryProduct.freeDeliveryPeriodOfTheYear() ? discount_price : deliveryProduct.taxDelivery(discount_price);

      return final_price;
  }
  return -1;
 }
}

Now, the Facade design pattern was implemented and we simply inject it in a CDI managed bean:

Named
@RequestScoped
public class ProductBean implements Serializable {

 private int price;

 @Inject
 FacadeProduct facadeProduct;

 public int getPrice() {
  return price;
 }

 public void orderProductAction(String product) {
  price = facadeProduct.orderProduct(product);
 }
}

As you can see, the managed bean is not aware of the code complexity behind the #orderProduct() call and it doesn't contain complex business logic (it is a bad practice to define in this bean our "unit of work" - in some cases, this can be pretty large and complex).

A dummy JSF page can serve as a starting point:

<h:form>
 Price: $#{productBean.price}
 <h:commandButton value="'Nike LUNAR' Product Order" action="#{productBean.orderProductAction('Nike LUNAR')}" />
</h:form>

The complete code is available on GitHub.

marți, 28 iulie 2015

Indeterminate checkboxes with JSF and OmniFaces

Note The indeterminate state of a checkbox is visual only.

Checkboxes can be submitted as checked or unchecked, but visually there are actually three states a checkbox can be in: checked, unchecked, or indeterminate, as in the below figure:

The indeterminate state is useful when we deal with nested checkboxes. Practically, each checkbox that have children is checked if all of its children are checked, and is indeterminate ("partially" checked) if at least one of its children is unchecked.

Note The indeterminate state cannot be set via HTML, is not an HTML attribute for it. It is a property of checkboxes though, which you can change via JavaScript.

The Indeterminate Checkboxes article covers this topic for pure HTML and JavaScript. The JavaScript presented there is used next for writing an example of indeterminate checkboxes based on JSF and OmniFaces Tree component. Since we are talking about a checkboxes hierarchical structure (see picture above), we can shape it as an OmniFaces Tree as below (a CheckItem instance encapsulates a checkbox information):

public class CheckItem implements Serializable {
   
 private static final long serialVersionUID = 1L;
   
 private String label;
 private boolean value;

 public CheckItem(String label, boolean value) {
  this.label = label;
  this.value = value;
 }       

 // getters and setters
}

And the CheckBean shapes an hierarchy of CheckItems:

@Named
@SessionScoped
public class ChecksBean implements Serializable {

 private static final long serialVersionUID = 1L;
 private TreeModel<CheckItem> tree;

 @PostConstruct
 public void init() {
  tree = new ListTreeModel<>();

  tree.addChild(new CheckItem("Install", false))
      .addChild(new CheckItem("Demos", false))
      .getParent().addChild(new CheckItem("Development", false))
      .addChild(new CheckItem("Simple", false))
      .getParent().addChild(new CheckItem("Advanced", false))
      .getParent().getParent().addChild(new CheckItem("Debug", false))
      .getParent().getParent().addChild(new CheckItem("Repair", false))
      .addChild(new CheckItem("Demos", false))
      .getParent().addChild(new CheckItem("Tools", false))
      .getParent().addChild(new CheckItem("Kit", false));
 }

 public TreeModel<CheckItem> getTree() {
  return tree;
 }
}

Further we display the hierarchy via a JSF page:

<h:form>
 <o:tree value="#{checksBean.tree}" var="t">
  <o:treeNode>              
   <ul>
    <o:treeNodeItem>
     <li>
      <h:selectBooleanCheckbox id="checkboxId" value="#{t.value}"/>
      <h:outputLabel for="checkboxId">#{t.label}</h:outputLabel>
      <o:treeInsertChildren />
     </li>
    </o:treeNodeItem>
   </ul>                
  </o:treeNode>
 </o:tree>
 <h:commandButton value="Submit">           
  <f:ajax execute="@form" render=":panelId"/>
 </h:commandButton>
</h:form>

Finally, we just add the JavaScript code from the IndeterminateCheckboxes article. This is based on jQuery, but you can rewrite it as plain JavaScript:

$(function () {
  $('input[type="checkbox"]').change(function (e) {
    var checked = $(this).prop("checked"),
                  container = $(this).parent(),
                  siblings = container.siblings();

    container.find('input[type="checkbox"]').prop({
     indeterminate: false,
     checked: checked
    });

    function checkSiblings(el) {
     var parent = el.parent().parent(),
        all = true;

        el.siblings().each(function () {
         return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked);
        });
        //<![CDATA[
        if (all && checked) {
            //]]>
            parent.children('input[type="checkbox"]').prop({
             indeterminate: false,
             checked: checked
            });
            checkSiblings(parent);
            //<![CDATA[
        } else if (all && !checked) {
            //]]>
            parent.children('input[type="checkbox"]').prop("checked", checked);
            parent.children('input[type="checkbox"]').prop("indeterminate", (parent.find('input[type="checkbox"]:checked').length > 0));
            checkSiblings(parent);
        } else {
            el.parents("li").children('input[type="checkbox"]').prop({
             indeterminate: true,
             checked: false
            });
        }
    }

    checkSiblings(container);
  });
});

Just for testing I have displayed another tree (with ID, panelId) as below:

The complete source code is available on GitHub.

duminică, 26 iulie 2015

[JSF Page Author Beginner's Guide] JSF <selectBooleanCheckbox> / HTML5 <input> [checkbox]

The <h:selectBooleanCheckbox> renders an  HTML "input" element of "type" "checkbox"

Common/basic usage in JSF (I) - without label defined via <h:outputLabel>:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
 <h:head>
  <title>JSF selectBooleanCheckbox examples</title>        
 </h:head>
 <h:body>
  <h:form>          
   Remember me:
   <h:selectBooleanCheckbox value="#{playerBean.rememberme}"/>
   <h:commandButton value="Submit" action="data"/>
  </h:form>
 </h:body>
</html>

The <h:selectBooleanCheckbox> will be rendered in HTML as:
<input type="checkbox" name="j_idt6:j_idt8" checked="checked" />

Common/basic usage in JSF (II) - with label defined via <h:outputLabel>:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
 <h:head>
  <title>JSF selectBooleanCheckbox examples</title>        
 </h:head>
 <h:body>
  <h:form>                      
   <h:selectBooleanCheckbox id="checkboxId" value="#{playerBean.rememberme}"/>
   <h:outputLabel for="checkboxId">Remember me</h:outputLabel>
   <h:commandButton value="Submit" action="data"/>
  </h:form>
 </h:body>
</html>

The <h:selectBooleanCheckbox> will be rendered in HTML as:
<input id="j_idt11:checkboxId" type="checkbox" name="j_idt11:checkboxId" checked="checked" />

The PlayerBean will be:

package beans;

import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named
@SessionScoped
public class PlayerBean implements Serializable {

 private boolean rememberme = true;

 public boolean isRememberme() {
  return rememberme;
 }

 public void setRememberme(boolean rememberme) {
  this.rememberme = rememberme;
 }
}

At initial request, the checkbox is selected (ticked) because the its value is initialized from bean with true. If rememberme will be initially set to false, then at initial request the checkbox will be unselected (unticked).

The data.xhtml page is:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"    
      xmlns:h="http://xmlns.jcp.org/jsf/html">
 <h:head>
  <title></title>        
 </h:head>
 <h:body>
  <!-- View submitted data -->           
   Remember: #{playerBean.rememberme}     
 </h:body>
</html>

Data flow in image:
More examples:

Add xmlns:pt="http://xmlns.jcp.org/jsf/passthrough" for pass-through attributes

Styling messages with CSS class

<h:form>
 Remember me:
 <div class="slide">                                 
  <h:selectBooleanCheckbox id="slide" value="#{playerBean.rememberme}"/>
  <h:outputLabel for="slide"></h:outputLabel>
 </div>
 <h:commandButton value="Submit" action="data"/>
</h:form>
<h:form>
 Remember me:
 <div class="rounded">                
  <h:selectBooleanCheckbox id="rounded" value="#{playerBean.rememberme}"/>
  <h:outputLabel for="rounded"></h:outputLabel>
 </div>
 <h:commandButton value="Submit" action="data"/>
</h:form>
The used CSS are available in the complete source code.

Use valueChangeListener with <h:selectBooleanCheckbox>

<h:form>
 Remember me:
 <h:selectBooleanCheckbox value="#{playerBean.rememberme}" onchange="this.form.submit();"
                          valueChangeListener="#{playerBean.rememberAction}"/>                      
</h:form>
#{playerBean.rememberme}

In PlayerBean we need to add the rememberAction() method, as below (the ValueChangeEvent is optional, you can use a void method without arguments also):

private static final Logger LOG = Logger.getLogger(PlayerBean.class.getName());
public void rememberAction(ValueChangeEvent event) {
 LOG.log(Level.INFO, "rememberAction() called, {0}", event.getOldValue() + " - " + event.getNewValue());
}

AJAXify <h:selectBooleanCheckbox>

<h:form>
 Remember me:
 <h:selectBooleanCheckbox value="#{playerBean.rememberme}">                      
  <f:ajax execute="@this" render="@form"/>
 </h:selectBooleanCheckbox>   
 #{playerBean.rememberme}
</h:form>       

AJAXify <h:selectBooleanCheckbox> with valueChangeListener

<h:form>
 Remember me:
 <h:selectBooleanCheckbox value="#{playerBean.rememberme}" valueChangeListener="#{playerBean.rememberAction}">                      
  <f:ajax execute="@this" render="@form"/>
 </h:selectBooleanCheckbox>   
 #{playerBean.rememberme}
</h:form>  

In PlayerBean we need to add the rememberAction() method, as below (the ValueChangeEvent is optional, you can use a void method without arguments also):

private static final Logger LOG = Logger.getLogger(PlayerBean.class.getName());
public void rememberAction(ValueChangeEvent event) {
 LOG.log(Level.INFO, "rememberAction() called, {0}", event.getOldValue() + " - " + event.getNewValue());
}

Indeterminate checkbox, see https://css-tricks.com/indeterminate-checkboxes/ 

<h:form id="indeterminateForm">          
 <ul>
  <li>
   <h:selectBooleanCheckbox id="basic"/>
   <h:outputLabel for="basic">Install</h:outputLabel>
   <ul>
    <li>
     <h:selectBooleanCheckbox id="basic-1"/>
     <h:outputLabel for="basic-1">Demos</h:outputLabel>
    </li>
    <li>
     <h:selectBooleanCheckbox id="basic-2"/>
     <h:outputLabel for="basic-2">Development</h:outputLabel>
     <ul>
      <li>
       <h:selectBooleanCheckbox id="basic-2-1"/>
       <h:outputLabel for="basic-2-1">Simple</h:outputLabel>
      </li>
      <li>
       <h:selectBooleanCheckbox id="basic-2-2"/>
       <h:outputLabel for="basic-2-2">Advance</h:outputLabel>
      </li>
     </ul>
    </li>
    <li>
     <h:selectBooleanCheckbox id="basic-3"/>
     <h:outputLabel for="basic-3">Debug</h:outputLabel>
    </li>
   </ul>
  </li>
  <li>
   <h:selectBooleanCheckbox id="repair"/>
   <h:outputLabel for="repair">Repair</h:outputLabel>
   <ul>
    <li>
     <h:selectBooleanCheckbox id="repair-1"/>
     <h:outputLabel for="repair-1">Demos</h:outputLabel>
    </li>
    <li>
     <h:selectBooleanCheckbox id="repair-2"/>
     <h:outputLabel for="repair-2">Tools</h:outputLabel>
    </li>
    <li>
     <h:selectBooleanCheckbox id="repair-3"/>
     <h:outputLabel for="repair-3">Kit</h:outputLabel>
    </li>
   </ul>
  </li>
 </ul>
 <h:commandButton value="Submit" action="data"/>
</h:form>  
Notice that indeterminate is not a checkbox attribute, is a JavaScript property. With other words, we can't make a checkbox indeterminate through HTML by design. The below snippet of JS (based on jQuery) can control this property in our case (the original source code is available at https://css-tricks.com/indeterminate-checkboxes/):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
 // see https://css-tricks.com/indeterminate-checkboxes/
 $(function () {               
   $('input[type="checkbox"]').change(function (e) {
     var checked = $(this).prop("checked"),
         container = $(this).parent(),
         siblings = container.siblings();

     container.find('input[type="checkbox"]').prop({
         indeterminate: false,
         checked: checked
     });

     function checkSiblings(el) {
         var parent = el.parent().parent(),
         all = true;

         el.siblings().each(function () {
             return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked);
         });
         //<![CDATA[
         if (all && checked) {
         //]]>
                 parent.children('input[type="checkbox"]').prop({
                     indeterminate: false,
                     checked: checked
                 });
                 checkSiblings(parent);
         //<![CDATA[
         } else if (all && !checked) {
         //]]>
                 parent.children('input[type="checkbox"]').prop("checked", checked);
                 parent.children('input[type="checkbox"]').prop("indeterminate",
                        (parent.find('input[type="checkbox"]:checked').length > 0));
                 checkSiblings(parent);
         } else {
                 el.parents("li").children('input[type="checkbox"]').prop({
                     indeterminate: true,
                     checked: false
                 });
         }
     }

     checkSiblings(container);
   });
 });
</script>

Require the user to tick the desired checkbox (use OmniFaces)

<h:form>                       
 <h:panelGrid columns="3">
  <h:outputLabel for="termsId" value="Tick terms and conditions:" />
  <h:selectBooleanCheckbox id="termsId" value="#{playerBean.terms}" requiredMessage="You must accept terms and conditions!">
   <f:validator validatorId="omnifaces.RequiredCheckboxValidator" />
  </h:selectBooleanCheckbox>
  <h:commandButton value="Submit" action="#{playerBean.termsAction()}"/>               
 </h:panelGrid>           
 <h:message for="termsId" />           
</h:form> 

 Require the user to tick the desired checkbox (use HTML 5)

<h:form>                        
 <h:panelGrid columns="3">
  <h:outputLabel for="termsId" value="Tick terms and conditions:" />
  <h:selectBooleanCheckbox id="termsId" value="#{playerBean.terms}" pt:required="true" 
                           pt:x-moz-errormessage="You must accept terms and conditions!" title="You must accept terms and conditions!" />
  <h:commandButton value="Submit" action="#{playerBean.termsAction()}"/>               
 </h:panelGrid>           
 <h:message for="termsId" />           
</h:form>
For both cases, just add the field terms and method termsAction() in PlayerBean:

private boolean terms;

public boolean isTerms() {
 return terms;
}

public void setTerms(boolean terms) {
 this.terms = terms;
}  

public String termsAction(){
 return "data";
}

You can simply display the terms value in data.xhtml:

Terms: #{playerBean.terms}

Check on client side (via JS) if a checkbox is selected

<h:form id="formId">          
 Remember me:
 <h:selectBooleanCheckbox id="rememberId" value="#{playerBean.rememberme}"/>
 <h:commandButton value="Submit" action="data" onclick="isSelected();"/>
</h:form>
<script type="text/javascript">
 function isSelected() {
          alert($('#formId:rememberId'.replace(/:/g, "\\:")).is(':checked'));
 }
</script>

Complete source code on GitHub.
See also Mkyong.com

More resources on Constantin Alin, ZEEF page.
BooleanCheckbox in JSF Extension on JSF ShowCase ZEEF page.

JSF BOOKS COLLECTION

Postări populare

OmniFaces/JSF Fans

Follow by Email

Visitors Starting 4 September 2015

Locations of Site Visitors