Wednesday, October 3, 2012

tr:forEach to soon provide support for changes to the collection

In order to address the issues that I discussed in my blog regarding the c:forEach tag, I implemented enhancements to the Trinidad forEach tag since I am a developer on that team.

The changes are part of TRINIDAD-1940 which should be part of the future Trinidad 2.1.0 release. Until then, you can try out the changes by using the snapshot build.

The forEach tag documentation does not have the new documentation as the site is currently based on the 2.0.2-SNAPSHOT documentation.

Until then, here is a preview of the new forEach documentation (Content owned by the ASF is covered by the Apache version 2.0 license):

Summary

Tag name: <tr:forEach>

The forEach tag provides additional functionality from the JSTL <c:forEach> tag. The tag is only supported in JSP.

Facelets

The <tr:forEach> is not supported in facelets. As a convenience, the tag handler for the <c:forEach> will be used in facelets when a <tr:forEach> is used in a facelets page, but no Trinidad functionality will be supported.

Supported collections

The Trinidad forEach tag supports the following collections for the items attribute:
  • Java array
  • java.util.List
  • org.apache.myfaces.trinidad.model.CollectionModel
  • java.util.Map

When using a map, the map should be one that has a consistent order. Either the java.util.LinkedHashMap or java.util.TreeMap are examples of maps that provide this functionality. The keys for the maps must implement java.io.Serializable.

Usage

Valid Use Cases

The for each tag is not as efficient as component stamping. When possible, the <tr:iterator> should always be used instead of the for each tag. There are times this is not possible and usually involve the inclusion of content from other pages. For example, if different <jsp:include> tags need to be generated, pointing to different files based on items in a list, a for each tag must be used and not a stamping component like the Trinidad iterator.

ID and Component State

Due to the way JSF and JSP create ValueExpression objects, the for each tag cannot safely map the expressions created and stored on JSF components to the iteration of the for each loop. As a result, it is possible to cause a discrepency between the component's location in the for each tag and the value expressions that are stored in the tag.

Due to this limitation, the forEach tag must place usage requirements on the pages they are placed on. For index based collections (arrays and lists), the components must be mapped to the index of the for each loop and not the item in the collection. In these cases, the index of the for each loop is stored into the value expressions created and stored into the components. This results in the component state (like expanded state of disclosure components) being tied to the index of the for each loop. As a result, a key based collection (map or collection model) is always recommended when the collection may change between requests.

For key based collections (map and collection model), the component IDs must be associated with the key of the collection. This is because the key of the collection is used in the value expressions and if the ID were not bound to the key, then the component state would not match the EL values. You should associate the component to the key using immediate EL in the ID attribute. See the examples below.

Generated IDs

When the collection may change between requests, a key based collection should be used. When this is done, it is not recommended that JSF be allowed to generate the IDs of any components inside the for each tag. The reason is that JSF auto-generated IDs are based on the sequence that they are created in the current page. If items are re-arranged in the for each loop, the IDs will have a different generation order. As a result, JSF will not find the components with auto-generated IDs when it tries to map the JSP tag to the component ID. Existing components will be thrown out and new ones will be created and component state will be lost if this occurs.

Reordering and Collection Modifications

Modifications to the collection in the same JSF view (between requests) are only supported with key based collections. Even with this being supported, the for each tag will not auto-rearrange the children.

When JSP seeks to locate a component that was created in a previous request, it creates the ID that it expects the component to have and then searches the children of the parent component of the tag for the child component with that ID. If the component is not found, a new one will be created. If it is found, the framework does not do anything to the component, it is left to exist where it is found. This means that if you reorder items in your collection between requests, the component order will no longer match the order of the items in the collection. Page authors must reorder the components when changes to the collection are made.

Trinidad supports re-ordering of components using the change manager (org.apache.myfaces.trinidad.change.ChangeManager) and the org.apache.myfaces.trinidad.change.ReorderChildrenComponentChange class. The change manager may be retrieved from the org.apache.myfaces.trinidad.context.RequestContext instance. See the Trinidad demo application for examples on how to reorder the components when the collections changes.

When using a key based collection, it is recommended to use a naming container to simplify tying the component ID to the key. See the examples below.

Examples

Please see the Trinidad demo application for complete examples.

Index Based Collection

<tr:forEach var="person" items="#{forEachBean.simpleList}" varStatus="vs">
  <f:subview id="sv${vs.key}">
    <tr:panelGroupLayout id="personPgl" layout="horizontal">
      <tr:outputText id="personName" value="#{person.firstName} #{person.firstName}"
                     inlineStyle="padding-right: 1em;"/>
      <tr:outputText id="clientId" value="(Client ID: #{component.clientId})"/>
    </tr:panelGroupLayout>
    <tr:spacer id="s1" height="1em" />
  </f:subview>
</tr:forEach>

Key Based Collection

<tr:forEach var="person" items="#{forEachBean.collectionModel}" varStatus="vs">
  <f:subview id="sv${vs.key}">
    <tr:panelGroupLayout id="personPgl" layout="horizontal">
      <tr:outputText id="personName" value="#{person.firstName} #{person.firstName}"
                     inlineStyle="padding-right: 1em;"/>
      <tr:outputText id="clientId" value="(Client ID: #{component.clientId})"/>
    </tr:panelGroupLayout>
    <tr:spacer id="s1" height="1em" />
  </f:subview>
</tr:forEach>

Example Re-Order Code

// Create a list of all the children IDs of the parent component of the for each loop. This must
// contain all the children, not just those created by the for each tag.
List<String> orderedIds = ...;

// Get the reference to the component that is the parent of the for each tag. For finding relative
// components, you may try using
// org.apache.myfaces.trinidad.util.ComponentUtils.findRelativeComponent(UIComponent, String)
UIComponent forEachParent = ...;

ReorderChildrenComponentChange componentChange = new ReorderChildrenComponentChange(orderedIds);
RequestContext requestContext = RequestContext.getCurrentInstance();
ChangeManager cm = requestContext.getChangeManager();
// The component change must be added before the tag execution (before the render response JSF
// phase)
cm.addComponentChange(FacesContext.getCurrentInstance(), forEachParentComponent,
  componentChange);

// Ensure that the view is updated during PPR requests
requestContext.addPartialTarget(forEachParentComponent);
        

Attributes

Name Type Supports EL? Description
begin primitive int or java.lang.Number subclass No index at which iteration begins
end primitive int or java.lang.Number subclass No index at which iteration ends
items Object Only EL the collection to iterate over. Supported classes:
  • Java array
  • java.util.List
  • org.apache.myfaces.trinidad.model.CollectionModel
  • java.util.Map
step primitive int or java.lang.Number subclass No number to increment the index by on each iteration
var String No name of the variable exposed when iterating that references the item in the collection
varStatus String No name of the loop status exposed when iterating.

Properties:

Name Description
index the current index (int)
count the total number of times the for each tag will iterate (int)
begin the index to start at when collections are not used (int)
end the last index when collections are not used (int)
first true if this is the first iteration (boolean)
last true if this is the last iteration (boolean)
key the index (int) for index based collections and when the items has not been specified. The key (java.io.Serializable) for key based collections

Wednesday, January 4, 2012

Component scope

It is often confusing to users what it means by having a JSF component be "in scope," especially in JSF 2. JSF is processed by a set of phases, each one usually iterates the component tree, acting upon each component in turn. Some components, like the h:dataTable, perform stamping.

Note, for more information on stamping, please see my blog on tables.

When a component is being processed, the EL context may be altered. For example, the data table injects "var" and "varStatus" variables into the request scope. This also means that when the table is not being processed, these variables are either not available, or point to another value.

This is what I mean by a component being "in scope," that it is currently being processed by the JSF lifecycle or JSF APIs in a manner congruent with the JSF specification for working with components.

How a component enters scope

A component can enter scope one of three ways:

  1. The JSF lifecycle is being run. This will be the result of calls from methods on the component:
    • processDecodes
    • processValidators
    • processUpdates
    • processSaveState
    • processRestoreState
    • broadcast
  2. During an invokeOnComponent callback
  3. During a visitTree callback

At any other time, it may not be valid to be interacting with the component. Take for example, using Oracle ADF components, an input text component inside of an iterator:

<af:iterator var="item" value="#{bean.items}">
  <af:inputText value="#{item.value}" binding="#{bean.inputText}" />
</af:iterator>

Now consider this Java code for the bean:

private RichInputText _inputText;

public RichInputText getInputText()
{
  return _inputText;
}

public void setInputText(RichInputText text)
{
  _inputText = text;
}

public Object getValue()
{
  return _inputText == null ? null : _inputText.getValue();
}

Should code call the bean's getValue() method, what is the outcome? Well that is indeed the problem. Before the JSF view is built, the value will be null as the component has not been bound yet. Between JSF phases, it will also be null because #{item} will not be present in the EL context.

As this example shows, the attributes and behavior of the component in question change based on what component is currently being operated on. What makes this even more of an issue, is component frameworks that setup and tear down contexts. For example, Oracle ADF faces has a base component class called a oracle.adf.view.rich.component.fragment.ContextSwitchingComponent. When a component is processing its JSF lifecycle, or one of its children is being called back via a visitTree or invokeOnComponent call, the setupContext method has been run. If one of these components is accessed through code, and the context has not been set up yet, unreliable results may occur, or even exceptions may be thrown. One use case is of the ADF page template component. By using context switching, this component alters the EL context so that facets in the page with the <af:pageTemplate /> tag are executed in the EL context they were defined in, and the components inside the page template definition are executed within the context of the page template definition file.

Note that JSF 2 has a compound component like the ADF page template, but I am not sure how it handles EL context resultion.

It is therefore, never a good idea to call methods or evaluate attributes on JSF components unless the caller is sure that the component being accessed is currently in scope. Here is another example:

<af:iterator var="item" value="#{bean.items}">
  <af:pageTemplate viewId="template.jspx" item="#{item}">
    <f:facet name="center">
      <af:outputText id="facetText" value="#{item.itemValue}" />
    </f:facet>
  </f:pageTemplate>
</af:iterator>

Page definition:

...
<af:pageTemplateDef var="attrs">
  <af:xmlContent>
    <component xmlns="http://xmlns.oracle.com/adf/faces/rich/component">
      <description>This component lays out an entire page.</description>
      <facet>
        <description>The center content.</description>
        <facet-name>center</facet-name>
      </facet>
      <attribute>
        <description>the item.</description>
        <attribute-name>item</attribute-name>
        <attribute-class>com.mycompany.MyItem</attribute-class>
      </attribute>
    </component>
  </af:xmlContent>
  <af:iterator var="item" value="#{item.innerItems}">
    <af:facetRef facetName="center"/>
    <af:outputText id="templateText" value="#{item.itemValue}" />
  </af:iterator>
</af:pageTemplateDef>

This is a very simplified example, but it illustrates the question, what does #{item.itemValue}" evaluate to? In the facet, this should be the item from the bean's items collection, as shown with the output text with id "facetText". Inside the page template, the value should be the item from the inner items collection of the item passed into the page template, show by the output text with the id "templateText". Depending on when this EL is evaluated, different values will be returned. Therefore, is is crucial, that in order to evaluate the RichOutputText.getValue() method, that the call is made while that component is "in scope," or "in context."

Putting a component into context

Components are automatically put into context when they are being validated, updated, broadcasting events, rendering, etc. Sometimes it is necessary to interact with a component outside of its context. For example, perhaps you have backing bean code that wishes to get the input text value. This may be done by knowing a component's client ID, and using the visitTree method. Here is an example:

public void performAction(ActionEvent evt)
{
  String clientId = "template1:table1:0:firstNameInputText";
  FacesContext facesContext = FacesContext.getCurrentInstance();
  VisitContext visitContext = VisitContext.createVisitContext(facesContext,
    Collections.singleton(clientId), EnumSet.of(SKIP_UNRENDERED));
  GetFirstNameCallback callback = new GetFirstNameCallback();
  facesContext.getViewRoot().visitTree(visitContext, callback);

  String firstName = callback.getFirstName();
  ...
}

private static class GetFirstNameCallback
  implements VisitCallback
{
  private String _firstName;

  public String getFirstName()
  {
    return _firstName;
  }

  public VisitResult visit(
    VisitContext visitContext,
    UIComponent  target)
  {
    RichInputText inputText = (RichInputText)target;
    _firstName = (String)inputText.getValue();
    return VisitResult.COMPLETE;
  }
}

Here the code illustrates how to access the input text value for a component in the first row of a table.

Summary

Due to the fact that EL is contextual, it is important that any EL based functionality is only accessed in the correct context for that EL. As such, JSF developers should use caution when interacting with components via their Java APIs. Using visit tree should always be considered when trying to access properties from a component in order to ensure that the expected EL context has been setup when the component attempts to access its data. Failing to do so may cause issues with your programs, and even data contamination.

Sunday, February 1, 2009

Problems with the Mozilla Component.utils.Sandbox

Writing a Firefox extension can be time consuming for the first time, the documentation is more reference oriented, more oriented to C++ than the JavaScript version, but it is the worst when there are bugs and you waste hours of work. That is what happened to me with the Sandbox APIs of Firefox 3. After talking to members of the FireBug extension on its Google groups forum, I found out that I am not alone with Sandbox frustrations.

The Sandbox

The sandbox, introduced in full in FF3, is a container that allows extension developers to run code in lower security. This is helpful for interacting with browser web pages or for running code from a server. The Sandbox API Documentation is pretty light, and gives no useful examples for real-world applications. The primary use of the sandbox is probably to work with pages, but they show no example on how to do that.

My Problem

When I was working on an extension I write for work, I found that I had some extremely peculiar results. As an illustration, lets say there are two types of JavaScript objects in a page that you want to work with. The first, is a single instance object that looks up other JS objects, and the second, a 'normal' JS object that we want to create. So for my example, lets say we want to lookup an object, pass that object into a constructor and then run a method on that new object:

  var obj = TheRegistry.lookupObject('customId1');
  var ref = new ObjectReference(obj);
  ref.save();

Now, I want to run this code in my extension, so I setup the sandbox and execute the code like this:

  var evalInSandbox = function(win, script, vars)
  {
    win = getUnwrapped(win);
    var sandbox = new Components.utils.Sandbox(win);
    sandbox.window = win;
    sandbox.document = sandbox.window.document;
    sandbox.XPathResult = Components.interfaces.nsIDOMXPathResult;
    sandbox.__proto__ = win;
    if (vars)
    {
      for (var prop in vars)
      {
        sandbox[prop] = vars[prop];
      }
    }
    return Components.utils.evalInSandbox(
      "(function() { " + script + "\n })();", sandbox);
  };
  
  var getUnwrapped = function(obj)
  {
    while (obj.wrappedJSObject)
    {
      obj = obj.wrappedJSObject;
    }
    return obj;
  };
  
  var doSomething = function(window)
  {
    evalInSandbox(window,
      "var obj = TheRegistry.lookupObject('customId1');"+
      "var ref = new ObjectReference(obj);"+
      "ref.save();");
  }

What I was surprised to find out is that ref had no 'save' method, but I knew that was not the case. Looking further into it, ref == obj. What the heck?! I tried wrapping the code with with (window) { ... }, using new window.ObjectReference(obj), but nothing would work. Finally I gave up on the code and used a FireBug technique to inject a script tag into the page's DOM.

Wrap Up

I wrote this article, not to teach, but hopefully to save other people some time so if the google 'mozilla sandbox bugs' or something similar, they may find this. Hopefully Mozilla will fix the sandbox and improve its documentation, but until then, watch out for bugs, and stay away from creating page objects using the 'new' keyword inside of the sandbox, it just doesn't work.

BTW, the google group discussion I mentioned can be found here.