Showing posts with label EE6. Show all posts
Showing posts with label EE6. Show all posts

Thursday, March 24, 2016

JSF 2.2 Tip of the Day: Using Hibernate Validators with JSF

Introduction

Hibernate validators offer a plethora of validators to make your development work much easier. Some of the common ones that are used are @NotNull, @NotBlank, and @NotEmpty. To take advantage of these validators, and avoid some misconceptions, a little information needs to be provided.

@NotNull

Everyone likes this particular annotation, and it can be a real life saver. However something that often catches developers using it on JSF is that JSF treats empty form fields as empty strings. This is not the same as null. So if you want JSF to capture these values and treat them as null values, you need to tell JSF to do so. This is accomplished by adding the following context parameter to the web.xml file.
    <context-param>
         <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
         <param-value>true</param-value>
    </context-param>
Once this is added to the context, all blanks will be treated as null values. Be mindful of any side effects created from this change.

@NotEmpty

This validator causes a lot of confusion. The value can not be null, but can be any character including whitespace, e.g. You can enter a space, and it will accept it.

@NotEmpty

This is the most useful annotation from my standpoint. This makes sure that the input is not null, and is not an empty string like white spaces. This is really what I think most developers are really after anyway. They want to make sure that users fill in form fields.

Code

The code for this project can be found on Github, and includes some additional bonus code such as using locales, and custom messages. The code can be found here: jsf-hibernate-validator.


Tuesday, March 22, 2016

JSF 2.2 Tip of the Day: Using ValueExpressions and VariableMapper to set EL using a PhaseListener

The title seems like a mouthful, and it is. I had some code which I used to demonstrate how to set EL values using a PhaseListener. I was going to delete the code when I decided that it was the second time someone in a short span of time asked me the same question, and I should post how to do it.

The use of a PhaseListener to set EL values seems to the casual observer like Voodoo magic. You will see the EL expressions on the page, and they magically seem to populate. In some ways it is like a classical interceptor which can make your code really seem magical, and lead to confusion. This approach though has its place, and if used correctly can solve a lot of issues. One example is determining if a <ui:include src="XXX" rendered="#{EL_VARIABLE_HERE}" /> should render.

It can also be used to set the src value on the fly. An always popular question on how to resolve.

The project can be found on GitHub here: jsf-ve-phaselistener

So the output looks like a nice set of name value pairs using the Greek alphabet as variable names.



Wednesday, April 01, 2015

JSF 2.2 Tip of the Day: p:passthrough and How to use it

I was asking my team to go through their JSF pages, and to update the XML namespaces to use the latest namespace from the JSF 2.2 specification. While I was looking at the code, I found a number of instances where developers were adding attributes like name to <h:commandButton /> and NetBeans correctly was identifying that there is an issue with that.

Fortunately, some of these attributes were passing through to the underlying page without needing p:passthrough. However, you should not rely on such functionality to work. If the VDL Document does not show it as an attribute, you shouldn't expect it to work.

Alright, so how do we do it correctly?

There is no magic here. It is simply a matter of adding the attribute with a prefix of p:, for example p:name="someName" for the name attribute. This will result in the attribute being passed through the rendered and added to the resulting output.

So I have an example, and the resulting output.

The resulting output will run the JavaScript associated with the passed through attributes, or set the CSS styling. Very simple and easy to implement.

Tuesday, February 17, 2015

JSF 2.x Tip of the Day: Implementing a ViewMapListener

A map of the lands where the Trobadors flourished. 
"France 1154-en" by Reigen - Own work
Licensed under CC BY-SA 4.0 via Wikimedia Commons.

Introduction

There are a number of SystemEvents supported by JSF 2.x. A question that comes up frequently is how to implement them. In a number of cases on stackoverflow, it is implemented using a PhaseListener. I was looking for a way to cleanup the view map, or just get values from it before it was destroyed. I decided that the simplest way to do so was to implement a ViewMapListener. I also noticed that there were very few posts on how to implement it using the faces-config.xml so I decided to use that approach since it was instructive and more clear to me.

Implementation

The basic implementation requires that you add our listener implementation to the faces-config.xml. The example I have here is designed to get called on a PreDestroyViewMapEvent which is called on a normal navigation. We can force it though by adding a @PreDestroy annotation to a method to invoke before being destroyed. Inside the method we would need to get the UIViewroot view map, and call clear(). This would cause our listener to be invoked too. It would be a good cleanup mechanism for cleaning up resources on session expiration too, but at the moment this does not work on JSF 2.1. The @PreDestroy is not called on session timeout on JSF 2.1. This is expected to be an enhancement in JSF 2.2+.

The code for the project can be downloaded from Bitbuket here: viewmaplistener-example

Conclusion

The example above is just one mechanism of using a SystemEvent listener. You may decide to read values from the map, and add them to the session, or manipulate it in some other way before the data is destroyed.

Sunday, December 21, 2014

JSF 2.x Dynamic Encoding

Encoding Examples
In an Internationalized world, we need to be able to change the encoding of a JSF page dynamically. In this case, we have some characters encoded in UTF-8, but we want to be able to change the encoding on the page, and have the framework handle the character conversions for our web page.

So how do we do it?

One of the simplest ways is to wrap our page in a <f:view /> tag. The tag wraps the <head/> and <body/> elements in our HTML page. In the example above this is accomplished as shown below: The code for the backing bean is shown below:

EncodingBean.java


The Netbeans Maven project can be found here: JSF Dynamic Encoding

Monday, January 20, 2014

RichFaces 4.3.x Tip of the Day: Complex RichFaces Data Tables

Introduction

I have been working on JSF tables for the various projects I have been involved with over the years. Starting in 2012, I began looking at RichFaces <rich:dataTable /> for some projects at my day job. The research into how to handle a number of complex situations has been enlightening to say the least.

The table is the most complex component in HTML. It is seemingly boundless in its extensibility. You can have multi-column headers that span multiple rows, you can multi-row cells, or multi-column cells. Tables can be displayed left-to-right, or right-to-left, top-to-bottom and vice-versa. As a result, when developing components for JSF, or any component framework, decisions must be made on how to generate them.

A couple of the component frameworks like PrimeFaces, and RichFaces allow developers to create more complex tables with more ease. However there are limitations with each of these frameworks. We trade flexibility for consistency, and this is fine in most cases.

The demonstration code in this post is about getting some of the flexibility back, or taking advantage of the flexibility that comes with a framework like RichFaces. We will gain the flexibility back, but it is a function of complexity. The examples will show you techniques for doing the "same thing" in multiple ways. For example, sorting can be done on the server, client, or a combination of both.

The question is where we put the complex bits. The answer to that question depends on you as a developer. You need to examine the problem domain, and understand the limits to the techniques presented.

Solutions

Please let me confess something. I like building HTML objects programmatically. There I said it. In this case I am trading the ease of development for flexibility. The solutions below will demonstrate the different techniques for accomplishing the same functionality. Please examine the code carefully before discounting it. I spent a lot of time playing with it to make it look simple.

The code for this project was developed using NetBeans and Apache Maven. The code was tested on GlassFish 3.1.2.2 and 4.0. It should work on other application servers, but I have not tested it on other servers. This project assumes you are using NetBeans which includes a sample database that these examples require. If you are not using NetBeans, you will need to create your own database with sample data to display some of the tables.

The code can be downloaded from Bitbucket at the link below, or in the references section at the end of the post.

richfaces-tables-poc

Dynamic Data Table with Sorting

Dynamic Table with Sorting
This example uses the binding attribute of the <rich:dataTable /> to bind our table to a CDI @ManagedBean. The bean is responsible for generating the table programmatically, and returning it back to the page. The data is sortable by column.
As you can see the page is very simple. In fact, most of the page is plumbing and navigation. The <rich:dataTable /> is the smallest part of the page. The code to generate the table is much more complex.
As you can see we have traded simplicity in the page for complexity in the @ManagedBean. If you are satisfied with this technique, lets take a look at another one.

Dynamic Data Table with Sorting Revisited

Dynamic Table
This table uses the same dynamic binding as the example above on the JSF page, but uses helper utilities to create JSF components dynamically from a library that I have written. It is a separate project that you can download (Please see references). This reduces the chances for errors creating common components, but it is still a lot of code. To check our sorting, I have made a "random" data generator for the table data for the code to sort.
The more simplified code in the @ManagedBean is shown below.
The code above was written before I added more functionality to my jsf-utils project. The new methods would shorten this considerably, but it would still be fairly complex.

Dynamic Table using JSP/JSTL Tags with JSF

JSF/JSTL Dynamic Table
Let me start this example with a warning. If you are using JSP/JSTL tags in your JSF pages, you may encounter very bad behavior. This technique should only be used as a last resort. I will not labor a point. If you don't understand why this is a bad idea, take a look at this post for links: JSF 2.x Tip of the Day: Great Blog Posts Explaining JSTL vs. JSF.
In this example, I will generate the rows and columns using <c:forEach />. This transfers a lot of the complexity to the page and away from the @ManagedBean. Since we are using <c:forEach />, our mechanism for sorting has to change. I used Query jquery.tablesorter.js to allow sorting of the headers.
As you can see we have much simpler code in the page bean. It looks like what you would expect for a normal JSF data table.

Complex Data Table Design

Complex Table Design
This table has a lot of really cool features, but the code is complex in the page, and the page bean is relatively simple.

Conclusion

RichFaces supports complex table designs, and produces nice results. The amount of work required to create dynamic data tables depends on the technique chosen, and limitations on the data being presented. There is no "one good way" to create data tables. Suffice to say that the easiest path should be chosen.

References

SourceServlet: Displaying the Source Code and Pages from a Project on your Blog

SourceServlet
I had been working on a way to create nice examples that include a way to display the page and source code for it. I created a servlet that will display the code as plain text that I would like to share with all of you.

SourceServlet.java


Sunday, January 19, 2014

JSF 2.x Tip of the Day: Custom JSF AJAX Error Handling on Client

Introduction

One of the holes in JSF, in my professional judgement, is the lack of really good exception handling on the client for AJAX exceptions. A number of client frameworks like PrimeFaces, OmniFaces, and RichFaces attempt to cleanup for this shortcoming, it is still a deficiency.

The capabilities are present to make AJAX exception handling more robust. The "chemistry" is present in the framework, but it is not really standardized.

In this short example, I am demonstrating how to use the jsf.ajax.addOnError functionality to make client exception handling better. We will display at a minimum, an alert to let them know something bad has happened to their request.

Additionally, I will demonstrate how to use XPath to get additional information from the response.

Solution

The solution is to add the following code to the <head />: of the JSF page, or to an external JavaScript file that is included in the head. In my case, I am using an external JS file called jsf.ajax.handler.js that is loaded using JSF <h:outputScript />.

Here are the contents of the file.

References

JSF 2.2.x Tip of the Day: Custom JSF Exception Page including the default Facelets Exception Page

If you want to create a custom exception page in JSF and include the default exception page, you simply need to include one line of code.

This is an example of a custom exception page using the code above.

The resulting page will look like the image below. Please note that we are including the default JSF exception page.

Saturday, January 18, 2014

Java EE Tip of the Day: @WebFilter (Servlet Filter) Redirection

There is a common case to check a condition in a filter, and if the condition is not satisfied to redirect back to the context root of the application. This may be the case in a login filter, or a filter that performs some session management.

Here is a simple code example of how to perform the redirection:

JSF 2.x Tip of the Day: Redirecting to the context path with parameters

This is just a quick code example that demonstrates how to do a redirect to the Servlet context path with parameters.

The code above will correctly format parameters to be passed as part of the redirection.

Here is an example using bogus parameters.



Here is the JSF Form I used to generate the output below.

Friday, January 10, 2014

JSF 2.2.x Expression Language (EL) Delimiting { } in nested EL

Introduction

I was working on possible updates for our application to use JavaServer Faces 2.2 with Manfred Riem from Oracle. I mentioned that I was had tried to update to 2.2.3, but encountered an exception from EL that indicated that the statements were unbalanced. I didn't have time at that point to figure out what the issue was. It was annoying that the switch from 2.1 to 2.2 would cause such an issue, but I thought I would figure it out later. Later arrived...

There is an issue JAVASERVERFACES-2977 : Components get rendered twice we encountered that occurred when we tried to upgrade to 2.1.26. It was fixed in 2.2.5, but needs to be backported to 2.1.x branch. You can get around the issue by using 2.1.21, but Manfred suggested using JSF 2.2. I decided to give it another try, but I am also aware that I am trying to run it on an EE 6 container not EE 7. This is not an issue in the sense that the technology works, but it is not on a support matrix.

Issue

Fast forward, the EL issue appeared again. Manfred and I looked at the issue and it has the following code signature:

"#{abc:method('ABC$XYZ(current{QUANTITY})',bean.property)}"
or this in a more shortened form.
"#{'{}'}"

Manfred and I tried a number of solutions, one of which seemed to work. However, after further examination it failed to work too.
The troubling part is that existing code running on JSF 2.0, and 2.1 on Weblogic worked fine. I began to look a little deeper. I really want our application to run JSF 2.2 on the latest build. I created a simple project to work out how to delimit the EL which was causing a problem. The project can be downloaded below, or in the references section.

Code: jsf-el-delimiting
When I deployed the project to my GlassFish 4.0 server, it worked! I was really surprised. I went back to my modified GlassFish 3.1.2.2 instance which had JSF 2.2.4 running on it. It failed. So I realized that there was an issue introduced between 2.2.0 and 2.2.4. I later checked with 2.2.5 and found the same issue. I began the process of tracking down where the issue began. It looks like it started on 2.2.2.
JSF Version Passed
2.2.0 OK
2.2.1 OK
2.2.2 FAIL
2.2.3 FAIL
2.2.4 FAIL
2.2.5 FAIL

SOLUTION

The interim solution until the JIRA issue listed in the references is resolved, you can use JSF 2.2.0, or 2.2.1 in your project.

References

Tuesday, October 22, 2013

CDI Tip of the Day: Understanding Injection Techniques

diego_cervo/istockphoto.com
I just finished reading a book Understanding SCA (Service Component Architecture) that covers SCA in detail. The book is a topic for another post. I did come across a gem in the book around Dependency Injection (DI) techniques, and how to make choices around one technique over another.

The three main techniques used for Dependency Injection (DI) are constructor, setter, and field injection. There is also reflection which I will not discuss in this article.

Constructor Injection

This technique calls for injecting the objects used in our class at object instantiation. A significant advantage of this technique is that it makes all of our dependencies explicit at compile time. This also makes testing much easier since we can use testing techniques like mock objects to test. "... Constructor-based injection also enables fields to be marked as final so they cannot be inadvertently changed later on." This can also add some additional performance gains since the object are final and the compiler can optimize this. If you allow mutators for the objects injected, then this performance perk is negated since the object can not be marked final.

A disadvantage of constructor based injection is that the constructors parameter lists can become very large. I would recommend that this approach be considered for 4 parameters, or less. Four parameters can result in 16 test cases (n X n matrix). Additionally, there may be more than one constructor, and dependency injection frameworks deal with it differently. Weld currently only allows DI on one constructor.

Advantages Disadvantages
Explicit Dependencies at compile time. Constructors can become very large
Fields can be marked final Mutable fields lose final advantage
Testing can be simplified The number of parameters produces an n X n matrix of tests

Setter Injection

The next technique is using setter based injection. Typically we have an object with setters and getters where the setter is annotated for injection. This requires that our setters be public, or protected. I would recommend making them public in the absence of reasons to do otherwise. The significant advantage to setter based injection is the ability to change the injected object at runtime. If the method is public, then it can be changed by any object. This could be an advantage, or disadvantage. Also this technique is conducive to testing as well. We can inject mock objects, or use a framework like Arquillian to handle injection during testing.

The disadvantages of using setter based injection "... are two major disadvantages to setter injection. Component (Class) dependencies are dispersed across a number of setter methods, making them less obvious and increasing the verbosity of the code because a method needs to be created for every reference In addition, setter methods make references that should be immutable subject to change because the fields they are assigned cannot be declared final." The second item may not be a disadvantage if  considered closely in your design. The former represents a significant disadvantage in terms of code clarity that has been a hallmark of EE5/6/7.

Another item to consider is that the one of the best practices for developing interfaces is to avoid putting setters in them. Interface design usually only has the getter defined, the setter is an implementation detail that is left out of the contract. This prevents the client code from altering the implementation code accidentally since it should be interacting with the interface contract.

Advantages Disadvantages
Code is more testable Results in less readable code as the number of references increase.
Injection can be changed at runtime. Fields cannot be marked final
- Mutators (setters) are typically not part of the interface contract.

Field Injection

Field based injection is often used in example code found for Dependency Injection (DI) frameworks. "The major advantage of field-based injection is that it is concise." The fields may be public, private, protected, or default. They can not be marked final. This technique avoids large lists of parameters for constructors, and adding setter methods that are not part of the interface contract. The Major disadvantage is unit testing. You need to add a setters, sub-class the object, or use reflection typically. A framework like Arquillian can be used to test, but this adds additional complexity that would not be required for using constructor, or setter injection. The brevity is both an advantage and disadvantage.
Advantages Disadvantages
Concise Difficult to test
- Fields cannot be marked final

Summary

In examining the tables of advantages and disadvantages, you may come to a conclusion that Field injection may be the best choice. This would be premature. In fact, there is clearly no one technique that is better than the other. All have advantages, and disadvantages. Clearly as a developer, or architect you must decide for a given class, or set of classes which technique will meet your requirements. A lot has been said about picking a pattern, and using it consistently throughout your project. I personally find that idea bad. Comparatively, we could say it is like picking a hammer out of a toolbox and using nails everywhere. Sometimes a bolt and nut would work much better. Don't fall into the trap of consistency over what makes sense for your project.

Popular Posts