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.

JSF BOOKS COLLECTION

Postări populare

OmniFaces/JSF Fans

Visitors Starting 4 September 2015

Locations of Site Visitors