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

luni, 18 ianuarie 2016

Misunderstanding the JSF lifecycle phases with the listen events types

A mistake is to not associate/interpret correctly the JSF lifecycle phases with the listen events types; you have to know which events takes place in which JSF phase. Per example, the below component registers itself as a listener for the PreValidateViewEvent event, and by default to the PostRestoreStateEvent event:

@FacesComponent(value = TomComponent.COMPONENT_TYPE, createTag = true)
public class TomComponent extends UIComponentBase
 implements ComponentSystemEventListener {

 public static final String COMPONENT_FAMILY =
  "jsf.uicomponentwithsubscribetoevent";
 public static final String COMPONENT_TYPE =  
  "uicomponentwithsubscribetoevent.TomComponent";

 @PostConstruct
 public void tomSubscribeToEvent() {
  subscribeToEvent(PreValidateEvent.class, this);
 }

 @Override
 public void processEvent(ComponentSystemEvent event)
                          throws AbortProcessingException {
  System.out.println("EVENT EMITTED: " + event);
 }

 @Override
 public void encodeEnd(FacesContext context) throws IOException {
  ResponseWriter responseWriter = context.getResponseWriter();
  responseWriter.write("I'm Tom the cat!");
 }

 @Override
 public String getFamily() {
  return COMPONENT_FAMILY;
 }
}

Well, at initial request JSF executes only the Restore View (there is nothing to restore now) and RenderResponse phases, which means that the TomComponent doesn't emit any of PreValidateViewEvent and PostRestoreStateEvent events. Actually, at initial request TomComponent subscribes to PostRestoreStateEvent and PreValidateViewEvent - component system event listeners are by default saved in JSF state and thus inherently view scoped. If you didn't know that, then you may think that the application is not working correctly. At postbacks instead, the Restore View (which restore the component tree now) and the Process Validations phase are executed, so both events are emitted and the output will be like this:

EVENT EMITTED: javax.faces.event.PostRestoreStateEvent
[source=uicomponentwithsubscribetoevent.TomComponent]
EVENT EMITTED: javax.faces.event.PreValidateEvent
source=uicomponentwithsubscribetoevent.TomComponent]

Obviously, the PostRestoreStateEvent first!

If you need a request scoped listener you may want to check the OmniFaces, Events#subscribeToRequestComponentEvent(), which subscribes the given callback instance to the given component that get invoked only in the current request when the given component system event type is published on the given component.

vineri, 15 ianuarie 2016

JSF 2.2 [usage pitfall] - Dependency injection wasn't done when the flow is in the bean constructor

The @PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This rule is sometimes "omitted" by novices who need to perform initialization stuff based on the injected artifacts. For example, let's suppose that we have the following session scoped CDI bean:

@Named
@SessionScoped
public class Buzz implements Serializable {
   
 private static final long serialVersionUID = 1L;
 private String buzz = "BUZZ!";

 // getter and setter for buzz
}

An instance of this bean is further injected into another session bean, and it will serve for some initialization stuff. Now, the wrong approach will consist in placing the initialization stuff in the bean constructor, instead of using a separate method annotated with @PostConstruct as below:

@Named
@SessionScoped
public class Foo implements Serializable {

 private static final Logger LOG = Logger.getLogger(Foo.class.getName());
 private static final long serialVersionUID = 1L;

 @Inject
 private Buzz buzz;

 // WRONG - buzz is not available yet!
 public Foo() {
  LOG.log(Level.INFO, "Foo() - The injected buzz is: {0}", buzz);
 }

 // CORRECT - dependency injection was done, so buzz is available!
 @PostConstruct
 private void init() {
  LOG.log(Level.INFO, "init() - The injected buzz is: {0}", buzz);
 }

 // CORRECT - just some bean method action
 public void fooAction() {
  LOG.log(Level.INFO, "fooAction() - The injected buzz is: {0}", buzz);
 }
}

The output will reveal (check out the constructor null output):

Foo() - The injected buzz is: null
init() - The injected buzz is: beans.Buzz@5b9370d8
fooAction() - The injected buzz is: beans.Buzz@5b9370d8

Since Buzz is session scoped the init() method is called only once per session. Using a request scoped bean will cause the initialization to take place at each request.

Open the targeted view in a new browser tab

Here it is a set of examples for opening the targeted view in a new browser tab:

·         for <h:link/>, <h:commandLink/> and <h:outputLink/> use the target="_blank":

<h:link value="Click me (h:link)!" outcome="result" target="_blank"/>

<h:outputLink value="http://showcase.omnifaces.org/whatsnew" target="_blank">Click me (h:outputLink)!</h:outputLink>

<h:form>
 <h:commandLink value="Click me (h:commandLink)!" action="result" target="_blank"/>
 <h:commandLink value="Click me (h:commandLink with redirect)!" action="result?faces-redirect=true" target="_blank"/>
 <h:commandLink value="Click me (h:commandLink with action method)!" action="#{resultBean.navigate()}" target="_blank"/>
 <h:commandLink value="Click me (h:commandLink with action method and redirect)!" 
                action="#{resultBean.navigateWithRedirect()}" target="_blank"/>
</h:form>

·         for <h:button/> use the window.open():

<h:button value="Click me (h:button)!" onclick="window.open('faces/result.xhtml');"/>

·         for <h:commandButton/> use the pass-through attribute, formtarget:

Add namespace: xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"

<h:form>
 <h:commandButton value="Click me (h:commandButton)!" action="result" pt:formtarget="_blank"/>
 <h:commandButton value="Click me (h:commandButton with redirect)!" action="result?faces-redirect=true" pt:formtarget="_blank"/>
 <h:commandButton value="Click me (h:commandButton with action method)!" action="#{resultBean.navigate()}" pt:formtarget="_blank"/>
 <h:commandButton value="Click me (h:commandButton with 
                  action method and redirect)!" action="#{resultBean.navigateWithRedirect()}" pt:formtarget="_blank"/>
</h:form>

Check the complete application here.

miercuri, 13 ianuarie 2016

JSF 2.2 [usage pitfall] - Prevent unintuitive behavior of nested tag files

Consider the following custom tag structure:

<my:tag id="foo" name="fooName">
 The id, <strong>#{id}</strong>, belongs to, <strong>#{name}</strong>
 <my:tag>
  The id, <strong>#{id}</strong>, belongs to, <strong>#{name}</strong>
 </my:tag>
</my:tag>

Check out the nested <my:tag>! Even if we don't specify the values of the id and name attributes, this tag has inherited them from the attributes of the parent tag with the same name. So, you will see:

The id, foo, belongs to, fooName
The id, foo, belongs to, fooName

While you may expected to see:

The id, foo, belongs to, fooName
The id,, belongs to,

Moreover, the problem doesn't manifest only when you nest very same tag file. But the problem applies as good on nesting completely different tags. For example:

<my:foo>
 <my:bar>
  <my:baz>

The issue of nested custom tags consist in the fact that the unspecified attributes will inherit the values from the attributes of their parents with the same name, instead of defaulting to null (empty string).

When this behavior represents an issue ( a big step consist in identifying the issue) you have to find an workaround to avoid it. Of course, the simplest approach consist in explicitly set the attributes values, but this is not always needed or convenient.

A professional workaround consist in using the OmniFaces TagAttribute. This allows us to explicitly declare a tag attribute on a Facelets tag file and avoid the presented issue. The attribute indicated via this tag handler will not inherit its value from the homologous attribute of the parent tag with the same name. Instead of this default behavior, the TagAttribute will clear out the attribute value and will support a default value for it. For page authors, the TagAttribute is available via the <o:tagAttribute> tag and configurable via two attributes:

·         name - This attribute is required and it represents the declared attribute name.
·         default - This attribute is optional and it represents the default value of the declared attribute.

This takes effect only when the declared attribute actual value is null.

<html xmlns=...>
 <ui:composition>
  <o:tagAttribute name="id" />
  <o:tagAttribute name="name" default="buzzName" />
  <div>
   <ui:insert />
  </div>
 </ui:composition>
</html>
Now, when the id and name are not present in the nested tag, we will see:

The id, foo, belongs to, fooName
The id,, belongs to, buzzName

If we don't indicate a default value for the name attribute then we will see:

The id, foo, belongs to, fooName

The id,, belongs to,

marți, 5 ianuarie 2016

JSF 2.2 [usage pitfall] - Counting the children of a composite component

Suppose that you have a composite component that accepts children via the <cc:insertChildren/> tag. Sometimes you may need to render a certain message when the list of children is empty, and for this you may think of writing a composite component implementation, as shown in the following code:

<!-- IMPLEMENTATION -->
<cc:implementation>
 <div id="#{cc.clientId}">
  <ul>
   <cc:insertChildren/>
   <h:panelGroup rendered="#{cc.childCount == 0}">
    The list of names is empty!
   </h:panelGroup>
  </ul>
 </div>
</cc:implementation>

Now if the composite component is used as follows, you may think that the message The list of names is empty! will be rendered:

<t:iccc/>

Well, you are right! But, the same message, next to the list content, will be rendered when the component is used as follows:

<t:iccc>
 <li>Mike</li>
 <li>Andrew</li>
</t:iccc>

In order to solve this issue, you can use the following code:

<cc:implementation>
 <div id="#{cc.clientId}">
  <ul>
   <cc:insertChildren/>
    <c:if test="#{cc.childCount == 0}">
     The list of names is empty!
    </c:if>
  </ul>
 </div>
</cc:implementation>

duminică, 3 ianuarie 2016

JSF 2.2 [usage pitfall] - Resource library meaning

As you probably know, JSF supports dedicated tags for loading resources, such as <h:outputStylesheet> for CSS resources, <h:outputScript> for JavaScript resources and <h:graphicImage> for images. These tags support an attribute named, library. The official documentation is pretty skimped about what the value of this attribute should be: The library name for this resource. Since this is all we have, there are plenty of examples like below:

<h:outputStylesheet library="css" name="style.css" />
<h:outputScript library="js" name="script.js" />
<h:graphicImage library="img" name="image.png" />

Now, the above snippet can be re-written as:

<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/image.png" />

Both approaches will generate almost the same HTML code. In the first approach, the library name will be rendered as a request parameter, ln=library_name, while in the second approach, the library name will be embed in the resource path as, ...javax.faces.resource/library_name/...
 So, if the generated HTML is almost the same, and in the first approach the library value simply repeats what the tag name already indicates, then how is library useful ?

We can answer to this question by checking some real world examples:

<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />

Notice that the library value represents the common library/module/theme name where all of those resources commonly belong to. This is the correct usage that brings us several advantages:

·         Distinguish where those resources belong to and/or are coming from.
·         In custom ResourceHandlers, you can also apply more finer grained control over resources.
·         You can apply resource library versioning the right way on resources provided by your own webapp

Each of these advantages are detailed by Bauke Scholtz (aka BalusC) at What is the JSF resource library for and how should it be used?.

So, as a conclusion, if your application doesn't need a library then just omit it (e.g. some personal applications). Nevertheless, if you decide to use a library name, but you don't have a clear purpose, then a name as default or common, or your company name may be a good choice.

sâmbătă, 2 ianuarie 2016

[OmniFaces utilities (2.3)] Fire the given CDI event, optionally with the given qualifiers


[OmniFaces utilities] The fireEvent() fires the given CDI event, optionally with the given qualifiers.

Method:
See also: Beans#getManager()
Usages:

In Java EE the observers are marked with the @Observes annotation. The addition of the @Observes annotation to the method signature instructs the container that this method should act as an observer of events of the type it precedes. Check out the below example:

@Named
@Dependent
public class ViningsFireStationBean {

 public void updateSmallFire(@Observes String arg) {
  System.out.println("Vinings fire department will go to a small fire at " + arg);
 }

 public void updateBigFire(@Observes String arg) {
  System.out.println("Vinings fire department will go to a big fire at " + arg);
 }       
}

Now, a CDI managed bean can fire an event that will be observed by ViningsFireStationBean like this:

@Named
@RequestScoped
public class MainFireStationBean {

 @Inject
 Event<String> evt;

 public void fireStarted(String address) {
  evt.fire(address);
 }
}

The above case is pretty classical. Now, if we choose to use the OmniFaces Beans#fireEvent() then we can re-write the MainFireStationBean as below:

import org.omnifaces.util.Beans;
...
@Named
@RequestScoped
public class MainFireStationBean {

 public void fireStarted(String address) {
  Beans.fireEvent(address);
 }
}

But, let's suppose that we need to differentiate between the same object types of objects and set up different observers to listen for them. For example, we may need to distinguish between small fires and big fires. Depending on this aspect, a local fire station may send to the fire address one fire truck or multiple fire trucks. We can model this case via a qualifier:

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface FireType {

 Type value();

 enum Type {
      SMALL, BIG
 }
}

The two enum types (SMALL and BIG)  will be used to act as annotation to mark the strings to be fired by the event instances. So, the MainFireStationBean will be:

@Named
@RequestScoped
public class MainFireStationBean {

 @Inject
 @FireType(Type.SMALL)
 Event<String> small;

 @Inject
 @FireType(Type.BIG)
 Event<String> big;

 public void fireStarted(String address, boolean t) {
  if (t) {
      small.fire(address);
  } else {
      big.fire(address);
  }
 }
}

Finally, add the annotations to the observer part:

@Named
@Dependent
public class ViningsFireStationBean {

 public void updateSmallFire(@Observes @FireType(FireType.Type.SMALL) String arg) {
  System.out.println("Vinings fire department will go to a small fire at " + arg);
 }

 public void updateBigFire(@Observes @FireType(FireType.Type.BIG) String arg) {
  System.out.println("Vinings fire department will go to a big fire at " + arg);
 }
}

In order to re-write this case to take advantage of OmniFaces Beans#fireEvent(), we need to need to declare an abstract qualifier that extends AnnotationLiteral and implements FireType:

public class FireTypeQualifier extends AnnotationLiteral<FireType> implements FireType {

 private final Type type;

 public FireTypeQualifier(Type t) {
  this.type = t;
 }

 @Override
 public Type value() {
  return type;
 }
}

And the MainFireStationBean become:

import org.omnifaces.util.Beans;
...
@Named
@RequestScoped
public class MainFireStationBean {

 public void fireStarted(String address, boolean t) {
  if (t) {
      Beans.fireEvent(address, new FireTypeQualifier(Type.BIG));
  } else {
      Beans.fireEvent(address, new FireTypeQualifier(Type.SMALL));
  }
 }
}

miercuri, 30 decembrie 2015

JSF 2.2 [usage pitfall] - Exemplifying <c:if/> versus <ui:fragment/>

JSF novices use to confuse the JSF tag handlers with JSF component handlers. Basically, tag handlers will not reach the component tree and, as a consequence of this aspect, will not produce any markup (HTML markup). More details about tag handlers are available in Write a custom TagHandler skeleton. In addition, more details about component handlers are available in Writing a custom ComponentHandler skeleton.

A common scenario is to render a table data based on a <c:if> condition, as follows:

<h:dataTable value="#{playersBean.dataArrayList}" var="t">
 <h:column>
  <c:if test="#{t.age gt 26}">
   <h:outputText value="#{t.player}, #{t.age}"/>
  </c:if>
 </h:column>
</h:dataTable>

Well, the result will not be as expected. The problem is that <c:if> is a tag handler; therefore, it is efficiently reflected when the tree is built. A perfect workaround will be to replace <c:if> with the <ui:fragment> tag, which is a component handler. The rendered attribute of <ui:fragment> can successfully replace the <c:if> test using the following code:

<h:dataTable value="#{playersBean.dataArrayList}" var="t">
 <h:column>
  <ui:fragment rendered="#{t.age gt 26}">
   <h:outputText value="#{t.player}, #{t.age}"/>
  </ui:fragment>
 </h:column>
</h:dataTable>

Alternatively, in an even simpler way, use the rendered attribute of <h:outputText>; this approach is particular to this example:

<h:dataTable value="#{playersBean.dataArrayList}" var="t">
 <h:column>
  <h:outputText value="#{t.player}, #{t.age}" rendered="#{t.age gt 26}"/>
 </h:column>
</h:dataTable>

Instead, even cooler, using a lambda expression (EL 3.0), you can write the following code:

<h:dataTable value="#{(playersBean.dataArrayList.stream().
                       filter((p)->p.age gt 26 )).toList()}" var="t">
 <h:column>
  <h:outputText value="#{t.player}, #{t.age}"/>
 </h:column>
</h:dataTable>

Is very possible that lambda expression can help you to easily choose when and what to render.

marți, 29 decembrie 2015

JSF 2.2 [usage pitfall] - the view scoped beans and the stateless feature

In a stateless environment, the view scoped beans act as request scoped beans. Besides the fact that you can't create/manipulate views dynamically, this is one of the big disadvantages that comes with the stateless feature, because it will affect AJAX-based applications that usually use view scoped beans. You can easily test this behavior with a set of beans with different scopes. The view scoped bean can be defined as follows:

@Named
@ViewScoped
public class TimestampVSBean implements Serializable{

 private static final long serialVersionUID = 1L;

 private Timestamp timestamp;

 public TimestampVSBean() {
  java.util.Date date = new java.util.Date();
  timestamp = new Timestamp(date.getTime());
 }

 public Timestamp getTimestamp() {
  return timestamp;
 }

 public void setTimestamp(Timestamp timestamp) {
 this.timestamp = timestamp;
 }
}

Just change the scope to request, session, and application to obtain the other three beans.
Next, we will write a simple stateless view as follows:

<f:view transient="true">
 <h:form>
  <h:commandButton value="Generate Timestamp"/>
 </h:form>

 Request Scoped Bean:
 <h:outputText value="#{timestampRSBean.timestamp}"/>

 View Scoped Bean:
 <h:outputText value="#{timestampVSBean.timestamp}"/>
 [keep an eye on this in stateless mode]

 Session Scoped Bean:
 <h:outputText value="#{timestampSSBean.timestamp}"/>

 Application Scoped Bean:
 <h:outputText value="#{timestampASBean.timestamp}"/>
</f:view>

Afterwards, just submit this form several times (click on the Generate Timestamp button) and notice that the timestamp generated by the view scoped bean changes at every request. This is a JSF pitfall!

The request, session, and application scopes work as expected!

JSF BOOKS COLLECTION

Postări populare

Visitors Starting 4 September 2015

Locations of Site Visitors