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

miercuri, 29 aprilie 2015

[OmniFaces utilities (2.0)] Check if the current request is a PrimeFaces dynamic resource request


[OmniFaces utilities] The isPrimeFacesDynamicResourceRequest() method returns true if the current request is a PrimeFaces dynamic resource request.

Method:
Usage:

boolean is = Hacks.isPrimeFacesDynamicResourceRequest(FacesContext.getCurrentInstance());
if(is){
   // is
} else {
   //is not
}

For example, PrimeFaces generates dynamic resource requests when we try to load images from StreamedContent via <p:graphicImage>. Such request may look like in figure below:

If you write a custom resource handler, it will be useful to distinguish such cases.

[OmniFaces utilities (2.0)] Get the default resource maximum age in milliseconds


[OmniFaces utilities] The getDefaultResourceMaxAge() method returns the default resource maximum age in milliseconds.

Method:
Usage:

import org.omnifaces.util.Hacks;
...
// e.g. 604800000 milliseconds
long maxAge = Hacks.getDefaultResourceMaxAge();

OmniFaces uses this method to set the Expires response header in org.omnifaces.resourcehandler.DynamicResource:

@Override
public Map<String, String> getResponseHeaders() {
 Map<String, String> responseHeaders = new HashMap<>(RESPONSE_HEADERS_SIZE);
 responseHeaders.put("Last-Modified", formatRFC1123(new Date(getLastModified())));
 responseHeaders.put("Expires", formatRFC1123(new Date(System.currentTimeMillis() + Hacks.getDefaultResourceMaxAge())));
 responseHeaders.put("Etag", String.format("W/\"%d-%d\"", getResourceName().hashCode(), getLastModified()));
 responseHeaders.put("Pragma", ""); // Explicitly set empty pragma to prevent some containers from setting it.
 return responseHeaders;
}

[OmniFaces utilities (2.0)] Remove the resource dependency processing related attributes


[OmniFaces utilities] The removeResourceDependencyState() method remove the resource dependency processing related attributes from the given faces context.

Method:
Usage:

import org.omnifaces.util.Hacks;
...
Hacks.removeResourceDependencyState(FacesContext.getCurrentInstance());

In Mojarra, the com.sun.faces.PROCESSED_RESOURCE_DEPENDENCIES is declared in RequestStateManager#PROCESSED_RESOURCE_DEPENDENCIES, and it is used to determine of the specified @ResourceDependency has already been previously processed:

// Mojarra 2.2.9 - com.sun.faces.application.annotation.ResourceDependencyHandler
private ResourceDependency[] dependencies;
...
@SuppressWarnings({"unchecked"})
private boolean hasBeenProcessed(FacesContext ctx, ResourceDependency dep) {
 Set<ResourceDependency> dependencies = (Set<ResourceDependency>)
  RequestStateManager.get(ctx, RequestStateManager.PROCESSED_RESOURCE_DEPENDENCIES);
 return ((dependencies != null) && dependencies.contains(dep));
}

And, to indicate that the specified @ResourceDependency  has been processed:

// Mojarra 2.2.9 - com.sun.faces.application.annotation.ResourceDependencyHandler
private ResourceDependency[] dependencies;
...
@SuppressWarnings({"unchecked"})
private void markProcssed(FacesContext ctx, ResourceDependency dep) {
 Set<ResourceDependency> dependencies = (Set<ResourceDependency>)
  RequestStateManager.get(ctx, RequestStateManager.PROCESSED_RESOURCE_DEPENDENCIES);
 if (dependencies == null) {
     dependencies = new HashSet<ResourceDependency>(6);
     RequestStateManager.set(ctx, RequestStateManager.PROCESSED_RESOURCE_DEPENDENCIES, dependencies);
 }
 dependencies.add(dep);
}

marți, 28 aprilie 2015

OmniFaces is used in ZEEF.com architecture

Arjan Tijms has been interviewed by Adam Bien about the architecture of ZEEF.com. Among others, Arjan Tijms "reveals" the fact that OmniFaces is one of the external dependencies used in ZEEF.com.

Read further here ...

[OmniFaces utilities (2.0)] Stream the given input to the given output by NIO ByteBuffer


[OmniFaces utilities] The stream() method stream the given input to the given output by NIO ByteBuffer. Both the input and output streams will implicitly be closed after streaming, regardless of whether an exception is been thrown or not.

Method:
Usage:

Suppose we have a file as an input stream and we want to pass it to an output stream for further processing. For this, we can use the Utils#stream() method:

import java.io.InputStream;
import java.io.OutputStream;
import org.omnifaces.util.Utils;
...
InputStream inputStream;
OutputStream outputStream;
try {
    inputStream = new FileInputStream("input_file");
    outputStream = new FileOutputStream("output_file");

    long length = Utils.stream(inputStream, outputStream);
} catch (IOException ex) {
   //
}

By default, the Utils#stream() method returns the length of the written bytes.

[OmniFaces utilities (2.0)] Check if the given class has at least one of the given annotations


[OmniFaces utilities] The isOneAnnotationPresent() method returns true if the given class has at least one of the given annotations.

Method:
Usage:

Check if the specified class is a JSF/CDI managed bean:

import org.omnifaces.util.Utils;
import javax.inject.Named;
import javax.faces.bean.ManagedBean;
...
Class[] annotations = new Class[]{Named.class, ManagedBean.class};
boolean isAnyAnnotations = Utils.isOneAnnotationPresent(MyClass.class, annotations);

Check if the specified class is a scoped/session/application CDI managed bean:

import org.omnifaces.util.Utils;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
...
Class[] annotations = new Class[]{RequestScoped.class, SessionScoped.class, ApplicationScoped.class};
boolean isAnyAnnotations = Utils.isOneAnnotationPresent(MyCDIBean.class, annotations);

luni, 27 aprilie 2015

[OmniFaces utilities (2.0)] Check if the given class instance could also be an instance of one of the given classes


[OmniFaces utilities] The isOneInstanceOf() method returns true if an instance of a class could also be an instance of one of the given classes.

Method:
Usage:

UIComponent currentComponent = Components.getCurrentComponent();
       
// check if the current component is an UICommand
boolean isCommand = Utils.isOneInstanceOf(currentComponent.getClass(), HtmlCommandButton.class, HtmlCommandLink.class);

[OmniFaces utilities (2.0)] Check if the given string starts with one of the given prefixes


[OmniFaces utilities] The startsWithOneOf() method returns true if the given string starts with one of the given prefixes.

Method:
Usage:

import org.omnifaces.util.Utils;
...
String[] listenersPrefixNames = {"Action", "AjaxBehavior", "Behavior", "ComponentSystemEvent", "ViewMap", "SystemEvent", "ValueChange"};
// returns true
boolean startsWithOneOf = Utils.startsWithOneOf("ComponentSystemEvent", listenersPrefixNames);
// returns false
boolean startsWithOneOf = Utils.startsWithOneOf("Phase", listenersPrefixNames);

[OmniFaces utilities (2.0)] Check if the given object equals one of the given objects


[OmniFaces utilities] The isOneOf() method returns true if the given object equals one of the given objects.

Method:
Usage:

The current submitted form has ID, loginFormId. Now, let's see some tests for Utils#isOneOf():

UIViewRoot viewRoot = Faces.getViewRoot();

UIComponent someForm= viewRoot.findComponent("loginFormId");
UIForm currentForm = Components.getCurrentForm();
UICommand currentCommand = Components.getCurrentCommand();
UIForm closestForm = Components.getClosestParent(currentCommand, UIForm.class);       
UIComponent currentComponent = Components.getCurrentComponent();
       
boolean  isSomeFormCurrentForm = Utils.isOneOf(someForm, currentForm); // true
boolean  isSomeFormClosestForm = Utils.isOneOf(someForm, closestForm); // true
boolean  isSomeFormCurrentFormOrClosestForm = Utils.isOneOf(someForm, currentForm, closestForm); // true
boolean  isSomeFormCurrentCommandOrCurrentComponent = Utils.isOneOf(someForm, currentCommand, currentComponent); // false


[OmniFaces utilities (2.0)] Get the first non-null object of the argument list, or null if there is no such element


[OmniFaces utilities] The coalesce() method returns the first non-null object of the argument list, or null if there is no such element.

Method:
Usage:

import org.omnifaces.util.Utils;
...
Object object = null;
StringBuilder sb = null;
BigDecimal ten = BigDecimal.TEN;

// returns BigDecimal.TEN, 10
Object notNull = Utils.coalesce(object, sb, ten);

[OmniFaces utilities (2.0)] Check if the given string is parseable as a number/decimal


[OmniFaces utilities] The isNumber() method returns true if the given string is parseable as a number. I.e. it is not null, nor blank and contains solely digits. I.e., it won't throw a NumberFormatException when parsing as Long.
[OmniFaces utilities] The isDecimal() method returns true if the given string is parseable as a decimal. I.e. it is not null, nor blank and contains solely digits. I.e., it won't throw a NumberFormatException when parsing as Double.

Method Utils#isNumber():

 Method Utils#isDecimal():
Usage:

import org.omnifaces.util.Utils;
...
String a = "";
String b = "3";
String c = "3L";
String d = "3.14";
String e = "3.14f";
String f = "3.14d";

// a
boolean isANumber = Utils.isNumber(a);   // false
boolean isADecimal = Utils.isDecimal(a); // false
// b
boolean isBNumber = Utils.isNumber(b);   // true
boolean isBDecimal = Utils.isDecimal(b); // true
// c
boolean isCNumber = Utils.isNumber(c);   // false
boolean isCDecimal = Utils.isDecimal(c); // false
// d
boolean isDNumber = Utils.isNumber(d);   // false
boolean isDDecimal = Utils.isDecimal(d); // true
// e
boolean isENumber = Utils.isNumber(e);   // false
boolean isEDecimal = Utils.isDecimal(e); // true
// f
boolean isFNumber = Utils.isNumber(f);   // false
boolean isFDecimal = Utils.isDecimal(f); // true

[OmniFaces utilities (2.0)] Check if the given string is null or is empty or contains whitespace only


[OmniFaces utilities] The isBlank() method returns true if the given string is null or is empty or contains whitespace only. In addition to #isEmpty(String), this thus also returns true when string.trim().isEmpty() returns true.

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

import org.omnifaces.util.Utils;
...
String a = null;
String b="";
String c="   ";
String d="text";

boolean isABlank = Utils.isBlank(a);  // true
boolean isBBlank = Utils.isBlank(b);  // true
boolean isCBlank = Utils.isBlank(c);  // true
boolean isDBlank = Utils.isBlank(d);  // false

duminică, 26 aprilie 2015

[OmniFaces utilities (2.0)] Check if a String, Collection, Map or Array is empty


[OmniFaces utilities] The isEmpty() method returns true if the given value is null or is empty. Types of String, Collection, Map and Array are recognized. If none is recognized, then examine the emptiness of the toString() representation instead.

Methods:

This method uses the below ones (which can be invoked individually):
Usage:

Testing a String:

String aString = null;
String bString = "";
String cString = "Done!";

import org.omnifaces.util.Utils;
...   
boolean a = Utils.isEmpty(aString);  // true
boolean b = Utils.isEmpty(bString);  // true
boolean c = Utils.isEmpty(cString);  // false

Testing an Object[]:

Object[] aObjectArray = null;
Object[] bObjectArray = new Object[1];
Object[] cObjectArray = {1};

boolean a = Utils.isEmpty(aObjectArray);  // true
boolean b = Utils.isEmpty(bObjectArray);  // false
boolean c = Utils.isEmpty(cObjectArray);  // false

Testing a List:

List aList = null;
List bList = new ArrayList();
List<String> cList = new ArrayList<>();
ArrayList<String> dList = new ArrayList<String>() {
            {
                add("A");
                add("B");
                add("C");
            }
        };

 boolean a = Utils.isEmpty(aList);  // true
 boolean b = Utils.isEmpty(bList);  // true
 boolean c = Utils.isEmpty(cList);  // true
 boolean d = Utils.isEmpty(dList);  // false

Testing a Map:

Map aMap = null;
Map bMap = new HashMap();
Map<String, String> cMap = new HashMap<>();  
Map<Byte, Integer> dMap = new HashMap<Byte, Integer>() {
            {
                put(new Byte("1"), 1);
                put(new Byte("2"), 2);
            };
        };

 boolean a = Utils.isEmpty(aMap);  // true
 boolean b = Utils.isEmpty(bMap);  // true
 boolean c = Utils.isEmpty(cMap);  // true
 boolean d = Utils.isEmpty(dMap);  // false

vineri, 24 aprilie 2015

[OmniFaces utilities (2.0)] Check whether the given script resource is rendered


[OmniFaces utilities] The isScriptResourceRendered() method returns whether the given script resource is rendered.

Method:

Usage:

See also: Set the given script/stylesheet resource asrendered

FacesContext context = ...;
boolean isScriptRendered = Hacks.isScriptResourceRendered(context, new ResourceIdentifier(script_component))
if(isScriptRendered){
   // is
} else {
   //is not
}

Note The OmniFaces org.omnifaces.resourcehandler.ResourceIdentifier is a convenience class to represent a resource identifier (maps resource name and library).

[OmniFaces utilities (2.0)] Set the given script/stylesheet resource as rendered


[OmniFaces utilities] The setScriptResourceRendered() method set the given script resource as rendered.
[OmniFaces utilities] The setStylesheetResourceRendered() method set the given stylesheet resource as rendered.

Method (for script):

Method (for stylesheet):

Usage:

When we need to add any component (resource instance) as a resource in the view, we can use UIViewRoot#addComponentResource(). By any component (resource instance) we understand a resource instance which is rendered by a resource Renderer, as described in the Standard HTML RenderKit. For example, if you move a <script> component at the end of the <body>, you will probably do this:

UIViewRoot view = context.getViewRoot();
view.addComponentResource(context, script_component, "body");

Further, you may need to mark this resource as rendered. You have to instruct JSF that the script resource is already rendered, otherwise JSF will force the auto-inclusion/rendering of the script resource. As BalusC points out, "in case of Mojarra and MyFaces, a context attribute with key of name+library and a value of true has to be set in order to disable auto-inclusion of the resource". Well, in Mojarra you can easy see these words in code lines in com.sun.faces.renderkit.html_basic.ScriptRenderer class, in encodeEnd() method (similar we have for stylesheets resources in StylesheetRenderer). The relevant part is listed below:

@Override
public void encodeEnd(FacesContext context, UIComponent component)
                                                        throws IOException {
 ...
 Map<Object, Object> contextMap = context.getAttributes();
 ...
 String name = (String) attributes.get("name");
 String library = (String) attributes.get("library");
 String key = name + library;
 ...
 // Ensure this script/stylesheet is not rendered more than once per request
 if (contextMap.containsKey(key)) {
     return;
 }
 contextMap.put(key, Boolean.TRUE);
 ...
}

Since there's no standard JSF API for doing this, OmniFaces accomplished this task (for scripts) via Hacks#setScriptResourceRendered():

FacesContext context = ...;
Hacks.setScriptResourceRendered(context, new ResourceIdentifier(script_component));

And, for stylesheets via Hacks#setStylesheetResourceRendered():


FacesContext context = ...;
Hacks.setStylesheetResourceRendered(context, new ResourceIdentifier(stylesheet_component));

Note The OmniFaces org.omnifaces.resourcehandler.ResourceIdentifier is a convenience class to represent a resource identifier (maps resource name and library).
Note OmniFaces uses this method in DeferredScript and CombinedResourceHandler.

JSF BOOKS COLLECTION

Postări populare

OmniFaces/JSF Fans

Visitors Starting 4 September 2015

Locations of Site Visitors