dimanche 20 mars 2011

Etude comparatif entre les framworks de présentation Java / 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)

 

 


mercredi 16 mars 2011

Simple exemple - application web : 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

mardi 15 mars 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 

lundi 14 mars 2011

Save images into database Postgres with Java

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.