reusable and less-verbose jsf code via omnifaces utilities api
TRANSCRIPT
Reusable and less-verbose JSF code via OmniFaces utilities API
Constantin Alin
To make JSF life easier
JSFOmniFaces utilities are for
OmniFaces utilities location
org.omnifaces.utilorg.omnifaces.utilorg.omnifaces.util
How many utilities are in OmniFaces
org.omnifaces.util
OmniFaces Showcase
OmniFaces is always up to date and is continuously getting better
OmniFaces is NOT only about 300+ utilitiesOmniFaces is a utility library for JSF and a comprehensive compendium ofprogramming techniques, design patterns and recipes for JSF developers.
What we will cover here ?
• Quick overview of OmniFaces utilities• Shortcuts to access the most used JSF artifacts• Less-verbose utilities methods• Advanced utilities methods
Quick overview of OmniFaces utilitiesor
g.om
nifa
ces.
util
Shortcuts
Advanced Less-verbose
ShortcutsQuick access to the most used JSF artifacts
Faces Context
FacesContext
FacesContext fc = Faces.getContext();
// FacesContext for an ELContextFacesContext fc = Faces.getContext(el_context);
FacesContext fc = FacesContext.getCurrentInstance();
// FacesContext for an ELContextFacesContext fc = (FacesContext) el_context.getContext(FacesContext.class);
External Context
ExternalContext
ExternalContext ec = Faces.getExternalContext();
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
EL Context
ELContext
ELContext el = Faces.getELContext();
ELContext el = FacesContext.getCurrentInstance().getELContext();
Partial View Context
PartialViewContext
PartialViewContext pvc = Ajax.getContext();
PartialViewContext pvc = FacesContext.getCurrentInstance().getPartialViewContext();
HTTP Servlet Request
HttpServletRequest
HttpServletRequest request = Faces.getRequest();
HttpServletRequest request = (HttpServletRequest) FacesContext. getCurrentInstance().getExternalContext().getRequest();
Less-verboseBoost the speed of development and obtain a less-verbose
and easy to maintain code
Less-verbose
Facelet Context
FaceletContext flc = Faces.getFaceletContext();
private static final String[] FACELET_CONTEXT_KEYS = { FaceletContext.FACELET_CONTEXT_KEY, "com.sun.faces.facelets.FACELET_CONTEXT", "javax.faces.FACELET_CONTEXT" };
// pass the FacesContextpublic static FaceletContext getFaceletContext(FacesContext context) { Map<Object, Object> contextAttributes = context.getAttributes(); for (String key : FACELET_CONTEXT_KEYS) { FaceletContext faceletContext = (FaceletContext) contextAttributes.get(key); if (faceletContext != null) { return faceletContext; } } return null;}
Include Composite Component
Less-verbose
Components.includeCompositeComponent(parent, "customs", "/welcome.xhtml", "welcomeMsgId", attributes);
public static UIComponent includeCompositeComponent(UIComponent parent, String libraryName, String tagName, String id, Map<String, String> attributes) { String taglibURI = "http://xmlns.jcp.org/jsf/composite/" + libraryName; Map<String, Object> attrs = (attributes == null) ? null : new HashMap<String, Object>(attributes);
FacesContext context = FacesContext.getCurrentInstance(); UIComponent composite = context.getApplication().getViewHandler() .getViewDeclarationLanguage(context, context.getViewRoot().getViewId()) .createComponent(context, taglibURI, tagName, attrs); composite.setId(id); parent.getChildren().add(composite); return composite;}
Add Script to Body
Less-verbose
UIComponent uicomp = Components.addScriptToBody(snippetOfJS);
public static UIComponent addScriptToBody(String script) { UIOutput outputScript = createScriptResource(); UIOutput content = new UIOutput(); content.setValue(script); outputScript.getChildren().add(content); return addComponentResource(outputScript, "body");}
public static final String RENDERER_TYPE_JS = "javax.faces.resource.Script";private static UIOutput createScriptResource() { UIOutput outputScript = new UIOutput(); outputScript.setRendererType(RENDERER_TYPE_JS); return outputScript;}
private static UIComponent addComponentResource(UIComponent resource, String target) { FacesContext context = FacesContext.getCurrentInstance(); context.getViewRoot().addComponentResource(context, resource, target); return resource;}
Get Metadata Attributes
Less-verbose
Map<String,Object> metattr = Faces.getMetadataAttributes("index.xhtml");
public static Map<String, Object> getMetadataAttributes(FacesContext context, String viewId) { ViewHandler viewHandler = context.getApplication().getViewHandler(); ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(context, viewId); ViewMetadata metadata = vdl.getViewMetadata(context, viewId);
return (metadata != null) ? metadata.createMetadataView(context).getAttributes() : Collections.<String, Object>emptyMap();}
Get FacesServlet Registration
Less-verbose
ServletRegistration sr = Platform.getFacesServletRegistration(request.getServletContext());
public static ServletRegistration getFacesServletRegistration(ServletContext servletContext) { ServletRegistration facesServletRegistration = null;
for (ServletRegistration registration : servletContext.getServletRegistrations().values()) { if (registration.getClassName().equals(FacesServlet.class.getName())) { facesServletRegistration = registration; break; } }
return facesServletRegistration;}
AdvancedSave time, nerves and hours of researching by using the OmniFaces
advanced and robust solutions
Create AJAX Behavior
Advanced
AjaxBehavior ajaxBehavior = Components.createAjaxBehavior("#{commandBean.save}");
public static AjaxBehavior createAjaxBehavior(String expression) { FacesContext context = FacesContext.getCurrentInstance(); AjaxBehavior behavior = (AjaxBehavior) context.getApplication().createBehavior(AjaxBehavior.BEHAVIOR_ID); final MethodExpression method = createVoidMethodExpression(expression, AjaxBehaviorEvent.class); behavior.addAjaxBehaviorListener(new AjaxBehaviorListener() { @Override public void processAjaxBehavior(AjaxBehaviorEvent event) throws AbortProcessingException { method.invoke(getELContext(), new Object[] { event }); } }); return behavior;}
public static MethodExpression createVoidMethodExpression(String expression, Class<?>... parameterTypes) { return createMethodExpression(expression, Void.class, parameterTypes);}
public static MethodExpression createMethodExpression(String expression, Class<?> returnType, Class<?>... parameterTypes) {
FacesContext context = FacesContext.getCurrentInstance(); return context.getApplication().getExpressionFactory().createMethodExpression( context.getELContext(), expression, returnType, parameterTypes);}
Has Invoked Submit
Advanced
boolean hasInvokedSubmit = Components.hasInvokedSubmit(foo_uicomp);
public static boolean hasInvokedSubmit(UIComponent component) { FacesContext context = FacesContext.getCurrentInstance();
if (!context.isPostback()) { return false; }
String clientId = stripIterationIndexFromClientId(component.getClientId(context)); Map<String, String> params = context.getExternalContext().getRequestParameterMap(); if (context.getPartialViewContext().isAjaxRequest()) { String source = params.get("javax.faces.source"); if (source != null) { return clientId.equals(stripIterationIndexFromClientId(source)); } }
if (component instanceof UICommand) { for (String name : params.keySet()) { if (name.startsWith("javax.faces.")) { continue; // Quick skip. } if (clientId.equals(stripIterationIndexFromClientId(name))) { return true; } } } return false;}
private static String stripIterationIndexFromClientId(String clientId) { String separatorChar = Character.toString(UINamingContainer.getSeparatorChar(getContext())); return clientId.replaceAll(quote(separatorChar) + "[0-9]+" + quote(separatorChar), separatorChar);}
Set Script Resource as Rendered
Advanced
Hacks.setScriptResourceRendered(context, new ResourceIdentifier(script_component));
public static void setScriptResourceRendered(FacesContext context, ResourceIdentifier id) { setMojarraResourceRendered(context, id); if (isMyFacesUsed()) { setMyFacesResourceRendered(context, MYFACES_RENDERED_SCRIPT_RESOURCES_KEY, id); }}
private static final String MYFACES_RENDERED_SCRIPT_RESOURCES_KEY ="org.apache.myfaces.RENDERED_SCRIPT_RESOURCES_SET";
private static void setMojarraResourceRendered(FacesContext context, ResourceIdentifier id) { context.getAttributes().put(id.getName() + id.getLibrary(), true);}
private static void setMyFacesResourceRendered(FacesContext context, String key, ResourceIdentifier id) { getMyFacesResourceMap(context, key).put(getMyFacesResourceKey(id), true);}
private static Map<String, Boolean> getMyFacesResourceMap(FacesContext context, String key) { Map<String, Boolean> map = getContextAttribute(context, key); if (map == null) { map = new HashMap<>(); setContextAttribute(context, key, map); } return map;}
private static String getMyFacesResourceKey(ResourceIdentifier id) { String library = id.getLibrary(); String name = id.getName(); return (library != null) ? (library + '/' + name) : name;}
Is MyFaces Used
Advanced
boolean isMyFacesAround = Hacks.isMyFacesUsed();
private static final String MYFACES_PACKAGE_PREFIX = "org.apache.myfaces.";public static boolean isMyFacesUsed() { if (myFacesUsed == null) { FacesContext context = FacesContext.getCurrentInstance();
if (context != null) { myFacesUsed = context.getClass().getPackage().
getName().startsWith(MYFACES_PACKAGE_PREFIX); } else {
return false; } } return myFacesUsed;}
Build View
Advanced
UIViewRoot anotherView = Components.buildView("foo.xhtml");
public static UIViewRoot buildView(String viewId) throws IOException { FacesContext context = FacesContext.getCurrentInstance(); String normalizedViewId = normalizeViewId(context, viewId); ViewHandler viewHandler = context.getApplication().getViewHandler(); UIViewRoot view = viewHandler.createView(context, normalizedViewId); FacesContext temporaryContext = new TemporaryViewFacesContext(context, view);
try { setContext(temporaryContext); viewHandler.getViewDeclarationLanguage(temporaryContext, normalizedViewId).buildView(temporaryContext, view); } finally { setContext(context); } return view;}
private static class TemporaryViewFacesContext extends FacesContextWrapper { …}
Resources
http://omnifaces-fans.org/
Source Code
http://balusc.omnifaces.org/ http://arjan-tijms.omnifaces.org/
Resources
Thank you!