Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
License Agreement. Rich Faces - Natural Ajax for Java Server Faces (JSF) Copyright (C) 2007 Exadel, Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
 package org.richfaces.renderkit.util;
 
 import java.util.Map;
 
 import  javax.faces.application.FacesMessage;
 import  javax.faces.application.ViewHandler;
 import  javax.faces.component.NamingContainer;
 import  javax.faces.component.UIComponent;
 import  javax.faces.component.UIForm;
 import  javax.faces.component.UIParameter;
 import  javax.faces.component.UIViewRoot;
 import  javax.faces.component.behavior.ClientBehaviorContext.Parameter;
 import  javax.faces.component.behavior.ClientBehaviorHolder;
 import  javax.faces.context.FacesContext;
 import  javax.faces.context.ResponseWriter;
 
 import  org.ajax4jsf.Messages;
 import  org.ajax4jsf.component.JavaScriptParameter;
 import  org.ajax4jsf.javascript.JSReference;
 import  org.richfaces.renderkit.HtmlConstants;
Util class for common render operations - render passthru html attributes, iterate over child components etc.

Author(s):
asmirnov@exadel.com (latest modification by $Author: alexsmirnov $)
Version:
$Revision: 1.1.2.6 $ $Date: 2007/02/08 19:07:16 $
 
 public final class RendererUtils {
     public static final String DUMMY_FORM_ID = ":_form";
     // we'd better use this instance multithreadly quickly
     private static final RendererUtils INSTANCE = new RendererUtils();
    
Substitutions for components properies names and HTML attributes names.
 
     private static final Map<StringStringSUBSTITUTIONS = new HashMap<StringString>();
 
     static {
         .put(HtmlConstants.CLASS_ATTRIBUTE, "styleClass");
 
         Arrays.sort(HtmlConstants.PASS_THRU);
         Arrays.sort(HtmlConstants.PASS_THRU_EVENTS);
         Arrays.sort(HtmlConstants.PASS_THRU_BOOLEAN);
         Arrays.sort(HtmlConstants.PASS_THRU_URI);
     }
 
     // can be created by subclasses;
     // administratively restricted to be created by package members ;)
     protected RendererUtils() {
         super();
     }

    
Use this method to get singleton instance of RendererUtils

Returns:
singleton instance
 
     public static RendererUtils getInstance() {
         return ;
     }

    
Encode id attribute with clientId component property

Parameters:
context
component
Throws:
IOException
 
     public void encodeId(FacesContext context, UIComponent componentthrows IOException {
         encodeId(contextcomponent, HtmlConstants.ID_ATTRIBUTE);
    }

    
Encode clientId to custom attribute ( for example, to control name )

Parameters:
context
component
attribute
Throws:
IOException
    public void encodeId(FacesContext context, UIComponent componentString attributethrows IOException {
        String clientId = null;
        try {
            clientId = component.getClientId(context);
        } catch (Exception e) {
            // just ignore if clientId wasn't inited yet
        }
        if (null != clientId) {
            context.getResponseWriter().writeAttribute(attributeclientId, (StringgetComponentAttributeName(attribute));
        }
    }

    
Encode id attribute with clientId component property. Encoded only if id not auto generated.

Parameters:
context
component
Throws:
IOException
    public void encodeCustomId(FacesContext context, UIComponent componentthrows IOException {
        if (hasExplicitId(component)) {
            context.getResponseWriter().writeAttribute(HtmlConstants.ID_ATTRIBUTE, component.getClientId(context),
                HtmlConstants.ID_ATTRIBUTE);
        }
    }

    
Returns value of the parameter. If parameter is instance of JavaScriptParameter, NoEcape attribute is applied.

Parameters:
parameter instance of UIParameter
Returns:
Object parameter value
    public Object createParameterValue(UIParameter parameter) {
        Object value = parameter.getValue();
        boolean escape = true;
        if (parameter instanceof JavaScriptParameter) {
            JavaScriptParameter actionParam = (JavaScriptParameter) parameter;
            escape = !actionParam.isNoEscape();
        }
        if (escape) {
            if (value == null) {
                value = "";
            }
        } else {
            value = new JSReference(value.toString());
        }
        return value;
    }
    public Map<StringObjectcreateParametersMap(FacesContext context, UIComponent component) {
        Map<StringObjectparameters = new LinkedHashMap<StringObject>();
        if (component.getChildCount() > 0) {
            for (UIComponent child : component.getChildren()) {
                if (child instanceof UIParameter) {
                    UIParameter parameter = (UIParameter) child;
                    String name = parameter.getName();
                    Object value = createParameterValue(parameter);
                    if (null == name) {
                        throw new IllegalArgumentException(Messages.getMessage(Messages.UNNAMED_PARAMETER_ERROR,
                            component.getClientId(context)));
                    }
                    parameters.put(namevalue);
                }
            }
        }
        return parameters;
    }
    private void encodeBehaviors(FacesContext context, ClientBehaviorHolder behaviorHolderString defaultHtmlEventName,
        String[] attributesExclusionsthrows IOException {
        // if (attributesExclusions != null && attributesExclusions.length != 0) {
        // assert false : "Not supported yet";
        // }
        // TODO: disabled component check
        String defaultEventName = behaviorHolder.getDefaultEventName();
        Collection<StringeventNames = behaviorHolder.getEventNames();
        if (eventNames != null) {
            UIComponent component = (UIComponent) behaviorHolder;
            ResponseWriter writer = context.getResponseWriter();
            Collection<Parameter> parametersList = HandlersChain.createParametersList(createParametersMap(contextcomponent));
            for (String behaviorEventName : eventNames) {
                if (behaviorEventName.equals(defaultEventName)) {
                    continue;
                }
                String htmlEventName = "on" + behaviorEventName;
                if ((attributesExclusions == null) || (Arrays.binarySearch(attributesExclusionshtmlEventName) < 0)) {
                    HandlersChain handlersChain = new HandlersChain(contextcomponentparametersList);
                    handlersChain.addInlineHandlerFromAttribute(htmlEventName);
                    handlersChain.addBehaviors(behaviorEventName);
                    String handlerScript = handlersChain.toScript();
                    if (!isEmpty(handlerScript)) {
                        writer.writeAttribute(htmlEventNamehandlerScripthtmlEventName);
                    }
                }
            }
        }
    }

    
Encode common pass-thru html attributes.

Parameters:
context
component
Throws:
IOException
    public void encodePassThru(FacesContext context, UIComponent componentString defaultHtmlEventthrows IOException {
        encodeAttributesFromArray(contextcomponent, HtmlConstants.PASS_THRU);
        if (component instanceof ClientBehaviorHolder) {
            ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder) component;
            encodeBehaviors(contextclientBehaviorHolderdefaultHtmlEventnull);
        } else {
            encodeAttributesFromArray(contextcomponent, HtmlConstants.PASS_THRU_EVENTS);
        }
    }

    
Encode pass-through attributes except specified ones

Parameters:
context
component
exclusions
Throws:
IOException
    public void encodePassThruWithExclusions(FacesContext context, UIComponent componentString exclusions,
        String defaultHtmlEventthrows IOException {
        if (null != exclusions) {
            String[] exclusionsArray = exclusions.split(",");
            encodePassThruWithExclusionsArray(contextcomponentexclusionsArraydefaultHtmlEvent);
        }
    }
    public void encodePassThruWithExclusionsArray(FacesContext context, UIComponent componentString[] exclusions,
        String defaultHtmlEventthrows IOException {
        ResponseWriter writer = context.getResponseWriter();
        Map<StringObjectattributes = component.getAttributes();
        Arrays.sort(exclusions);
        for (int i = 0; i < HtmlConstants.PASS_THRU.length; i++) {
            String attribute = HtmlConstants.PASS_THRU[i];
            if (Arrays.binarySearch(exclusionsattribute) < 0) {
                encodePassThruAttribute(contextattributeswriterattribute);
            }
        }
        if (component instanceof ClientBehaviorHolder) {
            ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder) component;
            encodeBehaviors(contextclientBehaviorHolderdefaultHtmlEventexclusions);
        } else {
            for (int i = 0; i < HtmlConstants.PASS_THRU_EVENTS.length; i++) {
                String attribute = HtmlConstants.PASS_THRU_EVENTS[i];
                if (Arrays.binarySearch(exclusionsattribute) < 0) {
                    encodePassThruAttribute(contextattributeswriterattribute);
                }
            }
        }
    }

    
Encode one pass-thru attribute, with plain/boolean/url value, got from properly component attribute.

Parameters:
context
writer
attribute
Throws:
IOException
    public void encodePassThruAttribute(FacesContext contextMap<StringObjectattributes, ResponseWriter writer,
        String attributethrows IOException {
        Object value = attributeValue(attributeattributes.get(getComponentAttributeName(attribute)));
        if ((null != value) && RenderKitUtils.shouldRenderAttribute(value)) {
            if (Arrays.binarySearch(HtmlConstants.PASS_THRU_URI, attribute) >= 0) {
                String url = context.getApplication().getViewHandler().getResourceURL(contextvalue.toString());
                url = context.getExternalContext().encodeResourceURL(url);
                writer.writeURIAttribute(attributeurlattribute);
            } else {
                writer.writeAttribute(attributevalueattribute);
            }
        }
    }
    public void encodeAttributesFromArray(FacesContext context, UIComponent componentString[] attrsthrows IOException {
        ResponseWriter writer = context.getResponseWriter();
        Map<StringObjectattributes = component.getAttributes();
        for (int i = 0; i < attrs.lengthi++) {
            String attribute = attrs[i];
            encodePassThruAttribute(contextattributeswriterattribute);
        }
    }

    
Encode attributes given by comma-separated string list.

Parameters:
context current JSF context
component for with render attributes values
attrs comma separated list of attributes
Throws:
IOException
    public void encodeAttributes(FacesContext context, UIComponent componentString attrsthrows IOException {
        if (null != attrs) {
            String[] attrsArray = attrs.split(",");
            encodeAttributesFromArray(contextcomponentattrsArray);
        }
    }

    

Parameters:
context
component
property
attributeName
Throws:
IOException
    public void encodeAttribute(FacesContext context, UIComponent componentObject propertyString attributeName)
        throws IOException {
        ResponseWriter writer = context.getResponseWriter();
        Object value = component.getAttributes().get(property);
        if (RenderKitUtils.shouldRenderAttribute(value)) {
            writer.writeAttribute(attributeNamevalueproperty.toString());
        }
    }
    public void encodeAttribute(FacesContext context, UIComponent componentString attributethrows IOException {
        encodeAttribute(contextcomponentgetComponentAttributeName(attribute), attribute);
    }

    
Checks if the argument passed in is empty or not. Object is empty if it is:
- null
- zero-length string
- empty collection
- empty map
- zero-length array

Parameters:
o object to check for emptiness
Returns:
true if the argument is empty, false otherwise
Since:
3.3.2
    public boolean isEmpty(Object o) {
        if (null == o) {
            return true;
        }
        if (o instanceof String) {
            return 0 == ((Stringo).length();
        }
        if (o instanceof Collection<?>) {
            return ((Collection<?>) o).isEmpty();
        }
        if (o instanceof Map<?, ?>) {
            return ((Map<?, ?>) o).isEmpty();
        }
        if (o.getClass().isArray()) {
            return Array.getLength(o) == 0;
        }
        return false;
    }

    
Convert HTML attribute name to component property name.

Parameters:
key
Returns:
    protected Object getComponentAttributeName(Object key) {
        Object converted = .get(key);
        if (null == converted) {
            return key;
        } else {
            return converted;
        }
    }

    
Convert attribute value to proper object. For known html boolean attributes return name for true value, otherthise - null. For non-boolean attributes return same value.

Parameters:
name attribute name.
value
Returns:
    protected Object attributeValue(String nameObject value) {
        if (null == value || Arrays.binarySearch(HtmlConstants.PASS_THRU_BOOLEAN, name) < 0) {
            return value;
        }
        boolean checked;
        if (value instanceof Boolean) {
            checked = ((Booleanvalue).booleanValue();
        } else {
            checked = Boolean.parseBoolean(value.toString());
        }
        return checked ? name : null;
    }

    
Get boolean value of logical attribute

Parameters:
component
name attribute name
Returns:
true if attribute is equals Boolean.TRUE or String "true" , false otherwise.
    public boolean isBooleanAttribute(UIComponent componentString name) {
        Object attrValue = component.getAttributes().get(name);
        boolean result = false;
        if (null != attrValue) {
            if (attrValue instanceof String) {
                result = "true".equalsIgnoreCase((StringattrValue);
            } else {
                result = ..equals(attrValue);
            }
        }
        return result;
    }
    public String encodePx(String value) {
        return HtmlDimensions.formatPx(HtmlDimensions.decode(value));
    }

    
formats given value to

Parameters:
value
Returns:
    public String encodePctOrPx(String value) {
        if (value.indexOf('%') > 0) {
            return value;
        } else {
            return encodePx(value);
        }
    }

    
Find nested form for given component Deprecated: use getNestingForm(UIComponent) instead

Parameters:
component
Returns:
nested UIForm component, or null
    public UIComponent getNestingForm(UIComponent component) {
        return getNestingForm(nullcomponent);
    }

    
Find nested form for given component

Parameters:
component
Returns:
nested UIForm component, or null
    @Deprecated
    public UIComponent getNestingForm(FacesContext context, UIComponent component) {
        UIComponent parent = component;
        // Search enclosed UIForm or ADF UIXForm component
        while ((parent != null) && !(parent instanceof UIForm)
                && !("org.apache.myfaces.trinidad.Form".equals(parent.getFamily()))
                && !("oracle.adf.Form".equals(parent.getFamily()))) {
            parent = parent.getParent();
        }
        return parent;
    }

    
Find submitted form for given context

Parameters:
facesContext
Returns:
submitted UIForm component, or null
    public UIComponent getSubmittedForm(FacesContext facesContext) {
        if (!facesContext.isPostback()) {
            return null;
        }
        for (Entry<StringStringentry : facesContext.getExternalContext().getRequestParameterMap().entrySet()) {
            final String name = entry.getKey();
            final String value = entry.getValue();
            // form's name equals to its value
            if (isFormValueSubmitted(namevalue)) {
                // in that case, name is equal to clientId
                UIComponent component = findComponentFor(facesContext.getViewRoot(), name);
                UIComponent form = getNestingForm(component);
                return form;
            }
        }
        facesContext.addMessage(nullnew FacesMessage("The form wasn't detected for the request",
                "The form wasn't detected for the request - rendering does not have to behave well"));
        return null;
    }

    
Determines whenever given form has been submitted
    public boolean isFormSubmitted(FacesContext context, UIForm form) {
        if (form != null) {
            String clientId = form.getClientId(context);
            String formRequestParam = context.getExternalContext().getRequestParameterMap().get(clientId);
            return isFormValueSubmitted(clientIdformRequestParam);
        }
        return false;
    }

    
Determines if a form was submitted based on its clientId (which equals to request parameter name) and submitted value

Returns:
true if clientId and value equals and they are not null; false otherwise
    private boolean isFormValueSubmitted(String clientIdString value) {
        if (clientId == null) {
            return false;
        }
        return clientId.equals(value);
    }

    

Parameters:
context
component
Returns:
Throws:
IOException
    public void encodeBeginFormIfNessesary(FacesContext context, UIComponent componentthrows IOException {
        UIComponent form = getNestingForm(contextcomponent);
        if (null == form) {
            ResponseWriter writer = context.getResponseWriter();
            String clientId = component.getClientId(context) + ;
            encodeBeginForm(contextcomponentwriterclientId);
            // writer.writeAttribute(HTML.STYLE_ATTRIBUTE, "margin:0;
            // padding:0;", null);
        }
    }

    

Parameters:
context
component
writer
clientId
Throws:
IOException
    public void encodeBeginForm(FacesContext context, UIComponent component, ResponseWriter writerString clientId)
        throws IOException {
        String actionURL = getActionUrl(context);
        String encodeActionURL = context.getExternalContext().encodeActionURL(actionURL);
        writer.startElement(HtmlConstants.FORM_ELEMENT, component);
        writer.writeAttribute(HtmlConstants.ID_ATTRIBUTE, clientIdnull);
        writer.writeAttribute(HtmlConstants.METHOD_ATTRIBUTE, "post"null);
        writer.writeAttribute(HtmlConstants.STYLE_ATTRIBUTE, "margin:0; padding:0; display: inline;"null);
        writer.writeURIAttribute(HtmlConstants.ACTION_ATTRIBUTE, encodeActionURL"action");
    }

    

Parameters:
context
component
Throws:
IOException
    public void encodeEndFormIfNessesary(FacesContext context, UIComponent componentthrows IOException {
        UIComponent form = getNestingForm(contextcomponent);
        if (null == form) {
            ResponseWriter writer = context.getResponseWriter();
            // TODO - hidden form parameters ?
            encodeEndForm(contextwriter);
        }
    }

    
Write state saving markers to context, include MyFaces view sequence.

Parameters:
context
Throws:
IOException
    public static void writeState(FacesContext contextthrows IOException {
        context.getApplication().getViewHandler().writeState(context);
    }

    

Parameters:
context
writer
Throws:
IOException
    public void encodeEndForm(FacesContext context, ResponseWriter writerthrows IOException {
        UIViewRoot viewRoot = context.getViewRoot();
        for (UIComponent resource : viewRoot.getComponentResources(context"form")) {
            resource.encodeAll(context);
        }
        writeState(context);
        writer.endElement(HtmlConstants.FORM_ELEMENT);
    }

    

Parameters:
facesContext
Returns:
String A String representing the action URL
    public String getActionUrl(FacesContext facesContext) {
        ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
        String viewId = facesContext.getViewRoot().getViewId();
        return viewHandler.getActionURL(facesContextviewId);
    }

    
Simplified version of encodeId

Parameters:
context
component
Returns:
client id of current component
    public String clientId(FacesContext context, UIComponent component) {
        String clientId = "";
        try {
            clientId = component.getClientId(context);
        } catch (Exception e) {
            // just ignore
        }
        return clientId;
    }

    
Wtrie JavaScript with start/end elements and type.

Parameters:
context
component
script
    public void writeScript(FacesContext context, UIComponent componentObject scriptthrows IOException {
        ResponseWriter writer = context.getResponseWriter();
        writer.startElement(HtmlConstants.SCRIPT_ELEM, component);
        writer.writeAttribute(HtmlConstants.TYPE_ATTR, "text/javascript""type");
        writer.writeText(scriptnull);
        writer.endElement(HtmlConstants.SCRIPT_ELEM);
    }

    
If target component contains generated id and for doesn't, correct for id

Parameters:
forAttr
component
    public String correctForIdReference(String forAttr, UIComponent component) {
        int contains = forAttr.indexOf(UIViewRoot.UNIQUE_ID_PREFIX);
        if (contains <= 0) {
            String id = component.getId();
            int pos = id.indexOf(UIViewRoot.UNIQUE_ID_PREFIX);
            if (pos > 0) {
                return forAttr.concat(id.substring(pos));
            }
        }
        return forAttr;
    }
    public void encodeChildren(FacesContext context, UIComponent componentthrows IOException {
        if (component.getChildCount() > 0) {
            for (UIComponent child : component.getChildren()) {
                child.encodeAll(context);
            }
        }
    }
    public boolean hasExplicitId(UIComponent component) {
        return component.getId() != null && !component.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX);
    }
    public UIComponent findComponentFor(FacesContext context, UIComponent componentString id) {
        return findComponentFor(componentid);
    }

    

Parameters:
component
id
Returns:
    public UIComponent findComponentFor(UIComponent componentString id) {
        if (id == null) {
            throw new NullPointerException("id is null!");
        }
        if (id.length() == 0) {
            return null;
        }
        UIComponent target = null;
        UIComponent parent = component;
        UIComponent root = component;
        while ((null == target) && (null != parent)) {
            target = parent.findComponent(id);
            root = parent;
            parent = parent.getParent();
        }
        if (null == target) {
            target = findUIComponentBelow(rootid);
        }
        return target;
    }
    private UIComponent findUIComponentBelow(UIComponent rootString id) {
        UIComponent target = null;
        for (Iterator<UIComponent> iter = root.getFacetsAndChildren(); iter.hasNext();) {
            UIComponent child = (UIComponent) iter.next();
            if (child instanceof NamingContainer) {
                try {
                    target = child.findComponent(id);
                } catch (IllegalArgumentException iae) {
                    continue;
                }
            }
            if (target == null) {
                if ((child.getChildCount() > 0) || (child.getFacetCount() > 0)) {
                    target = findUIComponentBelow(childid);
                }
            }
            if (target != null) {
                break;
            }
        }
        return target;
    }
New to GrepCode? Check out our FAQ X