java.net member

Rechercher dans ce site

A graphical counter on GAEJ (Google App Engine for Java) using Images API Service

>> 26 May 2010

Images Service on GAEJ provides the ability to manipulate images, thus you can composite multiple images into a single one. I'll use this possibility to display a graphical hit counter. This  tutorial is only a kind of how-to. I'm sure you can write real programs using the instructions given  in this post. For simplicity reasons error handling are reduced to the minimum.

The idea is pretty simple, persist a counter using Memcache or DataStore, have digits from 0 to 9 as  PNG images, read images as bytes, make images and composites of these images, put all composites in a List and finally use this List to get the composed image.


PNG or Gif Images?
Png images does not render transparency very well ! If you want to get clean, with transparent background counter, you can replace Png by .gif images, and setContentType accordingly.

Lets go !

First declare some variables

List<Composite> listComposites=new ArrayList<Composite>();
Image img=null;
Composite composite=null;

//n is the value of the counter
int n=0;

//offset between images
int offset=0;

Create a background image
This one will normally has the total of all images width as it's width. All images have the same height.
See readImage method below.

//create a background image, this image (a physical one) is read on disk as bytes
//com.google.appengine.api.images.Image;  
    img=ImagesServiceFactory.makeImage(readImage("images/counter/b.png"));

makeComposite
makeComposite is defined like this :
public static Composite makeComposite(Imageimage,
                                      intxOffset,
                                      intyOffset,
                                      floatopacity,
                                      Composite.Anchoranchor)
Parameters:
image - The image to be composited.
xOffset - Offset in the x axis from the anchor point.
yOffset - Offset in the y axis from the anchor point.
opacity - Opacity to be used for the image in range [0.0, 1.0].
anchor - Anchor position from the enum Composite.Anchor. The anchor position of the image is aligned with the anchor position of the canvas and then the offsets are applied.

Make a Composite of the background Image

//create a Composite for the background image
    composite= ImagesServiceFactory.makeComposite(img, 0, 0, 1, Anchor.TOP_LEFT);
  

Add the background Composite to the List

  
    listComposites.add(composite);

Get the value of the counter
See getNumber() method below.

//get the number you want to display
n=getNumber();

Get individual numbers of the counter
Using a String and it's characters (not very elegant, but it works)
String s=Integer.toString(n);
for(char c:s.toCharArray())

Make Images and Composites

  • Make an image for every number of the counter,
  • Make a Composite,
  • Add the Composite to the List of Composites
  • Add the width of an image to the offset

for(char c:s.toCharArray())
                {
              
                img=ImagesServiceFactory.makeImage(readImage("images/counter/"+c+".png"));
              
                composite=ImagesServiceFactory.makeComposite(img, offset, 0, 1, Anchor.TOP_LEFT);
              
                listComposites.add(composite);
                offset+=14;
                }

Define a color for the background
color - Background color of the canvas in ARGB format.

long color=0xffffff;



Get the final image
Use composite method of ImageService
This method return an Image, it's bytes can be get by using getImageData(), you can write these bytes to your servlet (for instance ) to display the image.

Image composite(java.util.Collection<Composite>composites,
                intwidth,
                intheight,
                longcolor)


Applies the provided Collection of Composites using a canvas with dimensions determined by width and height and background color color. Uses PNG as its output encoding.

Parameters:
composites - Compositing operations to be applied.
width - Width of the canvas in pixels.
height - Height of the canvas in pixels.
color - Background color of the canvas in ARGB format.
Returns:
A new image containing the result of composition.
Throws:
java.lang.IllegalArgumentException - If width or height is greater than 4000, color is outside the range [0, 0xffffffff], composites contains more than 16 elements or something is wrong with the contents of composites.
ImagesServiceFailureException - If there is a problem with the Images Service

TutorCounterServlet.java
package com.java_javafx;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.images.Composite;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Composite.Anchor;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceException;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

/**
 * @author Kaesar ALNIJRES
 *
 */

public class TutorCounterServlet extends HttpServlet{

    private PersistenceManager pm=null;
    private final static Logger logger=Logger.getLogger("CounterServlet");
  
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException,IOException {
      
            resp.setContentType("image/png");
          
            ServletOutputStream out = resp.getOutputStream();
          
    //First some variables
      
    List<Composite> listComposites=new ArrayList<Composite>();
    Image img=null;
    Composite composite=null;
  
    int n=0;//This one will be rendered by a composition of image
    int offset=0;//offset between images (normally width of one image)
 
    //create a background image, this image (a physical one) is read on disk as bytes
   //com.google.appengine.api.images.Image;  
    img=ImagesServiceFactory.makeImage(readImage("images/counter/b.png"));
  
  
  
    //create a Composite for the background image
    composite= ImagesServiceFactory.makeComposite(img, 0, 0, 1, Anchor.TOP_LEFT);
  
    //Add the background Composite to the list
    listComposites.add(composite);

    //get the number you want to display (your counter)
n=getNumber();
String s=Integer.toString(n);

    
          
//every character here is an individual number of the counter          
            for(char c:s.toCharArray())
                {
                //create an image from bytes for every number of the counter, make a composite for every image
                //and add this compoiste to the list of composite
                img=ImagesServiceFactory.makeImage(readImage("images/counter/"+c+".png"));
              
                composite=ImagesServiceFactory.makeComposite(img, offset, 0, 1, Anchor.TOP_LEFT);
              
                listComposites.add(composite);
                //Modify this to the width of one image
                offset+=14;
                }
          
      
          
    
      



long color=0xffffff;
int widthOfCounter=70;
int heightOfCounter=16;

byte[] imgComplet=ImagesServiceFactory.getImagesService().composite(listComposites, widthOfCounter, heightOfCounter, color).getImageData();


out.write(imgComplet);
out.flush();



}
    private byte[] readImage(String fileName)
    {
        byte[] buffer;
      
        try
        {
        FileInputStream in=new FileInputStream(fileName);
        buffer=new byte[in.available()];
         in.read(buffer);
         in.close();
        
         return buffer;
        }
        catch(Exception e)
        {
            logger.severe("Exception "+e.getMessage());
        return null;  
        }
    }
//==============================================================================
    //This method will read the counter value from memcache or DataStore. The counter is called "counter" in memcache
    //give it any name you want
    private int getNumber()
    {
int counter=0;
      
      
        try {
            pm=PMF.get().getPersistenceManager();
            //get memcache   
            MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();

            //increment counter
            Long lCounter=memcache.increment("counter", 1);
          
            //if the key is in memcache and increment is ok
            if(lCounter !=null)
                counter=lCounter.intValue();
            else
            {
              
                List<Counter> pCounters = (List<Counter>) pm.newQuery("select from "+Counter.class.getName()).execute();
                if (pCounters.isEmpty()) //if no record
                 {
                    counter=1;
                    memcache.put("counter",1);
                  
                 }
                else
                    {
                    counter=pCounters.size()+1;
                    memcache.put("counter",pCounters.size()+1);
                    }
            }
              
                Counter c1=new Counter();
                c1.setCounter(1);
                pm.makePersistent(c1);
          
            }
            catch (MemcacheServiceException e) {
                            // Ignore cache problems, nothing we can do. Put log a message
                logger.severe("memcache exception "+e.getMessage());
                            }
            catch(Exception e)
            {
                logger.severe("General exception "+e.getMessage());  
            }
            finally
            {
                if(pm != null)
                pm.close();
              
              
            }
            return counter;
    }
//==============================================================================  
}

Counter.java

package com.java_javafx;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;

/**
 * @author Kaesar ALNIJRES
 *
 */
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Counter {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
  
    @Persistent
    private int counter;

    /**
     * @return the key
     */
    public Key getKey() {
        return key;
    }

    /**
     * @param key the key to set
     */
    public void setKey(Key key) {
        this.key = key;
    }

    /**
     * @return the counter
     */
    public int getCounter() {
        return counter;
    }

    /**
     * @param counter the counter to set
     */
    public void setCounter(int counter) {
        this.counter = counter;
    }
}

PFM.java
package com.java_javafx;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;
/**
 * @author Kaesar ALNIJRES
 *
 */
public final class PMF {
    private static final PersistenceManagerFactory pmfInstance =
        JDOHelper.getPersistenceManagerFactory("transactions-optional");

    private PMF() {}

    public static PersistenceManagerFactory get() {
        return pmfInstance;
    }
}

Thank you for reading. Hope you find this post helpful.

Read more...

Logging Templates for Eclipse

>> 23 May 2010


















Description

Some useful Java Editor Templates for easy working with java.util.logging in Eclipse



Installation

  • Download the zip file to your hard disk.
  • Unzip
  • Import templates to your eclipse : Window -> Preferences -> Java -> Editor -> Templates
  • Click on "Import" and select the  XML file (obtained after the unzip) -> ""ka_logging_templates_1.2Beta.xml"



Using

In any Java editor -> type "log" and CTRL+SPACE Bar. Choose the instruction you want to use. In most templates "TAB" is available for multiple choices. If you need help on using java.util.logging : Type "log" and CTRL+SPACE BAR -> choose "1st Look How to use - General Informations"



Read more...

Google Font API/Directory in your Blog/Web Site/GoogleAppEngine etc.

>> 20 May 2010

This is not a specific JEE theme, but as this can add benefits to your site,I found it useful to add it in JEE section. Use it if like it.

Site: http://code.google.com/apis/webfonts/
Web font directory :  http://code.google.com/webfonts

The Google Font Directory provides high-quality web fonts that you can include in your pages using the Google Font API.

Benefits of the Google Font API include:

  • A choice of high quality open source fonts.
  • Works in most browsers.
  • Extremely easy to use.


The fonts in the directory are all released under open source licenses; you can use them on any non-commercial or commercial project.

Just a little example :
Say you want to use "Tangerine" font.

Between <head> and </head> of an html page add this link to a stylesheet

<head>
...
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine">
..
</head>

Add Between <head> and </head> of an html page a selector

This one will use the "Tangerine" font. I used here a custom class "ka", give your class any name you want


.ka {
  font-family: 'Tangerine', serif;
 
}

Use the newly added font

In any place in your html (between <body> and </body>
add for instance <p> that use this font

<p class="ka">Hello World!!!</p>

Note:
You can add several fonts in the stylesheet link.

You can add normal CSS properties in your custom class

Hello World !!!

Enjoy !

Read more...

Utiliser les fonts de Google dans votre Blog, Site,GoogleAppEngine etc.

Oui, le sujet n'est pas liée directement au développement, mais on a besoin aussi de tous les outils susceptible d'améliorer le fonctionnement ou même le look de sites.

Google Font Directory, ce sont des polices de caractères de très haute qualité à utiliser dans toutes sortes de pages Web.

D'abord les URL :
Site: http://code.google.com/apis/webfonts/
Web font directory : http://code.google.com/webfonts

Les avantages de Google Font API sont multiples, par exemple :

  • Open source
  • Compatibilité avec des navigateurs internet
  • Facile à utiliser
  • Il est possible de les utiliser dans des sites perso, comme des sites commerciaux.


Comment ça marche :
Nous utilisons dans cet exemple le font " Tangerine "
Entre les deux balises <head> et </head> d'un fichier HTML

Insérez un lien vers une feuille de style comme suite
<head>
...
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine">
..
</head>

Ajoutez aussi entre les balises <head> et </head> un selecteur, cette classe personnelle va utilliser le font "Tangerine". Donnez un nom de votre choix à cette classe (j'ai utilise " ka ")


.ka {
font-family: 'Tangerine', serif;

}

Utilisez " Tangerine " pour l'affichage
Dans votre page HTML et entre les deux balises <body> et </body>, utilisez la classe définie là-haut pour les balises <div>, <span>,<p> etc...

<p class="ka">Hello World!!!</p>

Et voilà !

Hello World !!!

Note:
Il est possible d'importer plusieurs fonts dans la même URL

Les proprietées CSS sont utilisables normalment dans avec ces polices de caractères.

Read more...

JSF Validation - Part 3

>> 19 May 2010

 In this part we will see how to customize validation for your need.

If validation is not supported by the standard validators

In this case you can :

  • Write a method in your bean (JSF mainly works with beans to get and set Data)
  • Write a custom validator
  • Create your own library and tags

Write a custom method

You can provide a method in your business bean. The validator attribute will use this method to validate the input. If the converted value is considered invalid, it should throw a ValidatorException and provide a FacesMessage.


The Expression Language is used here to point to a method on an arbitrary JavaBean that adheres to the contract and signature of Validator.validate( ). This can greatly simplify application design by allowing you to put the
business logic, and the method to validate it, in the same class.

Note:
Detailed message is used with <h:message />.By default, the UI Messages will
display the summary messages.(<h:messages /> with "s")

Note:
validate must be defined like this :

public void validate(FacesContext context,
UIComponent component,
Object enterdValue)
throws ValidatorException


 In a bean add a method (here ValidateMail)
//==================================================
    //validateMail
    //==================================================
    public void validateMail(FacesContext context,//jsf engine) 
                             UIComponent component, //the component
                             Object enteredValue//must not be empty
                             )throws ValidatorException
      {
        String email=(String)enteredValue;
        if(email.trim().equals("") || !email.matches("^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\\-+)|([A-Za-z0-9]+\\.+)|([A-Za-z0-9]+\\++))*[A-Za-z0-9]+@((\\w+\\-+)|(\\w+\\.))*\\w{1,63}\\.[a-zA-Z]{2,6}$") )
      
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                     "Error Entered e-mail",//summary msg
                     "Entered e-mail: \""+email+"\" is invalid"//detailed msg
                                     ));
    }

In testValidation.xhtml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:h="http://java.sun.com/jsf/html"
    
      >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test Validation</title>
</head>
<body>
<h:messages/>
<f:view>

<h:form id="form">
<h:outputLabel for="name" value="Enter Name"/>
<h:inputText required="true" label="name" id="sname">
<f:validateLength minimum="3" maximum="20"/>
</h:inputText>
<h:outputLabel for="double" value="Enter Double Value"/>
<h:inputText required="true" label="double">
<f:validateDoubleRange minimum="2.0" maximum="20.1" />
</h:inputText>

<h:outputLabel for="long" value="Enter Long Value"/>
<h:inputText required="true" label="long">
<f:validateLongRange minimum="0" maximum="10" />
</h:inputText>

<h:outputLabel for="email" value="Enter Your email"/>
<h:inputText required="true" label="email" validator="#{person.validateMail}"/>

<h:commandButton action="ok" value="Validate" />
</h:form>
</f:view>
</body>
</html>

Display

If one of the conditions is missed, an error message is displayed


When email is valid no more error message







Create a Validator

1.Create a class that implements the javax.faces.validator.Validator interface
2.Implement the validate() method
3.Register this validator in the configuration file "faces-confix.xml"
4.Put <f:validator validatorId="xxx" to use it.

Note:
Using a custom validator offers the possibility of re-using this component.
Create a class that implements the javax.faces.validator.Validator interface


EMailValidator.java

package fr.iipt.ka.faces;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class EMailValidator implements Validator{
  
    //==================================================
    //validateMail
    //==================================================
    public void validate(FacesContext context,//jsf engine) 
                             UIComponent component, //the component
                             Object enteredValue//must not be empty
                             )throws ValidatorException
      {
        String email=(String)enteredValue;
        if(email.trim().equals("") || !email.matches("^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\\-+)|([A-Za-z0-9]+\\.+)|([A-Za-z0-9]+\\++))*[A-Za-z0-9]+@((\\w+\\-+)|(\\w+\\.))*\\w{1,63}\\.[a-zA-Z]{2,6}$") )
      
        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                     "Error Entered e-mail - custom class",//summary msg
                                     "Entered e-mail: \""+email+"\" is invalid"//detailed msg
                                     ));
    }

}

Edit faces-config.xml

<faces-config>
...
<validator>
 <validator-id>checkMail</validator-id>
 <validator-class>fr.iipt.ka.faces.EMailValidator</validator-class>
 </validator>
 </faces-config>


In testValidation.xhtml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:h="http://java.sun.com/jsf/html"
    
      >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test Validation</title>
</head>
<body>
<h:messages/>
<f:view>

<h:form id="form">


<b>Validate email using custom method in JavaBean</b><br/>
<h:outputLabel for="email" value="Enter Your email"/><br/>
<h:inputText required="true" label="email" validator="#{person.validateMail}"/><br/>

<b>Validate email using custom custom class</b><br/>
<h:outputLabel for="email" value="Enter Your email"/><br/>
<h:inputText required="true" label="email2">
<f:validator validatorId="checkMail"/>
</h:inputText>


<h:commandButton action="ok" value="Validate" />
</h:form>
</f:view>
</body>
</html>

Display

Create your own tags

It's possible to create custom validation classes and put them in a facelet tag lib, use them the same way as the core tag lib or html tag lib. Steps to do this are the same as creating a custom validation class with one exception, you must create a taglib descriptor.

First step :

Create a custom validation class this class must implement Validator and provide validate method (the same as the previous custom validation class). Let it have a modified error message (just to see the result)

EMailValidator2.java

package fr.iipt.ka.faces;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class EMailValidator2 implements Validator{
  
    //==================================================
    //validateMail
    //==================================================
    public void validate(FacesContext context,//jsf engine) 
                             UIComponent component, //the component
                             Object enteredValue//must not be empty
                             )throws ValidatorException
      {
        String email=(String)enteredValue;
        if(email.trim().equals("") || !email.matches("^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\\-+)|([A-Za-z0-9]+\\.+)|([A-Za-z0-9]+\\++))*[A-Za-z0-9]+@((\\w+\\-+)|(\\w+\\.))*\\w{1,63}\\.[a-zA-Z]{2,6}$") )
      
        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                     "Error Entered e-mail - facelet tag lib",//summary msg
                                     "Entered e-mail: \""+email+"\" is invalid"//detailed msg
                                     ));
    }

}

Second Step

Register this class as validator in the configuration file "faces-confix.xml", give your validator any ID and specify it's class.


<faces-config>
...
...
<validator>
 <validator-id>ka.faceletTag.1</validator-id>
 <validator-class>fr.iipt.ka.faces.EMailValidator2</validator-class>
 </validator>
 </faces-config>

Third Step

Create a facelet tag lib descriptor (in src/META-INF folder), give it a name with .taglib.xml extension. Define your tag(s), (every tag will be called in facelet .xhtml file with it's name). Associate the tag name with it's validator.

ka.taglib.xml

<!DOCTYPE facelet-taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
"http://java.sun.com/dtd/facelet-taglib_1_0.dtd">
<facelet-taglib xmlns="http://java.sun.com/JSF/Facelet" >

<namespace>http://iipt.fr</namespace>

<tag>
<tag-name>validateMail</tag-name>

<validator>
<validator-id>ka.faceletTag.1</validator-id>
</validator>
</tag>
</facelet-taglib>

Now you can use your tag(s)

testValidation.xhtml

Declare a name space with a prefix, in the body of <h:inputText use the same prefix with your custom tag name

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:h="http://java.sun.com/jsf/html"
    
      xmlns:ka="http://iipt.fr"
      >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test Validation</title>
</head>
<body>
<h:messages/>
<f:view>

<h:form id="form">


<b>Validate email using custom method in JavaBean</b><br/>
<h:outputLabel for="email" value="Enter Your email"/><br/>
<h:inputText required="true" label="email" validator="#{person.validateMail}"/><br/>

<b>Validate email using custom class</b><br/>
<h:outputLabel for="email" value="Enter Your email"/><br/>
<h:inputText required="true" label="email2">
<f:validator validatorId="checkMail"/>
</h:inputText>
<br/>
<b>Validate email using facelet tag lib</b><br/>
<h:outputLabel for="email" value="Enter Your email"/><br/>
<h:inputText required="true" label="email3">
<ka:validateMail />
</h:inputText>
<br/>

<h:commandButton action="ok" value="Validate" />
</h:form>
</f:view>
</body>
</html>

Display

Read more...

JSF Validation - Part 2

>> 15 May 2010

This tutorial works on JSF 2 using MyFaces 2
<f:validateRegex
This is a JSF 2  standard validator.
This validator provides reqular expression-based validation
A validator that valid the component's value against the "pattern" attribute
You specify a regular expression (java one) in pattern.

In testValidation.xhtml
<code>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:h="http://java.sun.com/jsf/html" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test Validation</title>
</head>
<body>
<h:messages/>
<f:view>

<h:form id="form">


<h:outputText for="name" value="Enter your name with small letters"/>
<h:inputText id="name" required="true" label="name">
  <f:validateRegex pattern="[a-z]+"/>
</h:inputText>
              

<h:commandButton action="ok" value="Validate" />
</h:form>
</f:view>
</body>
</html>
</code>

Display
No error message if lower case letters

Error message with upper case

Note:
You can verify or valid normally any regular expression here. If you try to validate a complex pattern (like e-mail), you'll get a complex error message too. One of the solutions will be to write your own error message in a properties file (message.properties for instance),put it in the package with classes. Tell faces-config.xml to load the file.

message.properties

javax.faces.validator.RegexValidator.NOT_MATCHED="E-Mail is not valid"


faces-config.xml

<code>
<faces-config>
....
....
<application>
<message-bundle>fr.iipt.ka.faces.messages</message-bundle>
</application>
....
....
</faces-config>
</code>

In testValidation.xhtml

<code>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:h="http://java.sun.com/jsf/html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test Validation</title>
</head>
<body>
<h:messages/>
<f:view>

<h:form id="form">


                <h:outputText for="email" value="Enter your e-mail"/>
                <h:inputText id="email" required="true" label="email">
                <f:validateRegex pattern="^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$"/>
                </h:inputText>
               

<h:commandButton action="ok" value="Validate" />
</h:form>
</f:view>
</body>
</html>
</code>


Display
First attempt with entered e-mail does not match "Regex"

And one that matched

Read more...

JSF Validation- Part 1

>> 11 May 2010




Validation is used to verify that a component get an expected value.

JSF has several standard validators, ready to use. You can also create your own custom validators

Note:
For simplicity interactions with beans are omitted

Some standard validators with examples :

DoubleRangeValidator,
Numeric validation (double or float), value must be between minimum and maximum values

LongRangeValidator,
Numeric validation (long or int)  value must be between minimum and maximum


LengthValidator
String validation, length of the String must be between minimum and maximum values

<f:validateLength minimum= maximum= />

Example :

<h:messages /> and label for <h:inputText are used to display error messages
This example will verify that the name entered must be between 3, and 20 characters

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:h="http://java.sun.com/jsf/html"
    
      >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test Validation</title>
</head>
<body>
<h:messages/>
<f:view>

<h:form id="form">
<h:outputLabel for="name" value="Enter Name"/>
<h:inputText required="true" label="name">
<f:validateLength minimum="3" maximum="20"/>
</h:inputText>
<h:commandButton action="ok" value="Validate" />
</h:form>
</f:view>
</body>
</html>


Display
If a String of a length less that 3 or maximum is entered, submission is ignored and an error message is displayed

Note:
It's possible to use only minimum, maximum or both

<f:validateDoubleRange minimum="" maximum=""

Example :

<h:messages /> and label are for displaying errors
Validator will verify if the entered double is in the specified range

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:h="http://java.sun.com/jsf/html"
    
      >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test Validation</title>
</head>
<body>
<h:messages/>
<f:view>

<h:form id="form">
<h:outputLabel for="name" value="Enter Name"/>
<h:inputText required="true" label="name">
<f:validateLength minimum="3" maximum="20"/>
</h:inputText>
<h:outputLabel for="double" value="Enter Double Value"/>
<h:inputText required="true" label="double">
<f:validateDoubleRange minimum="2.0" maximum="20.1" />
</h:inputText>
<h:commandButton action="ok" value="Validate" />
</h:form>
</f:view>
</body>
</html>


Display
First the entered value is less than the maximum, no problems. Then the entered value is Superior than the maximum.
 


<f:validateLongRange
This one will validate the entered long and verify if it's in the range

Example

<h:messages /> and label are for displaying errors

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:h="http://java.sun.com/jsf/html"
    
      >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test Validation</title>
</head>
<body>
<h:messages/>
<f:view>

<h:form id="form">
<h:outputLabel for="name" value="Enter Name"/>
<h:inputText required="true" label="name">
<f:validateLength minimum="3" maximum="20"/>
</h:inputText>
<h:outputLabel for="double" value="Enter Double Value"/>
<h:inputText required="true" label="double">
<f:validateDoubleRange minimum="2.0" maximum="20.1" />
</h:inputText>

<h:outputLabel for="long" value="Enter Long Value"/>
<h:inputText required="true" label="long">
<f:validateLongRange minimum="0" maximum="10" />
</h:inputText>

<h:commandButton action="ok" value="Validate" />
</h:form>
</f:view>
</body>
</html>


Display
In the first attempt nothing, the value is in the range specified
Second error message is displayed because value is greater than the maximum
Third, what display we'll get, if the value is not at all a Long?

Read more...

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP