mardi 22 février 2011

Simple exemple : JSF 2.0, PRIMEFACES 2.2.RC, EJB 3.1, JPA 2

In this tutorial we are going to start developing our rich web application using JSF 2 , PRIMFACES , EJB and JPA
we can create the project  using your preferred IDE ,the most convenient method of creating a new project is to use an IDE that supports it (for example, Eclipse with plugin, NetBeans, JDeveloper)
I will explain all of the steps to build an empty web application project using netbeans and glassFish 3 .
A simple insert into phone_book data base and show the list of ccontact saved here the script of creation
CREATE DATABASE phone_book

CREATE TABLE contact (
    id integer NOT NULL,
    name character varying(20),
    surname character varying(20),
    mobile_phone character varying(15),
    email character varying(100)
);

ALTER TABLE ONLY contact
    ADD CONSTRAINT contact_pkey PRIMARY KEY (id);
Download and install
Note - it is required to use java JDK 6  : to check for java installation in windows or linux use " java -version "  in command line

Creating the project

Here we will create the web application EAR , Open netBeans and go to
File > New Project > Java EE > Entreprise Aplication > Next
Put the name (PhoneBook for exemple) and location for your project go to next
NetBeans use GlassFish 3 default server the screen chould be like :


Netbeans create the structure of web application project
Now we will add JSF 2 :
Got to BookPhone-War > right click with mouse > in Categories go to Framwork > Java Server Face
( if you dont have jsf option framwork you need to update netBeans plugin go to tools > plugins ) and confirm add librairie

the web.xml is update and should look :

    
        javax.faces.PROJECT_STAGE
        Development
    
    
        Faces Servlet
        javax.faces.webapp.FacesServlet
        1
    
    
        Faces Servlet
        /faces/*
    
    
        30
    
    
        faces/index.xhtml
    


Now we will create jpa entity from data base


In PhoneBook-ejb go to source package > right click > New > Persistance > Entity classes from data base > next
We will create connection using jpa to database
Data source > choise New DataSource > put name like phone_book into jndi name input > next ower New Data Base connection should look

Than choise the data base schema must be public select contact table from availabe table > enter the entity package like com.project.phone.entity the Contact entity Class is
package org.project.entity;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@Entity
@Table(name = "contact")
public class Contact implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "name")
    private String name;
    @Column(name = "surname")
    private String surname;
    @Column(name = "mobile_phone")
    private String mobilePhone;
    @Column(name = "email")
    private String email;

    public Contact() {
    }

    public Contact(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getMobilePhone() {
        return mobilePhone;
    }

    public void setMobilePhone(String mobilePhone) {
        this.mobilePhone = mobilePhone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Contact)) {
            return false;
        }
        Contact other = (Contact) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.project.entity.Contact[id=" + id + "]";
    }

}

Now we will create the first welcome page contains a form to add person

lundi 21 février 2011

Upload files / image with JSF and primfaces

the current versions of the Java web standards (servlets, JSP, and JSF) do not offer any help for upload files or pictures. Fortunately, there are third-party frameworks, such as  Apache Commons File UploadApache Tomahowk Richfaces, and primfaces

Primfaces provide JSF components that go beyond the JSF specification. These components are compatible with the JSF 2 with a little of bug

This article aims to provide detailed steps to develop an exemple of how to upload file using jsf 2 and primfaces and how to show it again into xhtml file.

The example in this tutorial creates a web page named :

  • upload_file.xhtml : contains a form for upload picture
  • show_image.xhtml to show picture

Preaparing the exemple

We need those librairies into project class path:

After adding the JAR's to class path we need to make changes into web.xml :

              PrimeFaces FileUpload Filter        org.primefaces.webapp.filter.FileUploadFilter                                    thresholdSize            51200                               uploadDirectory            /tmpDir/                        PrimeFaces FileUpload Filter        Faces Servlet    

Before creating the JSF pages and managed bean , we need first to add ower class Utils in my last post Image to byte array and byte array to image
this methode will be used :

public static byte[] InputStreamToByte(InputStream fis) throws FileNotFoundException {        ByteArrayOutputStream bos = new ByteArrayOutputStream();        byte[] buf = new byte[1024];        try {            for (int readNum; (readNum = fis.read(buf)) != -1;) {                bos.write(buf, 0, readNum);                System.out.println("read " + readNum + " bytes,");            }            byte[] bytes = bos.toByteArray();            return bytes;        } catch (IOException ex) {            ex.printStackTrace();            return null;        }    }
and to create the jsf 2 managed bean which will be providing the required services for the JSF pages that will be created later dont forget getters and setters methode :
@ManagedBean@SessionScopedpublic class UploadImage { private StreamedContent image;    /**     * Used to upload image from jsf pages     * @param event     */    public String imageUpload(FileUploadEvent event) {        try {            /** Convert file from input stream to bytes */            byte[] bytearray = Utils.InputStreamToByte(event.getFile().getInputstream())             /*             * bytearray used to store picture into database              */              InputStream ist = new ByteArrayInputStream(bytearray);            /*             * StreamedContent Object used to show the picture in jsf pages             * we need to convert again bytearray to InputStream             */            image = new DefaultStreamedContent(ist, "image/jpg");            FacesMessage msg = new FacesMessage("Succesful picture is uploaded.");            FacesContext.getCurrentInstance().addMessage(null, msg);            /** we dont need to use faces-config to navigate in jsf 2 */            return "/show_image.xhtml"        } catch (Exception e) {            FacesMessage msg = new FacesMessage("Exception happen");            FacesContext.getCurrentInstance().addMessage(null, msg);            e.printStackTrace();            return null;        }    }}
Now, we are ready to create the first web page named upload_file.xhtml that contains a form to upload file
                                                                                                                               
Create the next web page named show_file.xhtml that contains a tag to show image
                                                                                                        
Note - you can add ajax fonction to show picture when upload just in your managed bean change imageUpload methode to retur void and copy p:graphicImage into upload_image.picture and add update="image" to p:fileUpload tag

dimanche 20 février 2011

Etude comparatif entre les framworks de présentation JEE

Voir le nombre important de Framework destinés aux développements de la couche présentation en java j2ee, le choix d’une solution se base sur les principales fonctionnalités et besoins et ressources (qualité, interopérabilité, évolutive ainsi que le temps de production de maquettes de la charte graphique et la présentation des interfaces attractives). Les plus connus dans la communauté freeware sont JSF-Richfaces , Spring MVC , Struts GWT, WICKET ,  FLEX  .

WICKET

Wicket est un framework à base de composants, à l'inverse des frameworks MVC  Modèle-Vue-Contrôleur traditionnels à base d'actions, comme Apache Struts ou Spring MVC par exemple

Avantages : 

  • Utilise exclusivement les pages XHTML comme technologie de présentation. De plus, il n'y a aucune logique à écrire directement dans les pages XHTML.
  • Wicket permet de séparer l’HTML et le code Java.
  • Véritable séparation entre la partie cliente et la partie serveur.
  • Pas de fichier de configuration : une classe définie dans le web.xml sert de point d’entrée Pas de configuration complexe (XML).
  • Navigation entre les pages définies en Java.

Limites

  • Wicket stocke beaucoup d’informations en session et il est donc trop lourd pour gérer plusieurs centaine d’utilisateurs simultanés. 
  • A l’usage, on se rend compte que l’intégration manuelle avec le JavaScript n’est pas évidente. Toujours ces histoires d’Id générés qui rendent plus compliqué un framework orienté Composants.

GWT Google Web Toolkit

L’outil de Google est dédié à la présentation. « Il permet de coder 5 fois plus vite la couche graphique Web de son application ». GWT repose sur un modèle en composant. Par exemple, il dispose d’objets Champ texte, Tableau… Chacun de ces composants supporte les CSS et est donc potentiellement skinnable.

Avantages :

  • Côté intégration à un modèle de page, il n’y aurait aucun souci. Il suffit de partir du HTML et d’appliquer les styles au composant GWT

Limites :

  • Manque guidé de bonnes pratiques et de la documentation en général.
  • Il n’y a que des composants graphiques « simples ». Si l’on veut utiliser des composants plus évolués, il faut soit les coder ou bien se tourner vers des librairies de widgets GWT Open Source « non Google » (avantage : elles offre des composant telle que agenda facile à intégrer).

JSF Java Server Faces

Java Server Faces est un Framework pour la conception d'interfaces graphiques Web en Java.

JSF s'attache donc à :

  • Faciliter l'écriture d'interface à partir d'une bibliothèque de contrôles.
  • Gérer automatiquement l'état HTTP entre client et serveur (en cas de Postback par exemple)
  • Fournir un modèle simple pour la gestion des évènements coté client et coté serveur
  • Autoriser les créations ou l'enrichissement de composants graphiques utilisateur (custom)

 

 

JSF-Richfaces , JPA, EJB, avec Seam

Un petit article pour vous montrer comment créer une application de type CRUD avec JSF 1.2,  Jboss-seam EJB et JPA ensemble.

À la fin de ce petit article, vous allez créer une page qui affiche une liste des clients existants dans la base de données, modifier les enregistrements et une fonction permettant aux utilisateurs d'ajouter un nouveau client dans la base.


  • JSF - Java Server Face : est un Framework pour la conception d'interfaces graphiques Web en Java.
  • JPA - Java Persistence API est l'API de persistance fournie par JEE5. Cette API se base en grande partie sur les concepts apportés par Hibernate
  • EJB 3 - Entreprise Java Bean sont des composants serveurs, permettent de découpler le code client de l’interface

Le développement d'applications web basées sur J2EE se résume souvent à assembler un ou plusieurs frameworks (dans notre cas JSF,EJB,JPA par la suite la librairie des composantes Richfaces ), parfois pour chaque couche applicative, ces frameworks étant basés ou no sur des standards et bien souvent en provenance de la communauté open source.

Jboss-seam : framework d'intégration JEE 5, Seam est livré avec tous les composants nécessaires au développement d'une application web et, en plus, il permet de simplifier grandement les développements grâce à son modèle de composants unifié.

Préparation de l'exemple

Pour cette exemple, vous devez dans un premier temps télécharger

Eclipse comme Editeur version 3.5

Plugin Jboss tools pour la génération de code,wizards...

Serveur d'application Jboss j'ai choisi la version 5.1

Seam version 2

Instalation de l'exemple

samedi 19 février 2011

Save images into database

This exemple show you how to store byte array in data base and retrive it again.

To do this we need to use the Utils Java Class in my last post ( image to byte array and byte [] to image using java ) and we can chose Postgres or MySql data base to store data .

Many devlopper try to store data in Varchar format or string varbinary,
Saving the byte[] as VarBinary(MAX) is ok. But, the problem comes when retrieving it as byte array.

In this exemple i will explain how to

switch between images, bytes postgres, and image again using java

( you can use other data base )

The first step, we need to make a Postgres databases to store our images data. Make a database called “imagedb” on your Postgres or MySQL  database, then create a table called “image” the sql create script :

CREATE TABLE image
(
  id integer NOT NULL,
  name character varying(255),
  image bytea,
)

if you are using MySql change type of image from bytea to blob.

The id field represent id of image, name field represent name of image, and the dates is field that used to store information when the image uploaded.

Now we need to use ower Utils.ImageToByte methode in my last post from image to bytes

public static byte [] ImageToByte(File file) throws FileNotFoundException{
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);      
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
        }
        byte[] bytes = bos.toByteArray();
     
     return bytes; 
    }

Next step is to make a JDBC connection, i prefer to use JPA but now just to show you how we can insert byte to database

To do this i created two class: the first one is to create connection to data base named ConnectDB.java, the second one for SQL Query and finaly we need to create ower main methode for test

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectDB {

 Connection mySqlConnection;
 String URL = "jdbc:postgresql://localhost:5432/imagedb";
 String pwd = "root";
 String user = "postgres";

 public Connection getConnection() {

  try {
   Class.forName("org.postgresql.Driver");

  } catch (Exception e) {
   System.out.println("Driver Problem");
   e.printStackTrace();
  }
  try {
   if (mySqlConnection == null) {
    mySqlConnection = DriverManager.getConnection(URL, user, pwd);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return mySqlConnection;
 }

}

Don't forget to add the JDBC jar into your class path.

The second Java Class is the Class used to execute SQL Query for insert and select Data :

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.*;

import java.sql.Statement;

public class ConnectionBdImage {

 public byte[] getImage(int id) {
  byte[] byteImg = null;
  bd connect = new bd();
  Connection connection = null;
  try {
   connection = connect.getConnection();
   // String byteImg="";
   PreparedStatement ps = connection
     .prepareStatement("SELECT image FROM image WHERE id = ?");
   ps.setInt(1, id);
   ResultSet rs = ps.executeQuery();
   while (rs.next()) {
    byteImg = rs.getBytes(1);
    // use the data in some way here
   }
   rs.close();
   ps.close();

   return byteImg;
  } catch (Exception e) {
   // TODO: handle exception
   return null;
  }

 }

 public void addImage(byte[] img, int id) {
  bd connect = new bd();
  Connection connection = null;
  try {
   connection = connect.getConnection();

   Statement statement = connection.createStatement();

   PreparedStatement ps = connection
     .prepareStatement("INSERT INTO image VALUES (?, ?, ?)");
   ps.setInt(1, id);
   ps.setBytes(2, img);
   ps.setString(3, "test");

   ps.executeUpdate();
   ps.close();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    connection.close();

   } catch (Exception e) {
    // TODO: handle exception
   }
  }

 }
    

getImage methode is to get image from data base and addImage is to store it into DB.

Finaly we need main methode to store Data :

public class ConvertImage {   
 
    public static void main(String[] args) throws FileNotFoundException, IOException {
     
     ConnectionBdImage bd = new ConnectionBdlogin();
     
     String fileSource = "C:/imgSource/image.jpg";
     String fileDestination = "C:/imgDestination/destination.jpeg";
     
     try {
      
      byte [] byteImage = Utils.ImageToByte(new File(fileSource));
      
      bd.addImage(byteImage, 1);
      System.out.println(org.postgresql.util.Base64.encodeBytes(bd.getImage(1)));
     Utils.byteToImage(bd.getImage(1), new File(fileDestination));
  } catch (Exception e) {
   e.printStackTrace();
  }      
    }
     
}

Using the above steps you can retrieve and display the image from the database and store it into file or display to the web page.

vendredi 18 février 2011

Image to byte array and byte array to image

Il existe déjà des milliers d'exemple sur internet sur comment convertire
une image vers un tableau des byte [] en java et vis versa, récement j'ai eu l'occasion de travailer sur un petit projet qui  m'oblige a convertire une image vers un tableau de bytes, stocker dans une base des données et de récuperer l'image par la suite. Ma recherche sur internet n'etait pas satisfaisante vu que j'arrive pa
a convertire les images de n'importe types gif, tiff, jpeg, jpg, png ...

This Java Class contains two methode for how to convert image png, tiff, jpeg, jpg, gif to an array of byte [] in Java.
The first one take the path of file " c:/file_path/image.png " and return array of bytes





public static byte [] ImageToByte(File file) throws FileNotFoundException{
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);      
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
        }
        byte[] bytes = bos.toByteArray();
     
     return bytes; 
    }

This Second one is to convert back from bytes array byte [] to jpeg image





public static void byteToImage(byte [] bytes,File imageFile) throws IOException{
     
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator readers = ImageIO.getImageReadersByFormatName("jpeg");
 
        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; // File or InputStream, it seems file is OK
 
        ImageInputStream iis = ImageIO.createImageInputStream(source);

        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
 
        Image image = reader.read(0, param);
        //got an image file
 
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
      
        Graphics2D g2 = bufferedImage.createGraphics();
        g2.drawImage(image, null, null);
 
        ImageIO.write(bufferedImage, "jpeg", imageFile);
        //"jpeg" is the format of the image
        //imageFile is the file to be written to.
 
        System.out.println(imageFile.getPath());
     
 
    }

Our Java Utils Class is now :


import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;


public class Utils {

 public static byte [] ImageToByte(File file) throws FileNotFoundException{
      //code of ImageToByte
     return bytes; 
    }
    
    public static void byteToImage(byte [] bytes,File imageFile) throws IOException{
      // code of byteToImage
    }
}


Simple main java class for test :


public static void main(String[] args) {
     
    try {
       byte [] bytes = Utils.ImageToByte(new File("/home/path_source/image.png"));
      Utils.byteToImage(bytes,new File("/home/path_destination/destination_image.png"));
  }
     catch (Exception e) {
   e.printStackTrace();                                          
     }       
    }




In other post we will use this class to store byte into database ans show picture into html