<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Martin Ahrer - Together we&#039;ll make IT &#187; JavaServer Faces</title>
	<atom:link href="http://www.martinahrer.at/tag/javaserver-faces/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.martinahrer.at</link>
	<description>Java Enterprise Softwareentwicklung und Consulting</description>
	<lastBuildDate>Sun, 11 Dec 2011 16:19:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
<meta name="generator" content="deSignum 0.8.1" />
		<item>
		<title>A simple ViewController for JSF</title>
		<link>http://www.martinahrer.at/2010/05/18/a-simple-viewcontroller-for-jsf/</link>
		<comments>http://www.martinahrer.at/2010/05/18/a-simple-viewcontroller-for-jsf/#comments</comments>
		<pubDate>Tue, 18 May 2010 11:14:40 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=428</guid>
		<description><![CDATA[Very early Apache Shale came up with the idea of providing a view controller that allowed to execute dedicated methods (annotated, etc.) during various JSF life-cycle (phase) events for doing initialization work upfront for example. As Shale was hibernated, Apache Orchestra stepped in and added many more useful features. Both frameworks are based on the [...]]]></description>
			<content:encoded><![CDATA[<p>Very early <a href="http://shale.apache.org/">Apache Shale</a> came up with the idea of providing a view controller that allowed to execute dedicated methods (annotated, etc.) during various JSF life-cycle (phase) events for doing initialization work upfront for example. As Shale was hibernated, <a href="http://myfaces.apache.org/orchestra/myfaces-orchestra-core/viewController.html">Apache Orchestra</a> stepped in and added many more useful features.<br />
Both frameworks are based on the idea of having a dedicated page bean (a JSF managed bean per view) that would control important processing steps for the entire view (page).<br />
It requires following naming conventions in order to associate a page bean to a view, optionally a view controller mapper provided the ability of explicitely associating page beans and views.</p>
<p><span id="more-428"></span><br />
In many projects I found the situation that the client didn&#8217;t want to pull in another framework just for that little feature.  Also for distributing responsibilities, I usually have multiple managed beans per view. So another &#8220;artificial&#8221; page bean is required just for controlling the others. So I came up with a fairly simple solution that allows to directly invoke those life-cycle callbacks on any managed bean used on a single page.</p>
<p>The &lt;f:phaseListener&gt; tag allows to bind a JSF <a href="http://javadoc.glassfish.org/v3/apidoc/javax/faces/event/PhaseListener.html">PhaseListener</a>. You can even bind multiple phase listeners (one for each managed bean; you get the idea).</p>
<pre class="brush:xml">
&lt;f:phaseListener binding="#{bean1.viewControllerPhaseListener}" /&gt;
&lt;f:phaseListener binding="#{bean2.viewControllerPhaseListener}" /&gt;
</pre>
<p>So each of the beans would provide a reference to a phase listener that would take care to perform the proper processing for the bean itself. Every bean then would use a set of annotations (like @PreRenderView, @PostRestoreView, @PreInvokeApplication, etc.) to mark those methods that should be called during a specific phase.</p>
<pre class="brush:java">
public class EntityListController&lt;T&gt; {
	private volatile ViewControllerPhaseListener viewControllerPhaseListener;

	public ViewControllerPhaseListener getViewControllerPhaseListener() {
		if (viewControllerPhaseListener == null) {
			viewControllerPhaseListener = new ViewControllerPhaseListener(this);
		}
		return viewControllerPhaseListener;
	}

	@PreRenderView
	public void updateModel() {
		...
	}

	...
</pre>
<p>The code above is partially showing a base class from which many of my managed bean are subclassed. Key is the ViewControllerPhaseListener which hides all of the details of doing the reflection job for finding (and then caching) the annotated methods to invoke during a specific phase. For brevity I&#8217;m showing only the key elements of this class.</p>
<pre class="brush:java">
public class ViewControllerPhaseListener implements PhaseListener {
	private final Object target;

	public ViewControllerPhaseListener(Object target) {
		super();
		this.target = target;
	}

	private final Class&lt;Annotation&gt;[] LIFECYCLE_ANNOTATIONS = new Class[] { PreRenderView.class, PostRestoreView.class,
		PreInvokeApplication.class };

	private final static Map&lt;Class&lt;?&gt;, Map&lt;Class&lt;? extends Annotation&gt;, Set&lt;Method&gt;&gt;&gt; controllerClasses = new ConcurrentHashMap&lt;Class&lt;?&gt;, Map&lt;Class&lt;? extends Annotation&gt;, Set&lt;Method&gt;&gt;&gt;();

	static Map&lt;Class&lt;?&gt;, Map&lt;Class&lt;? extends Annotation&gt;, Set&lt;Method&gt;&gt;&gt; getControllerClasses() {
		return controllerClasses;
	}

	@Override
	public void beforePhase(PhaseEvent event) {
		if (PhaseId.RENDER_RESPONSE.equals(event.getPhaseId())) {
			invokeAnnotatedMethod(PreRenderView.class, target);
		} else if (PhaseId.INVOKE_APPLICATION.equals(event.getPhaseId())) {
			invokeAnnotatedMethod(PreInvokeApplication.class, target);
		}
	}

	@Override
	public void afterPhase(PhaseEvent event) {
		if (PhaseId.RESTORE_VIEW.equals(event.getPhaseId())) {
			invokeAnnotatedMethod(PostRestoreView.class, target);
		}
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.ANY_PHASE;
	}

	void invokeAnnotatedMethod(Class&lt;? extends Annotation&gt; annotation, Object targetObject) {
		if (!controllerClasses.containsKey(targetObject.getClass())) {
			registerController(targetObject.getClass());
		}
		for (Method method : controllerClasses.get(targetObject.getClass()).get(annotation)) {
			try {
				method.invoke(targetObject);
			} catch (Exception e) {
				LOGGER.error("Error invoking @{} annotated method {} on {}", new Object[] { annotation.getSimpleName(),
						method, targetObject });
				throw new RuntimeException(e);
			}
		}
	}

	public void registerController(Class&lt;?&gt; controllerClass) {
		// do the reflection work
	}
}
</pre>
<p>In a few projects this has proven to be quite versatile. Currently I have a couple of interesting phase listener components, from the simple DebugPhaseListener to the OpenTransactionInViewPhaseListener. I can just throw them into any view as they are required.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2010/05/18/a-simple-viewcontroller-for-jsf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The dreading timezone issue with JSF and how it hits you again with daylights saving</title>
		<link>http://www.martinahrer.at/2010/01/07/the-dreading-timezone-issue-with-jsf-and-how-it-hits-you-again-with-daylights-saving/</link>
		<comments>http://www.martinahrer.at/2010/01/07/the-dreading-timezone-issue-with-jsf-and-how-it-hits-you-again-with-daylights-saving/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 10:51:49 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[timezone]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=386</guid>
		<description><![CDATA[JSF is converting all date/datetime types into GMT base for rendering. This can cause a date offset of n-hours to be shown depending on the timezone you are in. You have 2 choices to deal with it: Either you implement an application wide (global) date converter as described here or you add the timezone attribute [...]]]></description>
			<content:encoded><![CDATA[<p>JSF is converting all date/datetime types into GMT base for rendering. This can cause a date offset of n-hours to be shown depending on the timezone you are in. You have 2 choices to deal with it:<br />
Either you implement an application wide (global) date converter as described <a href="http://www.coderanch.com/t/212267/JSF/java/MyFaces-Date-TimeZone-Issue">here </a>or you add the timezone attribute to each of the convertDateTime tags.<br />
<span id="more-386"></span></p>
<pre class="brush:xml">
&lt;h:outputText value="#{day.date}"&gt;
	&lt;f:convertDateTime type="date" pattern="dd.MM.yyyy" timeZone="#{viewController.timeZoneId}"/&gt;
&lt;/h:outputText&gt;
</pre>
<p>The latter approach allows to have a single point of detecting a users timezone preference (unfortunately the timezone is not included in the HTTP header) but requires to have the timezone attribute implemented in multiple places.</p>
<p>So far so good. Many solutions propose using the timezone offset based timezone identifier which turns out to be bad. It doesn&#8217;t allow the JDK date formatters to properly apply the daylight settings. So better use &#8220;Europe/Vienna&#8221; instead of &#8220;GMT+1&#8243;. It even looks like there were some subtle <a href="http://www.mail-archive.com/dev@myfaces.apache.org/msg39804.html">changes </a>with turning from JDK 1.5 to JDK 1.6 regarding this.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2010/01/07/the-dreading-timezone-issue-with-jsf-and-how-it-hits-you-again-with-daylights-saving/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extending the FacesContext (and using a Faces Factory)</title>
		<link>http://www.martinahrer.at/2009/12/23/extending-the-facescontext-and-using-a-faces-factory/</link>
		<comments>http://www.martinahrer.at/2009/12/23/extending-the-facescontext-and-using-a-faces-factory/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 17:21:05 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=378</guid>
		<description><![CDATA[JavaServer Faces has always been sold as a piece of flexible and extensible code. It really is. Through its factory facilities you can bend and twist that web framework until it fits. Today I tried to resolve something that has bothered me a long time. For a showcase I have implemented a few supporting lines [...]]]></description>
			<content:encoded><![CDATA[<p>JavaServer Faces has always been sold as a piece of flexible and extensible code. It really is. Through its factory facilities you can bend and twist that web framework until it fits. Today I tried to resolve something that has bothered me a long time. For a showcase I have implemented a few supporting lines of code that come handy in lots of places. When prototyping something, that code often ends up in some abstract base class from which managed bean are subclassed or it even ends up in some &#8220;helper&#8221; class with static methods. In the end you don&#8217;t feel that it is at the right place.<br />
<span id="more-378"></span><br />
The example I&#8217;m showing now is trying to detect if a request validated with some severe message.</p>
<pre class="brush:java">
public boolean isSevereMessage() {
	Severity severity = FacesContext.getCurrentInstance().getMaximumSeverity();
	return severity == null ? false : severity.compareTo(FacesMessage.SEVERITY_INFO) > 0;
}
</pre>
<p>Seems that could go into the FacesContext implementation, right? In order to get there you need a <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/javax/faces/context/FacesContextFactory.html">FacesContextFactory </a>that instantiates your <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/javax/faces/context/FacesContext.html">FacesContext </a>implementation.</p>
<p>The FacesContextFactory is setup by a <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/javax/faces/FactoryFinder.html">FactoryFinder </a>which supports quite a few strategies for picking up the factory.</p>
<pre class="brush:java">
public class BlueprintFacesContextFactory extends FacesContextFactory {
	private final FacesContextFactory factory;
	public BlueprintFacesContextFactory(FacesContextFactory factory) {
		super();
		this.factory = factory;
	}
	@Override
	public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle)
			throws FacesException {
		return new BlueprintFacesContext(factory.getFacesContext(context, request, response, lifecycle));
	}
}
</pre>
<p>By implementing a constructor that takes a FacesContextFactory as argument we can easily get hold of the factory provided by the JSF implementation and delegate.</p>
<p>For our FacesContext implementation the deal is to wrap the existing FacesContext with your own implementation. Therefore it also implements a constructor taking a Facescontext as argument.</p>
<pre class="brush:java">
public class BlueprintFacesContext extends FacesContext {
	private final FacesContext context;
	public BlueprintFacesContext(FacesContext context) {
		super();
		this.context = context;
		setCurrentInstance(this);
	}

	/**
	 * Test if a request processing resulted in a severe message. A message is
	 * considered severe if it is more severe than INFO.
	 *
	 * @return true if
	 *         &lt;code&gt;maximumSeverity.compareTo(FacesMessage.SEVERITY_INFO) &gt; 0&lt;/code&gt;
	 */
	public boolean isSevereMessage() {
		Severity severity = getMaximumSeverity();
		return severity == null ? false : severity.compareTo(FacesMessage.SEVERITY_INFO) > 0;
	}
	@Override
	public ELContext getELContext() {
		ELContext elContext = context.getELContext();
		elContext.putContext(FacesContext.class, this);
		return elContext;
	}
	//other methods stripped for brevity, they only delegate to context!
</pre>
<p>With JSF2 a <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/javax/faces/context/FacesContextWrapper.html">FacesContextWrapper</a> is provided so only those methods need to overridden that are required to add the desired behaviour.<br />
Here I needed to override getELContext in order to make the custom FacesContext available in EL expressions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2009/12/23/extending-the-facescontext-and-using-a-faces-factory/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Close a PrimeFaces dialog when no validation messages are available</title>
		<link>http://www.martinahrer.at/2009/12/03/close-a-primefaces-dialog-when-no-validation-messages-are-available/</link>
		<comments>http://www.martinahrer.at/2009/12/03/close-a-primefaces-dialog-when-no-validation-messages-are-available/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 21:45:19 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[PrimeFaces]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=372</guid>
		<description><![CDATA[I&#8217;m posting this to memorize a PrimeFaces pattern for reuse. The visibility of PrimeFaces dialog panel can be controlled using the visible attribute. JavaScript widget.open() or widget.hide() modify the visibility state as well. &#60;p:dialog widgetVar="widget" id="dialog" visible="#{not empty facesContext.maximumSeverity}"&#62; &#60;f:facet name="header"&#62; &#60;h:outputText value="Form" /&#62; &#60;/f:facet&#62; &#60;h:form&#62; &#60;h:panelGrid columns="3"&#62; &#60;h:outputLabel for="input" value="Input" /&#62; &#60;h:inputText id="input" label="Input" [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m posting this to memorize a PrimeFaces pattern for reuse. The visibility of PrimeFaces dialog panel can be controlled using the <strong>visible</strong> attribute.  JavaScript widget.open() or widget.hide() modify the visibility state as well.</p>
<pre class="brush:xml">
&lt;p:dialog widgetVar="widget" id="dialog"
	visible="#{not empty facesContext.maximumSeverity}"&gt;
	&lt;f:facet name="header"&gt;
		&lt;h:outputText value="Form" /&gt;
	&lt;/f:facet&gt;
	&lt;h:form&gt;
		&lt;h:panelGrid columns="3"&gt;
			&lt;h:outputLabel for="input" value="Input" /&gt;
			&lt;h:inputText id="input" label="Input" required="true" value="VALUE" /&gt;
			&lt;h:message for="input" /&gt;
		&lt;/h:panelGrid&gt;

		&lt;h:panelGroup&gt;
			&lt;!-- update the form for the case we get validation errors --&gt;
			&lt;p:commandButton value="Update" update="dialog"/&gt;
		&lt;/h:panelGroup&gt;
	&lt;/h:form&gt;
&lt;/p:dialog&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2009/12/03/close-a-primefaces-dialog-when-no-validation-messages-are-available/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Change appearance of UI elements based on validation results</title>
		<link>http://www.martinahrer.at/2009/11/05/change-appearance-of-ui-elements-based-on-validation-results/</link>
		<comments>http://www.martinahrer.at/2009/11/05/change-appearance-of-ui-elements-based-on-validation-results/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 22:29:34 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Facelets]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=310</guid>
		<description><![CDATA[In my previous post I showed how simple it is to control rendering of UI elements based on validation results. Today I want to put this idea a little bit further and add another convenicent facelets tag that will allow to assign a style class to any UI element based on validation results. In order [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.martinahrer.at/2009/10/20/control-rendering-of-ui-elements-based-on-validation-results/">previous</a> post I showed how simple it is to control rendering of UI elements based on validation results.</p>
<p>Today I want to put this idea a little bit further and add another convenicent facelets tag that will allow to assign a style class to any UI element based on validation results. In order to create an appealing form that clearly indicates the position where validation fails very often you see that input elements change their visual appearance based on the validation state. For example any invalid input element is shown with red background. With no component you end up with tedious (or complex) EL expressions that are assigned to the <em>styleClass </em>attribute.</p>
<p>To make that concept reusable and simple to apply I show how to create a facelets tag <strong>setStyleClassIfMessages</strong> that evaluates the faces messages available for a specific component, looks for the message with highest severity and uses the severity to apply a CSS style class to any component.</p>
<pre class="brush:xml">
<h:outputLabel for="amount" value="Amount" />
<h:inputText label="Amount" id="amount" value="#{mbean.amount}" required="true">
	<f:convertNumber maxFractionDigits="2" minFractionDigits="2" currencySymbol="€" />
	<b:setStyleClassIfMessages for="amount"
		infoClass="validationInfo" warnClass="validationWarn" 	errorClass="validationError" fatalClass="validationFatal" />
</h:inputText>
</pre>
<p>The tag implementation is quite straightforward, I have stripped some obvious details from the code.</p>
<pre class="brush:java">
public class SetStyleClassIfMessagesTagHandler extends MessagesTagHandler {

	protected final TagAttribute[] classAttributes = new TagAttribute[5];

	public SetStyleClassIfMessagesTagHandler(TagConfig config) {
		super(config);
		classAttributes[0] = getAttribute("passedClass");
		classAttributes[FacesMessage.SEVERITY_INFO.getOrdinal() + 1] = getAttribute("infoClass");
		classAttributes[FacesMessage.SEVERITY_WARN.getOrdinal() + 1] = getAttribute("warnClass");
		classAttributes[FacesMessage.SEVERITY_ERROR.getOrdinal() + 1] = getAttribute("errorClass");
		classAttributes[FacesMessage.SEVERITY_FATAL.getOrdinal() + 1] = getAttribute("fatalClass");
	}

	public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException,
			ELException {
		if (forAttribute != null) {
			UIComponent forComponent = getForComponent(ctx.getFacesContext(), forAttribute.getValue(ctx), parent);
			if (forComponent != null) {
				setMaximumSeverityStyleClass(ctx, forComponent);
			} else {
				LOGGER.warn("No component {} found.", forAttribute.getValue(ctx));
			}
		} else if (parent != null) {
			setMaximumSeverityStyleClass(ctx, parent);
		}
	}

	private void setMaximumSeverityStyleClass(FaceletContext ctx, UIComponent forComponent) {
		FacesMessage message = findMostSevereMessage(ctx.getFacesContext(), forComponent);
		if (PropertyUtils.isWriteable(forComponent, STYLE_CLASS_PROPERTY_NAME)) {
			TagAttribute messageStyleClass = message == null ? classAttributes[0] : classAttributes[message
					.getSeverity().getOrdinal() + 1];
			try {
				StringBuilder newStyleClass = new StringBuilder(messageStyleClass == null ? "" : messageStyleClass
						.getValue(ctx));
				// read style and remove style class from previous post-back,
				// then set new style class
				String oldStyleClass = (String) PropertyUtils
						.getSimpleProperty(forComponent, STYLE_CLASS_PROPERTY_NAME);

				Set&lt;String&gt; classNames = new HashSet&lt;String&gt;();
				for (TagAttribute classAttribute : classAttributes) {
					if (classAttribute != null) {
						classNames.add(classAttribute.getValue());
					}
				}
				StringTokenizer tokenizer = new StringTokenizer(oldStyleClass == null ? "" : oldStyleClass, " ");
				while (tokenizer.hasMoreElements()) {
					String styleClass = tokenizer.nextToken();
					if (classNames.contains(styleClass)) {
						continue;
					}
					newStyleClass.append(' ').append(styleClass);
				}
				PropertyUtils.setSimpleProperty(forComponent, STYLE_CLASS_PROPERTY_NAME, newStyleClass.toString());
			} catch (Exception e) {
				throw new FaceletException(e);
			}
		}
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2009/11/05/change-appearance-of-ui-elements-based-on-validation-results/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Control rendering of UI elements based on validation results</title>
		<link>http://www.martinahrer.at/2009/10/20/control-rendering-of-ui-elements-based-on-validation-results/</link>
		<comments>http://www.martinahrer.at/2009/10/20/control-rendering-of-ui-elements-based-on-validation-results/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 19:05:54 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[PrimeFaces]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=271</guid>
		<description><![CDATA[In this post I describe how I tackled a problem that I faced quite often in the past. I need control over rendering a part of the UI based on validation results. E.g. when there is a validation message available for a certain input component then render a tooltip (containing a validation message) for the [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I describe how I tackled a problem that I faced quite often in the past. I need control over rendering a part of the UI based on validation results. E.g. when there is a validation message available for a certain input component then render a tooltip (containing a validation message) for the component.</p>
<p>JSF components offer a boolean rendered attribute that allows controling the rendering process. For complex decisions that means that a method on a managed bean would calculate the resulting state.</p>
<p>Exactly that was the solution that I was starting with for the problem described above.</p>
<pre class="brush:java">
public Map&lt;String, Boolean&gt; getHasMessages() {
	HashMap&lt;String, Boolean&gt; flags = new HashMap&lt;String, Boolean&gt;(1);
	Iterator&lt;String&gt; messages = FacesContext.getCurrentInstance().getClientIdsWithMessages();
	while (messages.hasNext()) {
		flags.put(messages.next(), Boolean.TRUE);
	}
	return flags;
}
</pre>
<pre class="brush:xml">
&lt;h:inputText label="Amount" id="amount" &gt;
	&lt;p:tooltip for="amount" showEvent="focus" hideEvent="blur" rendered="#{mbean.hasMessages['amount']}"&gt;
		&lt;h:message for="amount" /&gt;
	&lt;/p:tooltip&gt;
&lt;/h:inputText&gt;
</pre>
<p>So I had a simple solution working fairly quickly. But let&#8217;s face it: It&#8217;s a clumsy solution that is hard to reuse and breaks when the id of the ui container around the input is changed.</p>
<p>To improve that, I decided that this requires a component that would be simple to reuse. As I&#8217;m using Facelets for the view I updated my knowledge of their support for custom components.</p>
<pre class="brush:java">
public class IfMessagesTagHandler extends TagHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(IfMessagesTagHandler.class);
	private static final String FOR_ATTRIBUTE_NAME = "for";
	private final TagAttribute forAttribute;

	public IfMessagesTagHandler(TagConfig config) {
		super(config);
		forAttribute = getAttribute(FOR_ATTRIBUTE_NAME);
	}

	public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException,
			ELException {
		if (forAttribute != null) {
			UIComponent forComponent = getForComponent(ctx.getFacesContext(), forAttribute.getValue(ctx), parent);
			if (forComponent != null) {
				if (ctx.getFacesContext().getMessages(forComponent.getClientId(ctx.getFacesContext())).hasNext()) {
					this.nextHandler.apply(ctx, parent);
				}
			} else {
				LOGGER.warn("No component {} found.", forAttribute.getValue(ctx));
			}
		} else if (parent != null) {
			if (ctx.getFacesContext().getMessages(parent.getClientId(ctx.getFacesContext())).hasNext()) {
				this.nextHandler.apply(ctx, parent);
			}
		}
	}
}
</pre>
<p>The above implementation accepts the optional attribute for that refers to a component id for which it tests if messages are available. In case the for attribute was not passed the tag would assume that the component to test for messages is the enclosing parent tag.</p>
<p>To register the tag handler a facelets tag library descriptor in META-INF is required.</p>
<pre class="brush:xml">
&lt;?xml version="1.0"?&gt;

&lt;!DOCTYPE facelet-taglib PUBLIC
  "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
  "http://java.sun.com/dtd/facelet-taglib_1_0.dtd"&gt;

&lt;facelet-taglib&gt;
	&lt;namespace&gt;http://martinahrer.at/jsf/facelets/blueprint&lt;/namespace&gt;
	&lt;tag&gt;
		&lt;tag-name&gt;ifMessages&lt;/tag-name&gt;
		&lt;handler-class&gt;at...view.facelets.IfMessagesTagHandler&lt;/handler-class&gt;
	&lt;/tag&gt;
&lt;/facelet-taglib&gt;
</pre>
<p>A client would use that tag as:</p>
<pre class="brush:xml">
&lt;h:inputText label="Amount" id="amount" value="#{expenseSlipFormController.entity.amount}" required="true"&gt;
	&lt;b:ifMessages &gt;
		&lt;p:tooltip for="amount" showEvent="focus" hideEvent="blur" style="myStyle"&gt;
			&lt;h:message for="amount" /&gt;
		&lt;/p:tooltip&gt;
	&lt;/b:ifMessages&gt;
&lt;/h:inputText&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2009/10/20/control-rendering-of-ui-elements-based-on-validation-results/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>PhaseListener rendering a binary document (PDF)</title>
		<link>http://www.martinahrer.at/2009/09/27/jsf-phaselistener-rendering-a-binary-document-pdf/</link>
		<comments>http://www.martinahrer.at/2009/09/27/jsf-phaselistener-rendering-a-binary-document-pdf/#comments</comments>
		<pubDate>Sun, 27 Sep 2009 19:45:41 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=252</guid>
		<description><![CDATA[Inspired by Cagatay Civici’s idea of having a phase listener rendering images I decided to replace my PDF rendering servlets from a product that I&#8217;m currently working on. At the end of the RESTORE_VIEW phase the listener would decode the request URL and extract a managed property reference expression, create an EL expression and get [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by <a href="http://cagataycivici.wordpress.com/2006/02/16/phaselistener_renders_an_image_no/">Cagatay Civici’s idea</a> of having a phase listener rendering images I decided to replace my PDF rendering servlets from a product that I&#8217;m currently working on.</p>
<p>At the end of the RESTORE_VIEW phase the listener would decode the request URL and extract a managed property reference expression, create an EL expression and get the byte array for the binary document.</p>
<pre class="brush:java; wrap-lines:false">
	public void afterPhase(PhaseEvent event) {
		String viewId = event.getFacesContext().getViewRoot().getViewId();
		if (viewId.startsWith(PDF_STREAM_VIEW_ID_PREFIX)) {
			String streamExpression = StringUtils.substringAfter(viewId, PDF_STREAM_VIEW_ID_PREFIX);
			ELContext elContext = event.getFacesContext().getELContext();

			byte[] bytes = (byte[]) event.getFacesContext().getApplication().getExpressionFactory()
					.createValueExpression(elContext, "#{" + streamExpression + "}", byte[].class).getValue(elContext);
			if (bytes != null) {
				HttpServletResponse response = (HttpServletResponse) event.getFacesContext().getExternalContext()
						.getResponse();
				response.setContentType("application/pdf");
				response.setContentLength(bytes.length);

				try {
					response.getOutputStream().write(bytes);
				} catch (Exception exception) {
					LOG.error(exception.getMessage());
				}
			}
			event.getFacesContext().responseComplete();
		}
	}
</pre>
<p>To display the binary document a matching URL needs to be generated. Here the &lt;object&gt; tag is used for displaying a PDF document. The URL part after &#8220;/pdf/stream/&#8221; is used as a part of a value expression for referencing the actual PDF binary document (here it is managedBeanName.propertyName).</p>
<pre class="brush:java">
<p:panel>
	&lt;object
		data="#{facesContext.externalContext.requestContextPath}/#{facesContext.externalContext.requestServletPath}/pdf/stream/managedBeanName.propertyName"
			type="application/pdf" /&gt;
</p:panel>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2009/09/27/jsf-phaselistener-rendering-a-binary-document-pdf/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>JSF Challenge</title>
		<link>http://www.martinahrer.at/2009/09/25/jsf-challenge/</link>
		<comments>http://www.martinahrer.at/2009/09/25/jsf-challenge/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 17:09:30 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=265</guid>
		<description><![CDATA[I have started to work on a new internal project that eventually sometime might turn into a product. It&#8217;s relies in JavaServer Faces for the web UI layer. For deepening my knowledge of the JSF technology (after I haven&#8217;t worked with JSF for almost a year) I have decided to start my JSF Challenge that [...]]]></description>
			<content:encoded><![CDATA[<p>I have started to work on a new internal project that eventually sometime might turn into a product. It&#8217;s relies in JavaServer Faces for the web UI layer. For deepening my knowledge of the JSF technology (after I haven&#8217;t worked with JSF for almost a year) I have decided to start my JSF Challenge that would accompany my project development.<br />
My JSF Challenge means that whatever the problem is that has to be solved I would tackle it directly using no workarounds but would rather try to utilize the most efficient features of JSF.<br />
Also that would mean that for many of these solutions I would strive to create solutions that are re-usable for other projects in future as well. So this would for example also involve creating custom JSF components and using more of the JSF APIs than I did in the past.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2009/09/25/jsf-challenge/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WebSphere 6.1 and JSF 1.2</title>
		<link>http://www.martinahrer.at/2008/08/14/websphere-61-and-jsf-12/</link>
		<comments>http://www.martinahrer.at/2008/08/14/websphere-61-and-jsf-12/#comments</comments>
		<pubDate>Thu, 14 Aug 2008 16:27:29 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[WebSphere]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/?p=85</guid>
		<description><![CDATA[The last week I was asked to migrate a JSF 1.2 / Seam 2.x based web app to a WebSphere 6.1 application server. I hadn&#8217;t worked with WebSphere in a while, though I knew what I had to expect. IBM still hasn&#8217;t released a JavaEE 5 compliant product, so the 6.1 version is still on [...]]]></description>
			<content:encoded><![CDATA[<p>The last week I was asked to migrate a JSF 1.2 / Seam 2.x based web app to a WebSphere 6.1 application server. I hadn&#8217;t worked with WebSphere in a while, though I knew what I had to expect.</p>
<p>IBM still hasn&#8217;t released a JavaEE 5 compliant product, so the 6.1 version is still on J2SE 1.4 with JSP 2.0 and Java Servlet 2.4. Also it has a built-in JSF 1.1.</p>
<p>The application to be migrated luckly is using facelets as its view technology otherwise I would have been screwed anyway. JSF 1.2 itself doesn&#8217;t rely on the servlet spec 2.4 so a good chance to get it done.</p>
<p>To run JSF 1.2 the following is required:</p>
<ol>
<li>Make sure that you WebSphere installation is at least running with fixpack 13!</li>
<li>Create a shared library containing JSF RI 1.2 jars (jsf-api.jar, jsf-impl.jar, el-api-1.0.jar,    el-impl-1.0.jar)</li>
<li>Create a classloader with application classes loaded first and bind it to the shared library above</li>
<li>Set the classloading policy as application classes loaded first and assign the classloader</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2008/08/14/websphere-61-and-jsf-12/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Implementing Logon Forms with JSF</title>
		<link>http://www.martinahrer.at/2008/03/10/implementing-logon-forms-with-jsf/</link>
		<comments>http://www.martinahrer.at/2008/03/10/implementing-logon-forms-with-jsf/#comments</comments>
		<pubDate>Mon, 10 Mar 2008 09:55:19 +0000</pubDate>
		<dc:creator>Martin Ahrer</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[MyFaces Trinidad]]></category>
		<category><![CDATA[Oracle ADF Faces]]></category>
		<category><![CDATA[Rich-Faces]]></category>

		<guid isPermaLink="false">http://www.martinahrer.at/2008/03/10/implementing-logon-forms-with-jsf/</guid>
		<description><![CDATA[Implementing a logon form with JSF has been alwys a bit troublesome. This requires form input elements with input names j_username and j_password. With the JSF RI this is hard to accomplish. So you typically end up with including the Apache MyFaces Tomahawk components which offer a forceId attribute. If you are using other popular [...]]]></description>
			<content:encoded><![CDATA[<p>Implementing a logon form with JSF has been alwys a bit troublesome. This requires form input elements with input names j_username and j_password. With the JSF RI this is hard to accomplish. So you typically end up with including the Apache MyFaces Tomahawk components which offer a forceId attribute.</p>
<pre lang="xml">
<h:outputText value="User" />
<t:inputText id="j_username" forceId="true"/>
<h:outputText value="Password" />
<t:inputSecret id="j_password" forceId="true" />
</pre>
<p>If you are using other popular JSF component libraries, things might get a bit more handy (you can avoid including tomahawk just for fully controlling the input ids!).</p>
<p>With Myfaces Trinidad (Oracle ADF Faces) it is pretty easy, ids are accepted as they are:</p>
<pre lang="xml">
<tr:outputLabel value="User" />
<tr:inputText id="j_username" />
<tr:outputLabel value="Password" />
<tr:inputText id="j_password" secret="true" />
</pre>
<p>With JBoss Rich-Faces use the a4j:form tag:</p>
<pre lang="xml">
<a4j:form prependId="false">
	<h:outputText value="User" />
	<h:inputText id="j_username" />
	<h:outputText value="Password" />
	<h:inputSecret id="j_password" />
</a4j:form>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.martinahrer.at/2008/03/10/implementing-logon-forms-with-jsf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

