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

marți, 30 iunie 2015

[OmniFaces utilities 2.1] Programmatically EL-resolve the given property on the given base object and set the given value


[OmniFaces utilities] The resolveExpressionSet() method programmatically EL-resolve the given property on the given base object and set the given value.

Method:
See also: Faces#getContext()
Usage:

Let's suppose that we have the following simple bean:

@Named
@SessionScoped
public class CommandBean {

 private String command;
 private String process;

 public String getProcess() {
  return process;
 }

 public void setProcess(String process) {
  this.process = process;
 }       

 public String getCommand() {
  return command;
 }

 public void setCommand(String command) {
  this.command = command;
 }
}

Now, for an instance of CommandBean, we can set the command as /f /pid 8080 and the process as taskkill via the Faces#resolveExpressionSet():

CommandBean commandBean = new CommandBean();
Faces.resolveExpressionSet(commandBean, "command", "/f /pid 8080");
Faces.resolveExpressionSet(commandBean, "process", "taskkill");

We can easily perform a check via Faces#resolveExpressionGet():

// returns /f /pid 8080
String command = Faces.resolveExpressionGet(commandBean, "command");
// returns taskkill
String process = Faces.resolveExpressionGet(commandBean, "process");

[OmniFaces utilities 2.1] Programmatically EL-resolve the given property on the given base object and return the resolved value


[OmniFaces utilities] The resolveExpressionGet() method programmatically EL-resolve the given property on the given base object and return the resolved value.

Method:
See also: Faces#getContext()
Usage:

Let's suppose that we have the following simple CDI bean:

@Named
@SessionScoped
public class CommandBean {

 private String command;

 public String getCommand() {
  return command;
 }

 public void setCommand(String command) {
  this.command = command;
 }
}

Now, the Faces#resolveExpressionGet() is capable to programmatically EL-resolve the command property on the CommandBean base object and return the resolved value. In a real scenario, you will be in a JSF artifact (e.g. in a bean, custom component, etc), and you will need to inspect the property of an existing CommandBean object (instance). But, we can also perform a quick test via Beans#getInstance() utility method, which returns the CDI managed bean instance (actual) of the given bean class and creates one if one doesn't exist. Since the above bean is a CDI bean, we can do this:

// returns:
   - null, if the CommandBean object (instance) was created by the Beans#getInstance(), since one doesn't exist
   - if the CommandBean object (instance) exist, it will return the current value of the command property
CommandBean commandBean = Beans.getInstance(CommandBean.class);
String resolved = Faces.resolveExpressionGet(commandBean, "command");

You can resolve a top-level variable also, by passing null as base:

Object resolved = Faces.resolveExpressionGet(null, "top-level variable");

luni, 29 iunie 2015

[OmniFaces utilities 2.1] Get all application resource bundles registered as <resource-bundle> in faces-config.xml


[OmniFaces utilities] The getResourceBundles() method returns all application resource bundles registered as <resource-bundle> in faces-config.xml. If there are no resource bundles registered, then this method just returns an empty map.

Method:
Usage:

Let's suppose that we have a resource bundle with "short" messages and a resource bundle with "full" messages:

Is quite simple, just check the content of the msgs.ShortMessages:

English and French (msgs.ShortMessages_en.properties and msgs.ShortMessages_fr.properties):


English and French (msgs.FullMessages_en.properties and msgs.FullMessages_fr.properties):


Now, in faces-config.xml, we declare both resource bundles, as below (for the "short" messages we have attached the var named, short, and for the "full" messages, the var named, full):

<application>
 <locale-config>
  <default-locale>en</default-locale>
  <supported-locale>en</supported-locale>
  <supported-locale>fr</supported-locale>
 </locale-config>
 <resource-bundle>
  <base-name>msgs.ShortMessages</base-name>
  <var>short</var>
 </resource-bundle>
 <resource-bundle>
  <base-name>msgs.FullMessages</base-name>
  <var>full</var>
  </resource-bundle>
 </application>

Now, you can use both resource bundles in the application views by indicating the proper var. For example, a dummy usage is below:

<h:outputText value="#{short['NAME']}"/>
<h:outputText value="#{short['SURNAME']}"/>
<h:outputText value="#{full['NAME']}"/>
<h:outputText value="#{full['SURNAME']}"/>

Now, programmatically speaking, we can access these resource bundles via Faces#getResourceBundles(), as below:

Map<String, ResourceBundle> resourcebundles = Faces.getResourceBundles();
for (Map.Entry<String, ResourceBundle> entry : resourcebundles.entrySet()) {
     // entry.getKey() - this is the var name (short, full)
     // entry.getValue().getString("NAME")); - for short var
     // entry.getValue().getString("SURNAME")); - for full var
}

[OmniFaces utilities 2.0] Check if at least one value is empty


[OmniFaces utilities] The isAnyEmpty() method returns true if at least one value is empty.

Method:
See also: Utils#isEmpty()
Usage:

String one = "one";
String two = "two";
List<String> oneandtwolist = new ArrayList<>();
Map<String, String> oneandtwomap = new HashMap<>();
// true, the list and the map are empty       
boolean isanyempty = Utils.isAnyEmpty(one, two, oneandtwolist, oneandtwomap);

oneandtwolist.add(one);
oneandtwolist.add(two);
// true, the map is empty       
boolean isanyempty = Utils.isAnyEmpty(one, two, oneandtwolist, oneandtwomap);

oneandtwomap.put(one, one);
oneandtwomap.put(two, two);
// false, there is no empty values with respect to Utils#isEmpty()
boolean isanyempty = Utils.isAnyEmpty(one, two, oneandtwolist, oneandtwomap);

duminică, 28 iunie 2015

[OmniFaces utilities 2.2] Unmodifiable list with all child UIParameter components of the given parent component


THIS METHOD IS AVAILABLE IN 2.1, BUT IT IS RECOMMENDED TO USE OmniFaces 2.2 SNAPSHOT (FINAL) or higher!

Starting with version 2.2 - SNAPSHOT (FINAL) the
 Components#getParams() was fixed to take into account converter of ParamHolder.

[OmniFaces utilities] The getParams() method returns an unmodifiable list with all child UIParameter components (<f|o:param>) of the given parent component as a list of ParamHolder instances. Those with disabled=true and an empty name are skipped.

Method (left side uses org.omnifaces.component.SimpleParam from version 2.1, while right side uses SimpleParam from version 2.2):

Usage:

Before seeing an example of using the Components#getParams(), is important to inspect the above source code and to notice that it relies on org.omnifaces.component.ParamHolder and org.omnifaces.component.SimpleParam. The ParamHolder is a simple interface that extends standard ValueHolder in order to provide:

-          a method for obtaining the parameter name associated with the parameter value
-          a method to return the original, unconverted value of the parameter
-          a method to return the converted value of the parameter (especially needed for <o:param>)

package org.omnifaces.component;

import javax.faces.application.Application;
import javax.faces.component.ValueHolder;
import javax.faces.convert.Converter;

import org.omnifaces.util.Faces;

public interface ParamHolder extends ValueHolder {

 // returns the name of the parameter
 public String getName();

 // returns the original, unconverted value of the parameter
 @Override
 public Object getLocalValue();

 // returns the converted value of the parameter
 @Override
 public Object getValue();
}

The SimpleParam provides a basic and default implementation of the ParamHolder interface. Ultimately, this class can be used as a simple key-value pair holder (parameter name-value) which uses an explicit/implicit JSF converter to convert the object value to string.

Now, let's suppose that we have the following simple form (notice that, for variety, the #{param['age']} is just a request parameters passed in the URL query string as ?age=24):

<h:form id="form">
 <h:commandButton id="submit" value="Send" action="#{myBean.sendAction()}">
  <f:param name="age" value="#{param['age']}"/>
  <f:param name="name" value="#{myBean.name}"/>
  <o:param name="address" value="#{myBean.address}" converter="addressConverter"/>
 </h:commandButton>
</h:form>

Further, we can use the Components#getParams() utility to programmatically collect the UIParameters  (<f|o:param>) nested in the above <h:commandButton/>. This can be accomplish in different JSF artifacts; for example, in a bean (obviously, there are several ways to identify the parent UIComponent of the UIParameters that we want to collect - the UIComponent that should be passed to the #getParams() should be obtained in a convenient manner depending on your circumstances; below, we simply used the Components#findComponent() utility):

UIComponent uc = Components.findComponent("form:submit"); // see: Components#findComponent()
List<ParamHolder> params = Components.getParams(uc);

for (ParamHolder ph : params) {
    // the getName() will return the parameter name

    // starting with version 2.2 
    // getLocalValue() returns the unconverted value
       // getValue() returns the converted value (passed through getAsString())    
}

Note Don't worry about <o:param> with attached converter, OmniFaces 2.2 takes care of it. 

API 2.1 GH 2.1

By Anghel Leonard and Constantin Alin

Spread of "JSF and OmniFaces Fans" blog visitors for 3 month

Spread of "OmniFaces and JSF Fans" blog visitors for 3 month:



sâmbătă, 27 iunie 2015

[OmniFaces utilities 2.0] Create an ajax behavior which should invoke an ajax listener method expression based on the given EL expression


[OmniFaces utilities] The createAjaxBehavior() method creates an ajax behavior which should invoke an ajax listener method expression based on the given EL expression. The target method must take an AjaxBehaviorEvent as argument. Note that this is essentially the programmatic equivalent of <f:ajax>. So if you intented to create for example a <p:ajax> programmatically, then don't use this method. Check also the UIComponentBase#addClientBehavior(String, ClientBehavior) whereby the string argument represents the client event name, such as action, valueChange, click, blur, etc.

Method:
Usage:

Let's suppose that we have the following simple form:

<h:form>
 ...
 <h:commandButton value="Save"/>
</h:form> 

Further, we want to programmatically add an AJAX behavior (like <f:ajax/>) to the above button, and for this we can write a tag handler that exploits the Components#createAjaxBehavior(). Below is listed only the apply() method (notice the pointed listener, #{commandBean.save}):

@Override
public void apply(FaceletContext ctx, UIComponent parent) throws IOException {

 // avoid the following code to be executed multiple time in the same request
 if (!ComponentHandler.isNew(parent)) { 
     return;
 }

 // obviously, if the parent is not a ClientBehaviorHolder then is not capable to deal with an AJAX behavior
 if (!(parent instanceof ClientBehaviorHolder)) {
     return;
 }

 AjaxBehavior ajaxBehavior = Components.createAjaxBehavior("#{commandBean.save}");
 ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder) parent;
 clientBehaviorHolder.addClientBehavior("action", ajaxBehavior);       
}

Or, in order to avoid the risk of adding twice the same AJAX behavior:

AjaxBehavior ajaxBehavior = Components.createAjaxBehavior("#{commandBean.save}");
ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder) parent;
List<ClientBehavior> behaviors = clientBehaviorHolder.getClientBehaviors().get("action");
// Guard against adding ourselves twice
if (behaviors == null || !behaviors.contains(ajaxBehavior)) {
    clientBehaviorHolder.addClientBehavior("action", ajaxBehavior);
}

Further, the form will become:

<h:form>
 <h:outputScript name="jsf.js" library="javax.faces" target="head"/>           
 <h:commandButton value="Save"> 
  <t:simpleAjax/>
 </h:commandButton>
</h:form>

Notice that we have explicitly added the jsf.js resource. By default, when JSF finds an AJAX behavior in the current view it will "install" this resource automatically (e.g. in Mojarra, via com.sun.faces.facelets.tag.jsf.core.AjaxHandler#installAjaxResourceIfNecessary()). But, notice that this is true from AJAX behavior explicitly defined in view, not programmatically. Depending on context, the jsf.js can be added via @ResourceDependency (not the case here, but when it is use: @ResourceDependency(library="javax.faces", name="jsf.js", target="head")), or via <h:outputScript>). Of course, you can have a helper method also (maybe inspired from Mojarra source code).

Finally, the listener (#{commandBean.save}) is defined in CommandBean, as:

public void save(AjaxBehaviorEvent evt) {
 LOG.log(Level.INFO, "---------------------Saving---------------------- / {0}", evt);
}

Note If you need to go deeper and understand how Components#createAjaxBehavior()is implemented, then you can check the com.sun.faces.facelets.tag.jsf.core.AjaxHandler methods, especially, AjaxHandler#applyAttachedObject()and AjaxHandler#createAjaxBehavior().

The complete code of this example is on GitHub.

vineri, 26 iunie 2015

[OmniFaces utilities 2.0] Get the UI component matching the given client ID search expression


[OmniFaces utilities] The findComponent() method returns the UI component matching the given client ID search expression.

Method:
Usage:

import org.omnifaces.util.Components;
...
UIComponent uiComponent = Components.findComponent("clientId");

joi, 25 iunie 2015

[OmniFaces utilities 2.1] Subscribe the given callback instance to the given component (request scoped event listener) and unsubscribe the given event listener on the given event from the given component


[OmniFaces utilities] The subscribeToRequestComponentEvent() method 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. The difference with UIComponent#subscribeToEvent(Class, ComponentSystemEventListener) is that this listener is request scoped instead of view scoped as component system event listeners are by default saved in JSF state and thus inherently view scoped.

[OmniFaces utilities] The unsubscribeFromComponentEvent() method unsubscribes the given event listener on the given event from the given component. Normally, you would use UIComponent#unsubscribeFromEvent(Class, ComponentSystemEventListener) for this, but this wouldn't work when executed inside ComponentSystemEventListener#processEvent(javax.faces.event.ComponentSystemEvent), as it would otherwise end up in a ConcurrentModificationException while JSF is iterating over all system event listeners. The trick is to perform the unsubscribe during the after phase of the current request phase #subscribeToRequestAfterPhase(PhaseId, org.omnifaces.util.Callback.Void).

Methods:

- subscribe the given callback instance to the given component (request scoped event listener)

- unsubscribe the given event listener on the given event from the given component


See also: Events#subscribeToRequestAfterPhase
Note: If the flow is in Render Response phase then there is too late to unsubscribe.

Usage:

Let's suppose that we are in the apply() method of a tag handler and we want to listen (via a callback) the PostValidateEvent emitted by the parent component, without saving this component system event listener in the JSF state. We can easily accomplish this via Events#subscribeToRequestComponentEvent():

@Override
public void apply(FaceletContext context, final UIComponent parent) throws IOException {
 ...
 subscribeToRequestComponentEvent(parent, PostValidateEvent.class, new Callback.WithArgument<ComponentSystemEvent>() {
  @Override
  public void invoke(ComponentSystemEvent event) {
   processTheEvent(event);
  }
 });
}

protected void processTheEvent (ComponentSystemEvent event) {
 UIComponent component = event.getComponent();
 // do something here
 ...
}

Or, maybe you need to use the UIComponent#subscribeToEvent(Class, ComponentSystemEventListener) as below:

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

 public static final String COMPONENT_FAMILY = "...";
 public static final String COMPONENT_TYPE = "...";

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

 @Override
 public void processEvent(ComponentSystemEvent event) throws AbortProcessingException {
  // do something here
 }
 ...
}

Now, in order to unsubscribe from the PreValidateEvent and avoid saving in JSF state this component system event listener, you can explicitly invoke the Events#unsubscribeFromComponentEvent(), as below:

@Override
 public void processEvent(ComponentSystemEvent event) throws AbortProcessingException {
  Events.unsubscribeFromComponentEvent(event.getComponent(), event.getClass(), this);
  // do something here
 }


SlideShare - OmniFaces Converters

Check out the OmniFaces Converters presentation on SlideShare


Check also the following presentations:
Introduction to OmniFaces
OmniFaces Validators

miercuri, 24 iunie 2015

[OmniFaces utilities 2.1] List of OmniFaces 2.1 serializable Callback interfaces


[OmniFaces utilities] The Callback represents a collection of serializable callback interfaces. Useful in (mini) visitor and strategy patterns.

In case you don't know, OmniFaces 2.0 comes with a set of un-serializable callback interfaces useful in (mini) visitor and strategy patterns.
OmniFaces 2.0 also supports a callback which takes two arguments, but this was removed in OmniFaces 2.1. For the rest of Callbacks, OmniFaces 2.1 provides a Serializable version. But, if you need the un-Serializable version then simply rely on OmniFaces 2.0.

Let's see what we have in OmniFaces 2.1 beside OmniFaces 2.0:

·         serializable void callback
·         serializable callback which returns a value
·         serializable callback which takes an argument

·        serializable callback which takes one argument and returns one value


Check out the blog Callback submenu to see several examples of using these interfaces to:

[OmniFaces utilities 2.0] List of OmniFaces 2.0 un-serializable Callback interfaces


[OmniFaces utilities] The Callback represents a collection of un-serializable callback interfaces. Useful in (mini) visitor and strategy patterns.

In case you don't know, OmniFaces 2.0 comes with a set of un-serializable callback interfaces useful in (mini) visitor and strategy patterns. These interfaces are available in the final class org.omnifaces.util.Callback.
Starting with OmniFaces 2.1 the callback which takes two arguments was removed. For the rest of Callbacks listed below, OmniFaces 2.1 provides a Serializable version. 

Let's see what we have in OmniFaces 2.0:

·         void callback
·         callback which returns a value

·         callback which takes an argument

·         callback which takes two arguments (removed in OmniFaces 2.1)


·         callback which takes one argument and returns one value

JSF BOOKS COLLECTION

Postări populare

OmniFaces/JSF Fans

Follow by Email

Visitors Starting 4 September 2015

Locations of Site Visitors