Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
$URL: https://source.sakaiproject.org/svn/jsf/tags/sakai-10.0/jsf-widgets/src/java/org/sakaiproject/jsf/util/RendererUtil.java $ $Id: RendererUtil.java 105077 2012-02-24 22:54:29Z ottenhoff@longsight.com $ Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation Licensed under the Educational Community License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.opensource.org/licenses/ECL-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. /
 
 
 package org.sakaiproject.jsf.util;
 
 import java.io.Writer;
 import java.util.List;
 import java.util.Map;
 
Common static utility methods that help in implementing JSF tags.
 
 public class RendererUtil
 {

    
This class is meant for static use only
 
     private RendererUtil()
     {
     }

    
Sets component attribute value - if a ValueBinding exists for that attribute, set through the binding; otherwise, set the value directly on the component.
 
     public static void setAttribute(FacesContext contextUIComponent componentString name,
             Object value)
     {
         ValueBinding binding = component.getValueBinding(name);
         if (binding != null)
         {
             try
             {
                 binding.setValue(contextvalue);
             } catch (IllegalArgumentException e)
             {
                 // try setting the value as a String
                 binding.setValue(context, String.valueOf(value));
             }
         } else
         {
             component.getAttributes().put(namevalue);
         }
     }

    
Return the attribute value - handles getting the value from a ValueBinding if necessary. This is necessary because of a difference in the Sun JSF RI versus the MyFaces RI. The Sun RI component.getAttributes().get(attrName) will automatically return value bindings, whereas the MyFaces implmentation requires getting values from ValueBinding seperately.
 
     public static Object getAttribute(FacesContext contextUIComponent componentString name)
     {
         // first check the attributes
         Object ret = component.getAttributes().get(name);
         if (ret != null)
             return ret;
 
         // next check the value bindings
         ValueBinding vb = component.getValueBinding(name);
         if (vb != null)
             ret = vb.getValue(context);
 
         return ret;
    }

    
Same as getAttribute, but if not found, we return a default value.
    public static Object getDefaultedAttribute(FacesContext contextUIComponent component,
            String nameObject defaultValue)
    {
        Object o = getAttribute(contextcomponentname);
        if (o == null)
            o = defaultValue;
        return o;
    }

    
Helper method for recursively encoding a component.

Parameters:
context the given FacesContext
component the UIComponent to render
Throws:
java.io.IOException
    public static void encodeRecursive(FacesContext contextUIComponent component)
            throws IOException
    {
        if (!component.isRendered())
        {
            return;
        }
        component.encodeBegin(context);
        if (component.getRendersChildren())
        {
            component.encodeChildren(context);
        } else
        {
            Iterator iter = component.getChildren().iterator();
            while (iter.hasNext())
            {
                UIComponent child = (UIComponentiter.next();
                encodeRecursive(contextchild);
            }
        }
        component.encodeEnd(context);
    }

    
If renderer supports disabled or readonly attributes use this method to obtain an early exit from decode method. Good idea to include it anyway, compnent will continue to work when these properties are added.
    public static boolean isDisabledOrReadonly(FacesContext contextUIComponent component)
    {
        boolean disabled = false;
        boolean readOnly = false;
        Object disabledAttr = getAttribute(contextcomponent"disabled");
        if (disabledAttr != null)
        {
            disabled = disabledAttr.equals(.);
        }
        Object readOnlyAttr = getAttribute(contextcomponent"readonly");
        if (readOnlyAttr != null)
        {
            readOnly = readOnlyAttr.equals(.);
        }
        return readOnly | disabled;
    }

    
Write default HTML passthrough attributes
    public static void writePassthroughs(FacesContext contextUIComponent component)
            throws IOException
    {
        String[] passthrus = { "ondblclick""onclick""onkeydown""onkeypress""onkeyup",
                "onmousedown""onmousemove""onmouseout""onmouseover""onmouseup" };
        writePassthroughAttributes(passthrustruecontextcomponent);
    }

    
write passthough attributes on the current element
    public static void writePassthroughAttributes(String[] passthrusboolean writeNullAttrs,
            FacesContext contextUIComponent componentthrows IOException
    {
        ResponseWriter writer = context.getResponseWriter();
        for (int i = 0; i < passthrus.lengthi++)
        {
            String key = passthrus[i];
            String value = (StringgetAttribute(contextcomponentkey);
            if (writeNullAttrs && value == null)
                value = "";
            if (value != null)
                writer.writeAttribute(keyvaluenull);
        }
    }

    

Parameters:
attributeMap String key/value pairs
writer response writer
    public static void writeAttributes(Map attributeMapResponseWriter writerthrows IOException
    {
        Iterator iter = attributeMap.entrySet().iterator();
        while (iter.hasNext())
        {
            Entry entry = (Entryiter.next();
            String key = (Stringentry.getKey();
            String value = (Stringentry.getValue();
            if (value == null)
                value = "";
            writer.writeAttribute(keyvaluekey);
        }
    }

    

Parameters:
attributeMap String key/value pairs
context Faces context
component the UIComponent
Throws:
java.io.IOException
    public static void writeAttributes(Map attributeMapFacesContext contextthrows IOException
    {
        ResponseWriter writer = context.getResponseWriter();
        writeAttributes(attributeMapwriter);
    }

    
Renders a script that includes an external JavaScript that gets added to the document through a document.write() if a gatekeeper value is NOT set. This effectively makes the script inclusion a per request JavaScript singleton.

Parameters:
gateKey for key value pair
gateValue value for key value pair for gatekeeper
contextBasePath the web app with the script
scriptPath the webapp-relative path
Throws:
java.io.IOException
    public static void writeSmartExternalScripts(FacesContext contextString gateKey,
            String gateValueString contextBasePathString[] scriptPathsthrows IOException
    {
        ResponseWriter writer = context.getResponseWriter();
        writeSmartExternalScripts(writergateKeygateValuecontextBasePathscriptPaths);
    }

    
Renders a script that includes an external JavaScript that gets added to the document through a document.write() if a gatekeeper value is NOT set. This effectively makes the script inclusion a per request JavaScript singleton.

Parameters:
writer the ResponseWriter
gateKey for key value pair
gateValue value for key value pair for gatekeeper
contextBasePath the web app with the script
scriptPath the webapp-relative path
Throws:
java.io.IOException
    public static void writeSmartExternalScripts(ResponseWriter writerString gateKey,
            String gateValueString contextBasePathString[] scriptPathsthrows IOException
    {
        writer.write("<script>");
        writer.write("  if (typeof window['" + gateKey + "'] == '" + gateValue + "')");
        writer.write("  {");
        for (int i = 0; i < scriptPaths.lengthi++)
        {
            writer.write("    document.write(");
            writer.write("   \"<\" + \"script type='text/javascript' src='/'\" + "
                    + contextBasePath + " +");
            writer.write("   \"'" + scriptPaths[i] + "'><\" + \"/script>);");
        }
        writer.write("   var " + gateKey + " = '" + gateValue + "';");
        writer.write("  }");
        writer.write("</script>");
        writer.write("");
        writer.write("");
    }

    
Get a Map of String key/value pairs from a UIComponent for all attributes keys in a collection

Parameters:
collection
component
Returns:
Map of String key/value pairs from a UIComponent for all keys in a collection
    public static Map mapComponentAttributes(Collection collectionUIComponent component)
    {
        Map attributeMap = new HashMap();
        if (collection == null)
            return attributeMap;
        String[] attributeNames = new String[collection.size()];
        Object[] objs = collection.toArray();
        for (int i = 0; i < objs.lengthi++)
        {
            attributeNames[i] = (Stringobjs[i];
        }
        return mapComponentAttributes(attributeNamescomponent);
    }

    
Get String key/value pairs from a UIComponent for all attributes keys in an array

Parameters:
attributeNames
component
Returns:
Map of String key/value pairs from a UIComponent for all keys in a collection
    public static Map mapComponentAttributes(String[] attributeNamesUIComponent component)
    {
        Map attributeMap = new HashMap();
        for (int i = 0; i < attributeNames.lengthi++)
        {
            attributeMap.put(attributeNames[i], (Stringcomponent.getAttributes().get(
                    attributeNames[i]));
        }
        return attributeMap;
    }

    
Switch handling utility.

Parameters:
rawSwitch String input string
supportOnOff boolean can input string be on, off?
supportTrueFalse boolean can input string be true, false?
supportYesNo boolean can input string be yes, no?
returnOnOff boolean output on, off instead of true false
returnYesNo boolean output yes, no instead of true false
defaultValue boolean if unknown, return true or false?
Returns:
String raw swrich sring translated to correct switch value or default
    public static String makeSwitchString(String rawSwitchboolean supportOnOff,
            boolean supportTrueFalseboolean supportYesNoboolean returnOnOff,
            boolean returnYesNoboolean defaultValue)
    {
        boolean switchValue = defaultValue;
        String trueString = "true";
        String falseString = "false";
        if (returnOnOff)
        {
            trueString = "on";
            falseString = "off";
        } else if (returnYesNo)
        {
            trueString = "yes";
            falseString = "no";
        }
        if (supportOnOff)
        {
            if ("on".equalsIgnoreCase(rawSwitch))
                switchValue = true;
            if ("off".equalsIgnoreCase(rawSwitch))
                switchValue = false;
        } 
        if (supportTrueFalse)
        {
            if ("true".equalsIgnoreCase(rawSwitch))
                switchValue = true;
            if ("false".equalsIgnoreCase(rawSwitch))
                switchValue = false;
        } 
        if (supportYesNo)
        {
            if ("yes".equalsIgnoreCase(rawSwitch))
                switchValue = true;
            if ("no".equalsIgnoreCase(rawSwitch))
                switchValue = false;
        }
        if (switchValue)
        {
            return trueString;
        } else
        {
            return falseString;
        }
    }

    
Given a List of SelectItems render the select options

Parameters:
out
items List of SelectItems
selected seelcted choice
clientId the id
styleClass the optional style class
component the component being rendered
Throws:
java.io.IOException
    public static void renderMenu(ResponseWriter outList itemsint selectedString clientId,
            String styleClassUIComponent componentthrows IOException
    {
        // // debug lines
        // out.writeText("startElement select", null);
        // if (true) return;
        out.startElement("select"component);
        out.writeAttribute("name"clientId"id");
        out.writeAttribute("id"clientId"id");
        if (styleClass != null)
        {
            out.writeAttribute("class"styleClass"styleClass");
        }
        Iterator iter = items.iterator();
        while (iter.hasNext())
        {
            SelectItem si = (SelectItemiter.next();
            Integer value = (Integersi.getValue();
            String label = si.getLabel();
            out.startElement("option"component);
            out.writeAttribute("value"valuenull);
            if (value.intValue() == selected)
            {
                out.writeAttribute("selected""selected"null);
            }
            out.writeText(labelnull);
        }
        out.endElement("select");
    }

    
Return the form ID of the form containing the given component
    public static String getFormId(FacesContext contextUIComponent component)
    {
        while (component != null && !(component instanceof UIForm))
        {
            component = component.getParent();
        }
        if (component != null)
            return ((UIFormcomponent).getId();
        return null;
    }
    
    
    

Parameters:
context FacesContext for the request we are processing
writer ResponseWriter to be used
key key to use to look up the value in the request
path path to the file
Throws:
java.io.IOException if an input/output error occurs while rendering
    public static void writeExternalJSDependencies(FacesContext context
          ResponseWriter writerString keyString paththrows IOException
    {
       String jsInclude= (Stringreq.getAttribute(key);
       
       if (jsInclude == null || jsInclude.length() == 0)
       {
          // include default stylesheet
          jsInclude = "<script type=\"text/javascript\" src=\"" + path + "\"></script>\n";
          req.setAttribute(keyjsInclude);
          writer.write(jsInclude);
       }
    }
    
    
    

Parameters:
context FacesContext for the request we are processing
writer ResponseWriter to be used
key key to use to look up the value in the request
path path to the file
Throws:
java.io.IOException if an input/output error occurs while rendering
    public static void writeExternalCSSDependencies(FacesContext context
          ResponseWriter writerString keyString paththrows IOException
    {
       String cssInclude = (Stringreq.getAttribute(key);
       
       if (cssInclude == null || cssInclude.length() == 0)
       {
          // include default stylesheet
          cssInclude = "<link href=\"" + path + "\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n";
          req.setAttribute(keycssInclude);
          writer.write(cssInclude);
       }
    }
    
    public static void writeAttr(Writer inWriterString inAttrString inAttrValue)
    throws IOException
    {
       if(inWriter == null || inAttr == null || inAttrValue == null)
          return;
       inWriter.write(" ");
       inWriter.write(inAttr);
       inWriter.write("=\"");
       inWriter.write(inAttrValue);
       inWriter.write("\" ");
    }
New to GrepCode? Check out our FAQ X