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

sâmbătă, 28 februarie 2015

[OmniFaces utilities (2.1/2.0)] Subscribe to view system events using serializable/un-serializable Callbacks


[OmniFaces utilities] The subscribeToViewEvent() methods subscribes the given callback (serializable (in 2.1) /un-serializable (in 2.0) void without arguments/void with one argument) to the current view that get invoked every time when the given system event type is published on the current view.

Method:

- using OmniFaces 2.1 serializable callback

- using OmniFaces 2.0 un-serializable callback

Note By OmniFaces implementation, the listened emitter of system events is the UIViewRoot, so use only system events types that can be emitted by the component tree's view root. OmniFaces relies on its org.omnifaces.eventlistener.DefaultViewEventListenerlisted below:

public abstract class DefaultViewEventListener implements SystemEventListener {
 @Override
 public void processEvent(SystemEvent event) throws AbortProcessingException {
  // NOOP
 }

 @Override
 public boolean isListenerForSource(Object source) {
  return source instanceof UIViewRoot;
 }
}

Usage:

Before calling the Events#subscribeToViewEvent() methods, let's have a quick overview of how this methods works. As the post title said, this method allows to subscribe the given callback to the current view that get invoked every time when the given system event type is published on the current view. So, we pass to this method the system event type to be observed, and one of the following OmniFaces Callbacks (this becomes the listener):

- using OmniFaces 2.1 serializable callback
- using OmniFaces 2.0 un-serializable callback


Basically, all we need to do is to subscribe to the desired event(s) with a Callback instance and implement a behavior to the corresponding invoke() method. Behind the scene, OmniFaces takes the provided Callback and creates a custom system event listener for it. When the specified event(s) occurs, OmniFaces will call our invoke() implementation. Knowing this, we can create a simple example:

JSF Page:

<h:form>
 <o:outputLabel for="tomId" value="Tom Enemy:"/>
 <h:inputText id="tomId" value="#{tomBean.enemy}"/>
 <h:commandButton value="Get Advice"/>
</h:form>
<h:outputText rendered="#{facesContext.postback}" value="#{tomBean.advice}"/>

TomBean

import org.omnifaces.util.Callback;
import static org.omnifaces.util.Events.subscribeToViewEvent;
...
@Named
@RequestScoped
public class TomBean {

 private String enemy;
 private String advice;

 @PostConstruct
 public void adviceForTom() {
       
  //the enemy value is not available in @PostConstruct, but we can
  //subscribe with a callback to PreRenderViewEvent, when the enemy is available


  //OmniFaces 2.1
  // serializable void Callback
  subscribeToViewEvent(PreRenderViewEvent.class, new Callback.SerializableVoid() {

   private static final long serialVersionUID = 1L;

   @Override
   public void invoke() {
    if (enemy != null) {
        if (enemy.equals("jerry")) {
            advice = "Tom, watch the dog while you are chasing Jerry!";
        } else if (enemy.equals("dog")) {
            advice = "Tom, be careful to Jerry traps!";
        } else {
            advice = "Tom, you have a new enemy ?!!";
        }
    }
   }
  });

  //OmniFaces 2.0
  // un-serializable void Callback
  subscribeToViewEvent(PreRenderViewEvent.class, new Callback.Void() {
   @Override
   public void invoke() {
    if (enemy != null) {
        if (enemy.equals("jerry")) {
            advice = "Tom, watch the dog while you are chasing Jerry!";
        } else if (enemy.equals("dog")) {
            advice = "Tom, be careful to Jerry traps!";
        } else {
            advice = "Tom, you have a new enemy ?!!";
        }
    }
   }
  });

  //OmniFaces 2.1
  // serializable void Callback with argument
  subscribeToViewEvent(PreRenderViewEvent.class, new Callback.SerializableWithArgument<SystemEvent>() {

   private static final long serialVersionUID = 1L;

   @Override
   public void invoke(SystemEvent event) {
    if (enemy != null) {
        if (enemy.equals("jerry")) {
            advice = "Tom, watch the dog while you are chasing Jerry!";
        } else if (enemy.equals("dog")) {
            advice = "Tom, be careful to Jerry traps!";
        } else {
            advice = "Tom, you have a new enemy ?!!";
        }
    }
   }
  });
  
  //OmniFaces 2.0
  // un-serializable void Callback with argument
  subscribeToViewEvent(PreRenderViewEvent.class, new Callback.WithArgument<SystemEvent>() {  
   @Override
   public void invoke(SystemEvent event) {
    if (enemy != null) {
        if (enemy.equals("jerry")) {
            advice = "Tom, watch the dog while you are chasing Jerry!";
        } else if (enemy.equals("dog")) {
            advice = "Tom, be careful to Jerry traps!";
        } else {
            advice = "Tom, you have a new enemy ?!!";
        }
    }
   }
  });
  ...

When Tom submits the form and the application flow reaches in the @PostConstruct method, the enemy value was not set yet. But, we register a callback as a listener for the PreRenderViewEvent which means that right before the UIViewRoot is about to be rendered the invoke() method is called, and the enemy value is set and can be used to choose the right advice for Tom. Nice!


Complete code on GitHub

[JSF Page Author Beginner's Guide] JSF <inputHidden> / HTML5 <input> hidden

The <h:inputHidden> renders an HTML "input" element of "type" "hidden"
Common/basic usage in JSF (I):

<?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 inputHidden examples</title>        
 </h:head>
 <h:body>
  <h:form>
   Name: <h:inputText value="#{playerBean.name}"/>
   <h:inputHidden value="#{playerBean.age}"/>
   <h:commandButton value="Send" action="data"/>
  </h:form>
 </h:body>
</html>

The <h:inputHidden> will be rendered in HTML as:

<input type="hidden" name="j_idt6:j_idt9" value="0" />

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 String name = "Rafael Nadal";
 private String age = "0";

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAge() {       
  return age;
 }

 public void setAge(String age) {
  this.age = age;
 }
}

At initial request, the hidden value is initialized from bean with 0 (the default value of age field). The hidden value is not modified in page, so, at postback, the hidden value will still be 0.

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 -->           
  Name: <h:outputText value="#{playerBean.name}"/><br/>                             
  Age: <h:outputText value="#{playerBean.age}"/><br/>                              
 </h:body>
</html>

Data flow in image:
More examples:

Commonly, the above example is the "skeleton" behind one of the next two use cases.

Use case 1 - you may need a hidden value in page - in this case, you can "extract" it via a snippet of JavaScript, as below:

<!-- Get in JavaScript the value of a JSF hidden value -->         
<h:form id="formId1">
 Name: <h:inputText id="playerNameId1" value="#{playerBean.name}"/>
 <h:inputHidden id="playerAgeId1" value="#{playerBean.age}"/>
 <h:commandButton value="Send" action="data" onclick="getHiddenAge();"/>
</h:form>

When the Send button is clicked, before the form is submitted, the JavaScript getHiddenAge() method is invoked. This time, we just alert the hidden value, but you can use it to influence the submitted form values:

<script type="text/javascript">
 function getHiddenAge() {
  alert("The hidden age is: " + document.getElementById("formId1:playerAgeId1").value);
 }
</script>

Use case 2 - sometimes, you need to alter the hidden value based on some conditions -  for example, you can set the hidden value depending on player name. Again, a snippet of JavaScript will be helpful:

<!-- Pass to a bean a new hidden value using a JSF hidden field and a snippet of JavaScript -->        
<h:form id="formId2">
 Name: <h:inputText id="playerNameId2" value="#{playerBean.name}"/>
 <h:inputHidden id="playerAgeId2" value="#{playerBean.age}"/>
 <h:commandButton value="Send" action="data" onclick="setHiddenAge();"/>
</h:form>

The hidden value is initialized form bean with 0, but the setHiddenAge() method will modify its value before submitting the form, based on the player name:

<script type="text/javascript">
 function setHiddenAge() {
  var playername = document.getElementById("formId2:playerNameId2").value;
  if (playername === "David Ferrer") {
      document.getElementById("formId2:playerAgeId2").value = "32";
  } else if (playername === "Andy Murray") {
      document.getElementById("formId2:playerAgeId2").value = "27";
  } else {
      document.getElementById("formId2:playerAgeId2").value = "28";
  }
 }
</script>

Further, let's see a dummy case of using the <h:inputHidden>

Common/basic usage in JSF (II) - dummy usage (check this code):

<?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:pt="http://xmlns.jcp.org/jsf/passthrough"       
      xmlns:h="http://xmlns.jcp.org/jsf/html">
 <h:head>
  <title>JSF inputHidden examples</title>        
 </h:head>
 <h:body>
  <h:form id="formId3">
   Name: <h:inputText value="#{playerBean.name}"/>
   <h:inputHidden id="playerage3" value="28"/>
   <h:commandButton value="Send" action="#{playerBean.save1()}"/>
  </h:form>
 </h:body>
</html>

The <h:inputHidden> will be rendered in HTML as:

<input id="formId3:playerage3" type="hidden" name="formId3:playerage3" value="28" />

The PlayerBean will be:

package beans;

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

@Named
@SessionScoped
public class PlayerBean implements Serializable {

 private String name = "Rafael Nadal";
 private String age = "0";

 public String save1() {
  // extract the hidden value from request parameter map
  String playerage = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("formId3:playerage3");
  // print the extracted value
  System.out.println("Player age: " + playerage);
  // set the bean field, 'age', equal to the extracted value
  this.age = playerage;
  // navigate to 'data.xhtml' page
  return "data";
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAge() {
  return age;
 }

 public void setAge(String age) {
  this.age = age;
 }
}

In PlayerBean, we can easily extract the hidden value from the request parameter map - the JSF getRequestParameterMap() method returns the submitted request parameters as a Map of type parameter name = parameter value (the parameter name represents the component clientId generated by JSF (e.g. formId1:playerage1)). This map can be inspected in browser via specialized tools - for example, in Mozilla Firefox, the request parameter map will be (the hidden field was highlighted):
We need to use the getRequestParameterMap() method, because the hidden value was hard coded in page, it wasn't linked to a bean field via a ValueExpression. The hidden value is used to set the bean field, age, right inside the bean (manually in the save1() method). Further, the application navigates to another page, named, data.xhtml:

<?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 -->           
  Name: <h:outputText value="#{playerBean.name}"/><br/>                             
  Age: <h:outputText value="#{playerBean.age}"/><br/>  
 </h:body>
</html>

Data flow in image:
Note In the above example we have hard coded the hidden value. This is a pretty dummy usage, because we don't exploit the JSF component itself. Basically, in such cases, we can achieve the same thing by replacing the <h:inputHidden> with the HTML markup, as below:

<!-- Pass to a bean a new hidden value using the HTML markup instead of JSF hidden field -->        
<h:form id="formId4">
 Name: <h:inputText value="#{playerBean.name}"/>
 <input type="hidden" id="playerage4" name="playerage4" value="28" />
 <h:commandButton value="Send" action="#{playerBean.save2()}"/>
</h:form>

This time the save2() method has a slight, but important, modification. Since this is plain HTML, we don't have a clientId (JSF generates this for JSF components only, not for plain HTML elements), we simply use the ID, playerage4:

public String save2() {
 // extract the hidden value from request parameter map
 String playerage = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("playerage4");
 // print the extracted value
 System.out.println("Player age: " + playerage);
 // set the bean field, 'age', equal to the extracted value
 this.age = playerage;
 // navigate to 'data.xhtml' page
 return "data";
}

Complete source code on GitHub.
See also Mkyong.com.
More resources on Constantin Alin, ZEEF page.
InputHidden in JSF Extension on JSF ShowCase ZEEF page.

vineri, 27 februarie 2015

[OmniFaces utilities (2.1/2.0)] Subscribe to application system events using serializable/un-serializable Callbacks


[OmniFaces utilities] The subscribeToApplicationEvent() methods subscribes the given callback (serializable (in 2.1) /un-serializable (in 2.0) void without arguments/void with one argument) to the current application that get invoked every time when the given system event type is published in the current application.

Method:

- using OmniFaces 2.1 serializable callback

- using OmniFaces 2.0 un-serializable callback

Note By OmniFaces implementation, the listened emitter of system events is the UIViewRoot, so use only system events types that can be emitted by the component tree's view root. OmniFaces relies on its org.omnifaces.eventlistener.DefaultViewEventListenerlisted below:

public abstract class DefaultViewEventListener implements SystemEventListener {
 @Override
 public void processEvent(SystemEvent event) throws AbortProcessingException {
  // NOOP
 }

 @Override
 public boolean isListenerForSource(Object source) {
  return source instanceof UIViewRoot;
 }
}

Usage:

Before calling the Events#subscribeToApplicationEvent() methods, let's have a quick overview of how this methods works. As the post title said, this method allows to subscribe the given serializable (in 2.1)/un-serializable (in 2.0) callback to the current application that get invoked every time when the given system event type is published in the current application. So, we pass to this method the system event type to be observed, and one of the following OmniFaces Callbacks (this becomes the listener):

- using OmniFaces 2.1 serializable callback

- using OmniFaces 2.0 un-serializable callback

Basically, all we need to do is to subscribe to the desired event(s) with a Callback instance and implement a behavior to the corresponding invoke() method. Behind the scene, OmniFaces takes the provided Callback and creates a custom system event listener for it. When the specified event(s) occurs, OmniFaces will call our invoke() implementation. Knowing this, we can create a simple example. Let's suppose that we have a custom component that  needs to know when the view root was just added to the view. For this, the custom component can subscribe with a Callback to the PostAddToViewEvent event, as below:

import org.omnifaces.util.Callback;
import static org.omnifaces.util.Events.subscribeToApplicationEvent;
...
//OmniFaces 2.1
// serializable void Callback with argument
subscribeToApplicationEvent(PostAddToViewEvent.class, new Callback.SerializableWithArgument<SystemEvent>() {

 private static final long serialVersionUID = 1L;

 @Override
 public void invoke(SystemEvent event) {
  System.out.println("..: PostAddToViewEvent event emitted by UIViewRoot :.." + event.getSource());
  //do something ...
 }
});

//OmniFaces 2.0
// un-serializable void Callback with argument
subscribeToApplicationEvent(PostAddToViewEvent.class, new Callback.WithArgument<SystemEvent>() {
 @Override
 public void invoke(SystemEvent event) {
  System.out.println("..: PostAddToViewEvent event emitted by UIViewRoot :.." + event.getSource());
  //do something ...
 }
});

// OmniFaces 2.1
// serializable void Callback
subscribeToApplicationEvent(PostAddToViewEvent.class, new Callback.SerializableVoid() {
 @Override

 private static final long serialVersionUID = 1L;

 public void invoke() {
  System.out.println("..: PostAddToViewEvent event emitted by UIViewRoot :..");
  //do something ...
 }
});

// OmniFaces 2.0
// un-serializable void Callback
subscribeToApplicationEvent(PostAddToViewEvent.class, new Callback.Void() {
 @Override
 public void invoke() {
  System.out.println("..: PostAddToViewEvent event emitted by UIViewRoot :..");
  //do something ...
 }
});
...


Complete code on GitHub
API 2.1   GH 2.1

JSF BOOKS COLLECTION

Postări populare

OmniFaces/JSF Fans

Follow by Email

Visitors Starting 4 September 2015

Locations of Site Visitors