Ok, this will be a multi-part blog entry series.
What I want to do with this blog entries, is to document, how to make your JSF2 application use JAAS ( Java Authentication and Authorization Service ) to manage your/my users, authenticate them through a form with
the help of the server and use that security information in our JSF2 pages and our Java Beans.

In this first part of the series, I’ll try to cover the terminology used in easy to understand words.

These are the terms, you’ll need to know:

  • realm: A realm is basically a "user database", being it a flat file with user/pass + group info, database tables or even an ldap directory or something else you can imagine, like facebook connect or google authentication system. It may be used by n applications.
  • user: A user is a person or program wishing to authenticate against our server/app. If you only make your website for real persons, these are your users. If you also offer a webservice, other programs accessing that service are also users. A user belongs to a realm, so may be valid in n applications (see principal below)
  • role: Roles are assigned to users and/or groups in an application. E.g. GUEST for a not authenticated visitor, LOGGEDIN_USER for an authenticated user, MODERATOR or ADMIN for special people.
  • group: Groups are like roles, but they are used over multiple applications and mapped to specific ROLES on an per-application-basis
  • principal: A Principal is an authenticated user in the scope of an application. The same user may have different principals in different applications. A principal is identified by its name and authenticated using authentication data (credentials)
  • security policy domain: Also called security domain or realm. Basically, the database where you lookup users. But in this meaning, its where the realms are used, being it application1, application2, applicationN
  • Security attributes: are attributes associated with every principal, like " is allowed to access the admin area" or stuff like that.
  • credential: contains or references security attributes; are used to authenticate a Principal for a Java EE product service (your webapp)
  • If you want to get the original documentation, take a look at the Security chapter in the Java EE 6 Tutorial Volume I

    Further references, which I’ll probably be using in the next posts of these series:

If you happen to localize your JSF Web-Application to German, you’ll probably have problems displaying German Umlauts ( äÄ, ö Ö, ü Ü, ß) in your page.

How to resolve this? Encode the umlauts with their Unicode code in your message-bundle like this

  1. ä = \u00e4
  2. Ä = \u00c4
  3. ö = \u00f6
  4. Ö =\u00d6
  5. ü = \u00fc
  6. Ü = \u00dc
  7. ß = \u00df

So, e.g. just specify it like this in your bundle.properties

1
homework=Haus\u00fcbung

Specify the bundle itself in your faces-config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version='1.0' encoding='UTF-8'?>
 
<faces-config version="2.0"
    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-facesconfig_2_0.xsd">
 
    <application>
        <resource-bundle>
            <base-name>/bundle</base-name>
            <var>bundle</var>
        </resource-bundle>
    </application>
</faces-config>

and use it in your facelets page example.xhtml like this:

1
#{bundle.homework}

or like this

1
<h:outputText value="#{bundle.homework}" />

If you don’t want to convert all the Umlauts in your bundle by hand, simply use javas

1
native2ascii

command to automatically encode the Umlauts in your bundle.properties file.

Update:
I found this unicode chart, which I think is quite useful!

Recently, I was looking for a way, to validate Email-Addresses with JSF.
I came accross this blog post on java.net:

It shows, how this would have been done in the old JSF 1.1/1.2 ways… But we’re in 2010 and do it now the following way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
...
            <h:panelGroup id="loginRegisterBox" layout="block">
                <p>
                    <h:outputLabel for="userEmail" value="#{bundle['register.emailaddress']}"/>
                    <h:inputText id="userEmail" value="#{loginRegisterBean.email}"
                                 validatorMessage="#{bundle.register_invalidEmail}"
                                 required="true"
                                 requiredMessage="#{bundle.registration_please_enter_email}"
                                >
                        <f:ajax event="change" execute="@this userEmail authorBox" render="@this loginRegisterBox"
                                listener="#{loginRegisterBean.emailChanged}"/>
                        <f:validateRegex pattern=".+@.+\.[a-z]+"/>
                    </h:inputText>
                    <h:message for="userEmail"/>
                </p>
....
</h:panelGroup>
....

What does this code? It sets the email property of the bean loginRegisterBean after the user changed the value and clicked out of the field (through ajax). It automatically validates the email address through the f:validateRegex pattern and updates the message ( h:message ) if the validation failed.

The Bean looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Named(value = "loginRegisterBean")
@SessionScoped
public class LoginRegisterBean implements Serializable {
 
....
 
     // also apply these restrictions on the property itself!
    @Pattern(regexp = ".+@.+\\.[a-z]+")
    @NotNull
    private String email;
....
    public void emailChanged(AjaxBehaviorEvent event) {
// do something
    }
...
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
}

Geekscrap posted what one needs to change to feel like home in [X|K|Ed]ubuntu, at least if we’re talking about the beautiful colors, Gentoo users like the most!

http://geekscrap.com/2010/01/gentooize-part-1-colorize-console/

or, if the site does not load, try it with the cached version
cache:http://geekscrap.com/2010/01/gentooize-part-1-colorize-console/

Current Quercus java_bean() method does not work in Glassfish v3, because Caucho are cooking their own soup with everything new of JavaEE6 (I don’t understand why they need to reinvent all of JavaEE6 like JSF, CDI, etc. for their own app-server… why don’t use something existing and build on top of it? Why don’t push your own projects further, like Quercus, Hessian, Burlap and co.? )

If you, like me, want to use managed beans from inside your php code, and find out, that jndi_lookup and java_bean() do not work (= return null every time), try this little method

1
2
3
4
5
6
7
8
9
10
function my_java_bean($name)
{
    $beanManager = quercus_get_servlet_context()->getAttribute("javax.enterprise.inject.spi.BeanManager");
    $beans = $beanManager->getBeans($name);
    if($beans == null || count($beans) < 1)
        return null;
    $object = $beanManager->getReference($beans[0], $beans[0]->getClass(),    
            $beanManager->createCreationalContext($beans[0]));
    return $object;
}

The Spring Security Facelets/JSF 2.0 Taglib got released in version 0.3.

CHANGES:

  • Replaced roles.isEmpty() with roles.equals(“”) to allow usage with Java 5
  • Adopted taglib for usage with Spring 3/Spring Security 3 final
  • removed faces-config.xml in taglibs for jsf 1.2 as it prevented deploying in some scenarios

Fetch it from the Project Homepage

As I had serious problems with FileUpload and the existing “solutions”, mainly Tomahawk, MyFaces, RichFaces, PrimeFaces, etc. which are all not 100% ready for JSF 2.

I created a taglib based on the code of BalusC.
You can find the Taglib on Github

The source code is based on these two posts:

  1. Uploading files in Servlet 3.0
  2. Uploading files with JSF 2.0 and Servlet 3.0

Simply check out the code with git

1
git clone http://github.com/domdorn/fileUploadServlet3JSF2.git

then install the taglib with

1
mvn clean compile install

and import it into your maven project like this

net.balusc
fileUploadServlet3JSF2
1.0-SNAPSHOT

You can then use the taglib in your Facelets files like this:

Upload.xhtml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:hh="http://balusc.net/jsf/html"
>
<h:head>
	<title>FileUploadTest</title>
</h:head>
<body>
 
<h:form prependId="false">
 
	<h:messages globalOnly="false" id="messages"/>
 
	<h:panelGrid columns="3">
 
			<label for="someText">
				SomeText:
			</label>
 
			<h:inputText id="someText" value="#{uploadBean.someText}" required="true">
				<f:ajax event="blur" render="someText someTextMessage" execute="@this"/>
			</h:inputText> <h:message for="someText" id="someTextMessage"/>
 
			<label for="filenameText">
			Filename:
			</label>
 
			<h:inputText id="filenameText" value="#{uploadBean.filename}" required="true">
				<f:ajax event="blur" render="filenameText filenameTextMessage" execute="@this" />
			</h:inputText>
			<h:message for="filenameText" id="filenameTextMessage"/>
	</h:panelGrid>
	</h:form>
 
	<h:form enctype="multipart/form-data" prependId="false">
	<h:panelGrid columns="3">
		<h:outputLabel for="uploadedFile" rendered="#{empty uploadBean.file}">
				Input File:
		</h:outputLabel>
		<hh:inputFile id="uploadedFile" value="#{uploadBean.file}" rendered="#{empty uploadBean.file}">
			<f:validator validatorId="fileValidator"/>
		</hh:inputFile>
		<h:message for="uploadedFile"/>
	</h:panelGrid>
	<h:commandButton value="submit" action="#{uploadBean.submit}" />
</h:form>
</body>
</html>

The bean:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.dominikdorn.simpleFileUpload.beans;</code>
 
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import java.io.File;
 
@ViewScoped
@ManagedBean
public class UploadBean {
 
private File file;
private String filename;
 
public String getFilename() {
return filename;
}
 
public void setFilename(String filename) {
System.out.println("binding filename");
this.filename = filename;
}
 
public String submit()
{
System.out.println("calling submit");
 
if(file != null)
{
this.filename = file.getName();
}
 
System.out.println("processed");
// do what you want with the file
return "yeah";
}
 
public UploadBean() {
}
 
public File getFile() {
return file;
}
 
public void setFile(File file) {
this.file = file;
}
 
private String someText;
 
public String getSomeText() {
return someText;
}
 
public void setSomeText(String someText) {
System.out.println("binding someText");
this.someText = someText;
}
}

Mikael Gueck has posted some tips for Spring to JavaEE6 migration.
Quite nice in my opinion, especially the one for JPA N+1 !

Thanks Mikael! And merry xmas everyone!

Andy Gibson has blogged about how to use Context & Dependency Injection ( CDI, the @Inject annotation ) with JSF 2.

Also take a look at the comments, there is some useful info there too!

Xovi SEO Tool Contest

18 Dec
2009

The german SEO Marketing Blog has a contest for winning a 2 month license for the new Xovi SEO Tool. Maybe I’m lucky 🙂

http://seo-marketing-blog.de/goatix/xovi-seo-tool-gewinnspiel/
top