Extreme Java When vanilla Java is not enough

8Apr/103

h:selectManyCheckbox with multiple columns/rows

If you ever tried to use the component, you had a bad time figuring out how to split the checkbox on multiple rows - there's no simple way to do that.

Let's talk about a feature of the tag: it can receive both SelectItem and SelectItemGroup. This means you can create a group of SelectItem easily. Example: if you have a Role list grouped by categories, the List can have a list of SelectItemGroup and these can have a list of SelectItem with the roles.

Pretty nice, but the items are rendered with the group orientation: this means JSF will render an horizontal table for the groups with nested horizontal tables for the items. Still ugly!

You can solve this using Tomahawk, but I think it's too much trouble only to get this simple requirement. I prefer using a pure-JSF solution like a new Renderer. Mojarra's renderer makes this job very easy:

public class MyRenderer
    extends SelectManyCheckboxListRenderer {
 
  // keeps track of current rendering
  private boolean inner;
 
  // overriding with synchronized
  @Override
  public synchronized void encodeEnd(
      FacesContext context,
      UIComponent component) throws IOException {
    super.encodeEnd(context, component);
  }
 
  @Override
  protected void renderBeginText(
      UIComponent component, int border,
      boolean alignVertical, FacesContext context,
      boolean outerTable) throws IOException {
    // are we at the inner table?
    this.inner = !outerTable;
    super.renderBeginText(component, border,
      alignVertical ^ inner, context, outerTable);
  }
 
  @Override
  protected void renderEndText(
      UIComponent component, boolean alignVertical,
      FacesContext context) throws IOException {
    super.renderEndText(component,
      alignVertical ^ inner, context);
    // reset after inner table is rendered
    this.inner = false;
  }
 
  @Override
  protected void renderOption(
      FacesContext context, UIComponent component,
      Converter converter, SelectItem curItem,
      Object currentSelections,
      Object[] submittedValues,
      boolean alignVertical, int itemNumber,
      OptionComponentInfo optionInfo)
      throws IOException {
    super.renderOption(context, component, converter,
      curItem, currentSelections, submittedValues,
      alignVertical ^ inner, itemNumber, optionInfo);
  }
}

The trick is pass "alignVertical" parameter XOR inner state. This will change the alignment for the inner table. If you use "pageDirection" as layout, the inner table will use "lineDirection" and vice-versa. Using the "roles" example, the groups will be aligned horizontally and their roles, vertically.

Now, if you don't want to use groups, you can still benefit - create pseudo-groups for each N elements.  This will give you a matrix-like checkbox list.

7Apr/100

Using f:selectItems with JPA entities

It's a common scenario: you must do a "SELECT e FROM Entity e" with JPA and pass it to a <h:selectOneMenu> or a <h:selectManyList>. Unfortunately, if you google it, you will find a lot of strange solutions.

I've tested a simple solution on JavaEE 6. On my managed bean, I can define a property like this:

...
public class MyBean {
  ...
  @PersistenceContext
  private EntityManager em;
 
  public Converter getConverter() {
    return new Converter() {
      @Override
      public Object getAsObject(
          FacesContext fc,
          UIComponent uic,
          String string) {
        return (string == null)
          ? null
          : em.find(MyEntity.class,
                    Long.parseLong(string));
      }
      @Override
      public String getAsString(
          FacesContext fc,
          UIComponent uic,
          Object o) {
        return (o == null)
          ? null
          : Long.toString(((MyEntity) o).getId());
      }
    };
  }
}

According to JSF specification, only managed beans can be injected. This is why I declared it as an inner class.

This way, the converter allows you to work only with entities, instead of manually storing IDs on the managed bean. This means the page can bind to this property when a conversion is needed:

<h:selectOneMenu value="#{myBean.myEntitySelection}">
  <f:selectItems value="#{myBean.myEntityList}"/>
  <f:converter binding="#{myBean.converter}"/>
</h:selectOneMenu>

One last step: your Entity must have an working "equals" method. If you forget this, you will receive the message "Validation Exception: Value is invalid".

Usually, a boilerplate, like this one generated by NetBeans will suffice:

@Override
public boolean equals(Object obj) {
  if (obj == null) {
    return false;
  }
  if (getClass() != obj.getClass()) {
    return false;
  }
  final MyEntity other = (MyEntity) obj;
  if (this.id != other.id
      &amp;&amp; (this.id == null
          || !this.id.equals(other.id))) {
    return false;
  }
  return true;
}

Works like a charm on JSF 2, but I haven't tested on JSF 1.2.

BTW, this solution can be refactored to became a more generic: create a base entity class that declares a "getId" method returning Serializable. Then, the converter can be a class receiving an entity manager and the persistent class.

22May/090

Using Spring with Mojarra InjectionProvider

Are you using SpringBeanFacesELResolver to handle dependency injection on managed beans? It works nice, but your faces-config grows fast with this approach.

Two months ago, I posted about using Spring injection outside application context. I forgot to mention that the same trick can be used to replace ELResolver solution if you are using Mojarra as your JSF provider.

You only need to add a servlet context parameter:

<context-param>
  <param-name>
    com.sun.faces.injectionProvider
  </param-name>
  <param-value>
    mypkg.SpringJSFInjectionProvider
  </param-value>
</context-param>

And the implementation of SpringJSFInjectionProvider is as simple as:

public class SpringJSFInjectionProvider
       implements InjectionProvider {
  private WebContainerInjectionProvider wcip =
      new WebContainerInjectionProvider();
 
  @Override
  public void inject(Object bean)
         throws InjectionProviderException {
    FacesContextUtils
      .getWebApplicationContext(
         FacesContext.getCurrentInstance())
      .getAutowireCapableBeanFactory()
      .autowireBeanProperties(bean,
         AutowireCapableBeanFactory.AUTOWIRE_NO,
         false);
    wcip.inject(bean);
  }
  @Override
  public void invokePreDestroy(Object bean)
         throws InjectionProviderException {
    wcip.invokePreDestroy(bean);
  }
  @Override
  public void invokePostConstruct(Object bean)
         throws InjectionProviderException {
    wcip.invokePostConstruct(bean);
  }
}

Adding this, you can shrink your faces-context, removing all "managed-property" tags. Your managed beans can look more JavaEE 5 after you change this:

private BO bo;
 
public void setBo(BO bo) {
  this.bo = bo;
}

To this:

@Resource(name="bean-on-appctx")
private BO bo;

No setter, no ELResolver. This means less code to maintain! If you plan to migrate from Spring to EJB, this means you will only need to promote the BO to an stateless bean and change @Resource to @EJB!

17Mar/090

Password and confirmation with JSF

If you need to validate a field in JSF and the value is dependent of another field (like password/confirmation), BalusC posted a nice tutorial about it. You need to create a JSF Validator and add a to your field. Easier than I thought...

12Jan/090

Marker-only validation error with RichFaces

I've made a simple JSP 2.1 tag file to show only a small icon on my validation errors (and a tooltip to show message details). This is the .tag file:

<%@ tag pageEncoding="UTF-8" %>
<%@ attribute name="field" required="true" deferredValue="true" %>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<%@ taglib prefix="a4j" uri="http://richfaces.org/a4j" %>
<%@ taglib prefix="rich" uri="http://richfaces.org/rich" %>
<rich:message for="#{field}" showSummary="false" showDetail="false">
  <f:facet name="errorMarker">
    <a4j:outputPanel>
      <h:graphicImage value="path-to-bullet"/>
      <rich:toolTip>
        <rich:message for="#{field}"/>
      </rich:toolTip>
    </a4j:outputPanel>
  </f:facet>
</rich:message>

It can be used like this:

<tags:errorMessages field="id-of-the-field"/>

Instead of showing a big chunk of text, your webdesigner will only deal with a small bullet that will show a nice tooltip with the full message. Some "catches":

  • <rich:message tooltip="true"> does not show tooltip if you disable both summary and details;
  • Since "rich:toolTip" can't work with "h:panelGrid", the "a4j:outputPanel" will show the tooltip without adding any extra visual effect (like "rich:panel" does);
  • The inner "rich:message" will render the message inside the tooltip (notice that outer "rich:message" renders only the marker, because summary and details are "off").