Archive

Archive for the ‘Richfaces’ Category

Disable backspace key in a Richfaces application

Friday, 6. November 2009 Andreas Höhmann Leave a comment

If you want disable the Backspace key in your JSF Richfaces application put this in your view:

<rich:hotKey key="backspace" handler="return false;" disableInInput="true"/>

This will register a jQuery Hotkey handler for the document. The handler is not reqistered for input elements because in input fields you need the backspace ;-) . Tested for FF3 and IE6.

Then I found out that the following snippet doesn’t work:

<rich:hotKey key="backspace"
             disableInInput="true"
             handler="alert('Backspace is disabled'); return false;" />

The Browser open the alert box and go to the previous page (in background?!). But there is a fix for that:

<rich:hotKey key="backspace"
             disableInInput="true"
             handler="alert('Backspace is disabled'); event.stopPropagation(); event.preventDefault(); return false;" />

The event variable is available in the handler function (see org.richfaces.renderkit.html.HotKeyRenderer method doEncodeEnd).

Customized Richfaces Tree

Thursday, 10. September 2009 Andreas Höhmann Leave a comment

Yesterday I had to customize the Richfaces tree component, because my client wants a special layout. My solution is a little bit strange. I share it here for someone which is in the same situation ;) Here is the story …

Per default the rich:tree looks like a standard tree browser (i.e. explorer, eclipse, whatever):

rich_tree_standard

But I want this look:

rich_tree_customized

You see that the expand/collapse icon (rich_tree_expand) is on the same level with the node-icon (rich_tree_leaf). That’s very hard to fix this with CSS (it’s possible but i prefer my strange solution ;) ). The Richfaces documentation describes which parts of a tree could be customize.

We have:

  • rich-tree-node-handle and rich-tree-node-handleicon – a td which contains a link and a image to expand/collapse the node (only possible for a node not a leaf)
  • rich-tree-node-icon – is a td which contains the image for a node (a node with children)
  • rich-tree-node-icon-leaf – is a td which contains the image for a leaf (a node without children)

I decide to move the expand/collapse icon from the handle-td to the icon-td and “simulate” the user-click with Javascript:

rich_tree_expand_move

Listing 1 tree.xhtml:

<rich:tree id="tree"
              binding="#{treeBean.tree}"
              var="item"
              switchType="ajax"
              ajaxSubmitSelection="true"
              toggleOnClick="false"
              showConnectingLines="false"
              disableKeyboardNavigation="true">

    <f:facet name="iconCollapsed">
       <!-- no image for collapsed -->
       <rich:spacer width="0"  height="0" style="border: none;"/>
    </f:facet>
    <f:facet name="iconExpanded">
       <!-- no image for expanded -->
       <rich:spacer width="0"  height="0" style="border: none;"/>
    </f:facet>

    <f:facet name="icon">
       <!--  use normal node icon to toggle expand/collapse -->
       <h:panelGroup>
          <h:graphicImage value="#{item.isLeaf ? '/images/leaf.gif' : '/images/collapsed.gif'}"
                                 onclick="myToggleTreeNode(this);"
                                 rendered="#{!treeBean.isExpanded}"/>
          <h:graphicImage value="#{item.isLeaf ? '/images/leaf.gif' : '/images/expanded.gif'}"
                                 onclick="myToggleTreeNode(this);"
                                 rendered="#{treeBean.isExpanded}"/>
       </h:panelGroup>
    </f:facet>

    <f:facet name="iconLeaf">
       <h:graphicImage value="/images/leaf.gif"/>
    </f:facet>

    <rich:recursiveTreeNodesAdaptor roots="#{treeBean.roots}" var="item" nodes="#{item.children}">
       <rich:treeNode>
          <h:outputText value="#{item.name}"/>
       </rich:treeNode>
    </rich:recursiveTreeNodesAdaptor>
</rich:tree>

Listing 2 tree.js:

function myToggleTreeNode(element) {
  var elem = jQuery(element);
  // img -> span -> td
  var parent = elem.parent().parent();
  var elementId = parent.attr("id");
  // i.e. j_id31:tree:j__id39:18::j_id40:icon -> the td arround the icon-image
  var index = elementId.lastIndexOf(":icon");
  var treeNodeId = elementId.substring(0, index);
  // i.e. j_id31:tree:j__id39:18::j_id40:handle -> the td arround the original expand/collapse-image
  var handleId = treeNodeId+':handle';
  // pure jQuery not working here
  var expandElement = jQuery($(handleId));
  expandElement.trigger("click");
}

Listing 3 tree.css:

.rich-tree-node-handleicon {
  display: none;
}
Categories: JSF, Richfaces Tags: , , , ,

ViewExpiredException in JSF 1 and 2

Monday, 7. September 2009 Andreas Höhmann Leave a comment

Ed Burns beschreibt in seinem Blog wie man in JSF 2 selbst eine ViewExpiredException’s behandeln kann.

Momentan (JSF < 2) kann die Standard-Fehlerbehandlung natürlich auch angepasst werden, z.B. durch Festlegung einer bestimmten Location pro Exception-Typ:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  ...
  <error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/pages/error/sessionexpired.xhtml</location>
  </error-page>
  ...

In der von Ed vorgestellten Lösung wird ein eigener ViewExpiredExceptionHandler registriert, welcher den ursprünglichen Handler kapselt. In der dort überschriebenen void handle() wir eine ViewExpiredException mit einem Redirect (via Navigation-Handler) auf eine Fehlerseite beantwortet. In der Fehlerseite können Variable, die im Handler gesetzt wurden, für eine sinnvolle Fehlerbeschreibung verwendet werden.

Beim Einsatz von Richfaces kann man diese Art von Fehler auch auf der Clientseite behandeln, beschrieben wird dies im Detail hier. Das Ganze ist mit zwei Erweiterungen machbar:

1. die Funktion für den Client aktivieren

<context-param>
  <param-name>org.ajax4jsf.handleViewExpiredOnClient</param-name>
  <param-value>true</param-value>
</context-param>

2. den Javascript-Code für die Behandlung zur Verfügung stellen:

if (typeof(A4J) !== 'undefined' && typeof(A4J.AJAX) !== 'undefined'){
   // richfaces is available
   A4J.AJAX.onExpired = function(loc,expiredMsg) {
      var confirmMsg = 'Session expired.\n\nReload?';
      if (confirm(confirmMsg)) {
         window.location.reload();
      }
      // return false to inform "link-commands", that the user doesn't want to reload the page
      return false;
   };
};

Fadein and Fadeout a Richfaces ModalPanel

Wednesday, 22. July 2009 Andreas Höhmann Leave a comment

Today i explain you a cool combination for rich:modalPanel and rich:effect.

In the richfaces forum i found a article about a modalpanel with scriptaculous-effects (“fade-in a modalpanel”). The answer was a link to the official richfaces demo-application (photoalbum). There we can find a login-dialog (svn source) with a “appear-effect”:

<rich:modalPanel id="loginPanel"
onshow="applyModalPanelEffect('loginPanel', appearFunc,{delay: 0.5, afterFinish: function(){$('loginPanelForm:username').focus();}})"
styleClass="login-panel"
showWhenRendered="#{authenticator.loginFailed}"
width="400" height="150" autosized="true">
<f:facet name="header">#{messages['login.login']}</f:facet>
<f:facet name="controls">
<h:panelGroup id="loginPanelHideControl">
<h:graphicImage value="/img/modal/close.png" style="cursor:pointer"
id="loginPanelhidelink" onclick="#{rich:component('loginPanel')}.hide();"/>
</h:panelGroup>
</f:facet>
...
<rich:effect type="Appear" name="appearFunc"/>
...

The javascript method applyModalPanelEffect can be found in the photoalbum.js (svn source):

function applyModalPanelEffect(panelId, effectFunc, params) {
 if (panelId && effectFunc) {
 var modalPanel = $(panelId);
 if (modalPanel && modalPanel.component) {
 var component = modalPanel.component;
 var div = component.getSizedElement();
 Element.hide(div);
effectFunc.call(this, Object.extend({targetId: div.id}, params || {}));}}
}

With this the rich:modalPanel will not shown immediately … it appears ;-) This was the “fade-in part”.

I improved the code for the “fade-out part”, first the dialog:


<!-- first the effects -->
<rich:effect type="Appear" name="appearDialog"/>
 <rich:effect type="Fade" name="disappearDialog"/>

<!-- to keep the dialog-code clean -->
<c:set var="closeDialog" value="hideModalPanelWithEffect('myDialog',disappearDialog,{delay:0.1,duration:0.5})"/>

<rich:modalPanel id="myDialog"
 onshow="showModalPanelWithEffect('myDialog',appearDialog,{delay:0.1,duration:0.5})"
 width="610" height="350" minHeight="350" autosized="true" shadowDepth="0">
<f:facet name="controls">
<h:panelGroup>
<h:graphicImage value="/img/modal/close.png" style="cursor:pointer" onclick="#{closeDialog}"/>
</h:panelGroup>
</f:facet>
</rich:modalPanel>

and the javascript:

function applyModalPanelEffect(panelId, effectFunc, params, hide) {
 if (panelId && effectFunc) {
 var modalPanel = $(panelId);
 if (modalPanel && modalPanel.component) {
 var component = modalPanel.component;
 var div = component.getSizedElement();
 if (hide) {
 Element.hide(div);
 }
 effectFunc.call(this, Object.extend( {targetId : div.id}, params || {}));}}
}

function showModalPanelWithEffect(panelId, showEffect, params) {
 applyModalPanelEffect(panelId, showEffect, params, true);
}

function hideModalPanelWithEffect(panelId, hideEffect, params) {
 var _params = params;
_params['afterFinish'] = function(){Richfaces.hideModalPanel(panelId)};
 applyModalPanelEffect(panelId, hideEffect, params, false);
}

Now the dialog call showModalPanelWithEffect to fade-in and hideModalPanelWithEffect to fade-out.

Try it :D

Clear JSF Input Components

Monday, 22. June 2009 Andreas Höhmann Leave a comment

Beim Implementieren einer einfachen CRUD Anwendung mit Hilfe von Richfaces Datatable und ModalPanel bin ich über ein “Problem” mit validierten (leeren) Eingabefeldern gestolpert.

Das Problem ist eigentlich kein richtiges Problem, sondern das Standardverhalten von JSF :-) Unschön wird es wenn man einen rich:modalPanel als Edit-Dialog einsetzt und diesen wiederverwendet.

Der grobe Aufbau:

  • eine DataTable zeigt eine Liste von Entities (z.B. mit Hilfe eine DAOs geladen)
  • jedes Entity hat eine eindeutige ID (z.B. PrimaryKey aus JPA)
  • pro Tabellenzeile gibt es einen “Edit”-CommandLink der eine rich:modalPanel für das Editieren eines Entity öffnet
  • vor jedem Edit muss die gewünschte Entity in einen CrudManager (Session-Scoped Bean) gelangen, aus der sich der Edit-Dialog mit Daten versorgen kann und mit dessen Hilfe die eigentliche Edit-Aktion durchgeführt wird

Nun sollen bestimmte Eingabefelder im Edit-Dialog validiert werden (z.B. mit einer @NotEmpty Annotation an den ensprechenden Properties der Entitiy-Klasse). Wenn man nun den Dialog für eine Entity mir der ID ‘1′ öffnet und eine Validierungsfehler auslöst, z.B. durch das Abschicken mit leeren Eingabefeldern, wird dieser Fehler ausgegeben … soweit so gut. Der Dialog kann dann geschlossen werden. Soll nun Entity mit der ID ‘2′ mit dem gleichen Dialog editiert werden, sind die Eingabefelder immer noch leer und nicht wie gewünscht mit den Werten aus Entity-2 gefüllt. Warum?!

Nach einer kurzen Googlesuche landete ich auf der Seite http://wiki.apache.org/myfaces/ClearInputComponents die den Effekt beschreibt. Der Grund für das Verhalten ist die Zwischenspeicherung von “SubmitedValues” in den jeweiligen UIComponents (z.B. h:inputText). Die werden den eigentlichen Modeldaten vorgezogen.

Will man nun einen immer aktuellen Edit-Dialog haben, gibt es verschiedene Möglichkeiten (siehe MyFaces). Ich habe mich für die “radikal einfache” Lösung entschieden … lösche alle Elemente innerhalb des Edit-Dialogs und lasse sie immer neu erzeugen.

Die Entity-Liste besteht aus einer rich:dataTable, pro Zeile ein a4j:commandButton:


<rich:dataTable value="#{tableManager.model}" var="dataItem">

<!-- Edit-Command Column -->
<rich:column sortable="false">
<a4j:commandButton ajaxSingle="true" limitToList="true"
reRender="foobar_editPanel"
oncomplete="Richfaces.showModalPanel('foobar_editPanel')"
 actionListener="#{crudManager.onEdit}">
 <f:attribute name="onEditClearTarget" value="foobar_editPanel"/>
 <f:setPropertyActionListener value="#{dataItem}" target="#{crudManager.currentEntity}" />
</a4j:commandButton>

<!-- more Columns ... -->
</rich:dataTable>

Der tableManager liefert die Entity-Daten, also eine Liste von Entity-Beans, jede Bean hat eine eindeutige ID. Der crudManager enthält stellt die gesamte CRUD Funktionalität zur Verfügung. Für eine Edit muss er mit einer Entity “initialisiert” werden, dies geschieht via f:setPropertyActionListener. Das reRender bewirkt, dass der Edit-Dialog aktuallisiert wird.

Der Edit-Dialog wird mit Hilfe von rich:modalPanel erzeugt (foobar_editPanel) und enthält eine Reihe von h:inputText Elementen. Diese sind wiederum an den crudManager gebunden.

Der Code für das Zurücksetzen der Inputelemente im Edit-Dialog ist ebenfalls im crudManager verborgen und sieht folgendermaßen aus:


public abstract class AbstractCrudManager {

public static final String ONEDIT_ATTRIBUTE_CLEARTARGET = "onEditClearTarget"; //$NON-NLS-1$

/**
 * Event-handler will be triggered on <tt>edit</tt>. This method is used as a
 * {@link ActionListener} and will be called before a <tt>edit-view</tt> is
 * shown. So here we can do some "initializations" for the edit-view, i.e.
 * reset input-fields.
 *
 *
 * This base implementation will call {@link #clearEditTarget(UIComponent)}.
 *
 *
 * @param aEvent
 *          is never <code>null</code>
 */
public void onEdit(final ActionEvent aEvent) {
clearEditTarget(aEvent.getComponent());
 }

/**
 * This method handle a edit-form-clear. Per default the command-button which delegates to the
 * edit-view could have a attribute {@link #ONEDIT_ATTRIBUTE_CLEARTARGET}.
 *
 * @param theSourceComponent
 *          is never <code>null</code>
 */
 protected void clearEditTarget(final UIComponent theSourceComponent) {
 final String onEditTarget = (String) theSourceComponent.getAttributes().get(ONEDIT_ATTRIBUTE_CLEARTARGET);
 if (onEditTarget == null) {
 return;
 }
 final UIComponent editTarget = FacesContext.getCurrentInstance().getViewRoot().findComponent(onEditTarget);
 if (editTarget == null) {
 return;
 }
 editTarget.getChildren().clear();
 }

...

}

Damit ist auch klar was das <f:attribute name=”onEditClearTarget” value=”#{id}_editPanel”/> bewirkt … es definiert die UI-Komponente die vor dem Öffnen des Dialogs zurückgesetzt werden soll.

Damit wird bei jedem Klick auf “Edit” ein Ajax-Request zum Server geschickt, dort wird die aktuelle Entity in den crudManager hinterlegt, es wird onEdit aufgerufen und damit der Inhalt des Edit-Dialogs gelöscht. JSF sorgt dann beim RenderResponse wieder dafür, dass alle UI Componenten korrekt erzeugt werden. Da dann alle Eingabeelement noch vollkommen “neu” sind, zeigen diese auch die Werte aus dem Modell an.

Categories: JSF, Richfaces Tags: , , , ,

Realworld JSF Application Story

Monday, 27. April 2009 Andreas Höhmann Leave a comment

Vielleicht hatte ich es in einem früheren Posting schonmal erwähnt, ich arbeite momentan für Siemens an einem Web 2.0 Projekt und das ist jetzt fertig :D .

Los ging es November 2007 und nun konnten wir planmässig im April 2009 live gehen. Wir konnten dabei all die wunderbaren “neuen” Technologien einsetzen und ausprobieren, u.a. JSF und damit eine funktionsfähige (also den Anforderungen des Kunden voll entsprechende) und zugleich performante “Web 2.0″ Applikation bauen. Die Applikation nimmt sich dem Thema “Sicherheitstechnik” (für die Auskenner: ISO 13849-1 und IEC 62061) an.

Mal kurz zu den verwendeten “Technologien/Frameworks/Tools/Ideen”:

  • Daten ziehen wir aus einer SAP Knowledgebase (selbst gestrickt) und aus einer Datenbank via OpenJPA
  • Services/Manager sind “normale” Javaklassen (Stichwort Design-Pattern),
    als Kleber verwenden wir Spring (Stichwort Dependency Injection)
  • UI mit JBoss Richfaces (Stichwort Ajax), JSF + Facelets (Stichwort Xhtml-Template), jQuery, CSS, etc.
  • Buildsystem, Projektseiten mit Maven2
  • Continues Integration via TeamCity und Maven2
  • Tests hauptsächlich mit TestNG aber teilweise auch mit JUnit
  • Laden/Speichern von Benutzerdaten via XStream (FileupLoad via Tomahawk), das alles noch Versionskompatibel, d.h. selbsgestrickte XML-Transformationskette für DomainModell-Updates
  • PDF Reportgenerierung mit iText
  • Anbindung an Siemens “Single Sign On” System via Spring Security, Webservices

Im Rückblick kann ich sagen, dass eigentlich alles ohne größere Probleme miteinander funktioniert hat
… so soll es sein :D

https://www.automation.siemens.com/cd/safety/html_00/produkte/si_normen/tool.htm

(Für die Applikation muss man sich registrieren)

Show Richfaces Version

Wednesday, 4. March 2009 Andreas Höhmann Leave a comment

Richfaces provide his version in the el-variable a4j.

So put a #{a4j} in a facelets-template and you will see a version-string like this

Jboss Richfaces by richfaces.org, version v.3.3.0.GA SVN $Revision: 12244 $ $Date: 2009-01-13 05:40:53 +0200 $

Categories: JSF, Richfaces Tags:

Richfaces internal Tree Node Selection Howto

Tuesday, 9. September 2008 Andreas Höhmann Leave a comment

Waffel beschreibt in seinem neuesten Blogbeitrag wie man den Richfaces Tree auch aus dem System heraus ansprechen kann um eine bestimmte Node zu selektieren und sichtbar zu machen. So auf anhieb findet sich bisher keine vernünftige Dokumentation zu dem Thema.

Er kombiniert in seinem Beispiel den Tree mit einem TreeNodeAdapter (um das lästige Erstellen der Nodeklassen zu überspringen) und benutzt schließlich einen TreeWalker um die gewünschte Node zu finden und aufzuklappen.

Vielleicht wird in einer der nächsten RF-Versionen das Handling mit dem Baum ja noch einfacher. Aus Benutzersicht (UI) läßt der Baum ja kaum noch Wünsche offen. Serverseitig sieht es da schon etwas dünner aus. Aber wenn man sich einmal bissl tiefer reingewühlt hat, wird auch da manches klarer :D

Categories: JSF, Richfaces Tags: , , , ,

Masked Input with Richfaces

Tuesday, 19. August 2008 Andreas Höhmann Leave a comment

I would like to define a input-mask for a inputfield, e.g. for a telefonnumber or number in scientific notation (1.23 E-10). A nice way could be the usage of a special “css-class” to mark the masked-input-elements and the usage of the alt-attribute to define the mask-format. Here is my solution:

First of all we need a little bit Javascript, i use the Masked Input Component from Jonas Raoni Soares Silva:


addEvent = function(o, e, f, s){
var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
r[r.length] = [f, s || o], o[e] = function(e){
try{
(e = e || (window.event ? (arguments = [].slice.call(arguments)).unshift(e = event) || 1 &amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp; e : {})).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
e.target || (e.target = e.srcElement || null);
e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
}catch(f){}
for(d = 1, f = r.length; f; r[--f] &amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp; (a = r[f][0], o = r[f][1], a.apply ? c = a.apply(o, arguments) : (o._ = a, c = o._(e), o._ = null), d &amp;amp;amp;amp;amp;amp;amp;amp;amp;= c !== false));
return e = null, !!d;
}
};
removeEvent = function(o, e, f, s){
for(var i = (e = o["_on" + e] || []).length; i;)
if(e[--i] &amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp; e[i][0] == f &amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp; (s || o) == e[i][1])
return delete e[i];
return false;
};
MaskInput = function(f, m){
function mask(e){
var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[\xC0-\xFF]/i, "8": /./ },
rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
function accept(c, rule){
for(var i = 1, r = rules[rule] || 0; i &amp;amp;amp;amp;amp;amp;amp;amp;lt;= r; i&amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;lt;=1)
if(r &amp;amp;amp;amp;amp;amp;amp;amp;amp; i &amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp; patterns[i].test(c))
break;
return i &amp;amp;amp;amp;amp;amp;amp;amp;lt;= r || c == rule;
}
var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
(!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) &amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp; (r[0] = r[2].indexOf(c) + 1) + 1 ?
r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
: (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
r.index : l)).length) &amp;amp;amp;amp;amp;amp;amp;amp;lt; m.length &amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp; accept(c, m.charAt(l))) || e.preventDefault();
};
for(var i in !/^(.)\^(.*)$/.test(m) &amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp; (f.maxLength = m.length), {keypress: 0, keyup: 1})
addEvent(f, i, mask);
};

then we define the inputfield:

<h:inputText styleClass="maskedInput" alt="9,99 E-99"/>

and last a little bit JS-Code which decorates the current formulare after each rerender, but it at the end of your page:

<a4j:outputPanel ajaxRendered="true">
  <script type="text/javascript">
   var maskedInput=$$(".maskedInput");
   if (Object.isArray(maskedInput)){
     maskedInput.each(function (elm){
     // input-mask is defined in the alt element
     var maskPattern = Element.readAttribute(elm, "alt");
     MaskInput(elm, maskPattern);
     });
   }
  </script>
</a4j:outputPanel>

That's it :) Every time A4J rerenders the page the decorator search all marked elements and creates a MaskInput object for the elements.

Try it!

Categories: JSF, Richfaces Tags: , ,