mercredi 31 décembre 2014

Spring4 / Hibernate4 / JSF2 / Primefaces5 jee web application skull

In this article we will try to build an entire skull of jsf2/spring4 application, welwill use hibernate4 to manage persistency, use bundles for internalization and primefaces 5 in view layer.The application will be mavenized.

The result architecture will have this behavior:

  1. First Step is to create a maven project based on webapp archtype

    mvn archetype:generate -DartifactId=travel -DarchetypeArtifactId=maven-archetype-webapp -DarchetypeVersion=1.0 -DinteractiveMode=false
    (how to work with maven nad elipse ?
     this link is useful by A.Mekki)
  2. Next step is to add correct dependencies for artifacts that we'll our pom.xml

    MySQL jdbc connector
    Hibernate4 (requires dbcp2)
    JSF 2 api/impl and servlet

    we will add also repositories
    our pom.xml will be

       Repository for JSF2
       Repository for Maven2
        PrimeFaces Maven Repository
       Java Dev Net Repository
       Spring Portfolio Milestone Repository
       Spring Portfolio snapshot Repository
       jboss Repository
     Repository for Maven2
       Spring External Dependencies Repository
       Jboss Repository for Maven 
       JBoss Public Repository Group       

    Note here we have used version properties to make pom more evolutive
  3. Next step is to configure web.xml (typical jsf webapp, web.xml with listner for spring)

      Faces Servlet
      Faces Servlet

  4. Now we write our faces-config.xml, thanks to annotation, this configuration file is too light

    We have used here a resource-bundle to manage internalization of messages and labels:
    In this line:
     we told to jsf that our file is located in package its name is
    NB: is a resource file: it must be located under WEB-INF/classes in deployement  folder :
    here under eclipse we have configured in deployement assembly onglet  a copy of src/main/resources to WEB-INF/classes contains these few lines: applicationTitle=Traveler
    userId=ID Utilisateur
    userName=Nom utilisateur

  5. Now we go ahead to applicationContext.xml which contains declaration of spring beans and hibernate properties.

    In order to seperate real configuration from database access configuration we will put database access informations in a separate file called under WEB-INF. folder

    We have told to spring that we will work with annotation and application beans will be in sub packages of  "
    <context:component-scan base-package="" />

    We have to tell hibenate where he will find models
    <property name="packagesToScan" value="" />

    Here is a complete applicationContext.xml
    and here is the listing of

  6. Now we have the choice : finish the view layer with its facelets or attack an entity to display it in th view layer.
    Personally i prefer finish the view for a simple reason :
    When a standard page of our application is displayed, then any problem that will appear in integration of any page will be the result of a programmation mistake.

    Ok, we continue,
    we start by th building of a template for the application:
      A- create a folder templates and under it a folder common.

    B- Create the commonLayout.xhtml file that will descibe the design of a common page in the application, in our casse commonLayout is composed by 3 files a header, a content and a footer  (here we have a one column deisgn).

    here is the listing of the 4 files:



    This is default content


    Note that next the composition called content in the commonContent.xhtml will be overrided each time a page is shown
    C- add the index.jsp page that will redirect to a default xhtml page that will be considered a the entry point of the application.
    index.jsp under the root(webapp):

    our application will show directly a listing of users inserted previously in database.
    css and js files have to be under folder resources under webapp otherways they will not be loaded.
  7. Now we will create the different layers of the application:
    a model layer
    a dao layer
    a service layer
    a managedbeans layer to interact with jsf views

    Considering that we have a mysql 3 tables under schema travel with this descriptions:
    mysql>  show tables;
    | Tables_in_travel |
    | profile          |
    | user_profile     |
    | utilisateur      |
    3 rows in set (3.36 sec)
    mysql> describe utilisateur;
    | Field     | Type        | Null | Key | Default | Extra          |
    | usr_id    | int(11)     | NO   | PRI | NULL    | auto_increment |
    | usr_login | varchar(45) | YES  |     | NULL    |                |
    | usr_pwd   | varchar(45) | YES  |     | NULL    |                |
    3 rows in set (2.76 sec)
    mysql> desc profile;
    | Field   | Type        | Null | Key | Default | Extra          |
    | prf_id  | int(11)     | NO   | PRI | NULL    | auto_increment |
    | prf_lib | varchar(45) | NO   | UNI | NULL    |                |
    2 rows in set (0.28 sec)
    mysql> desc user_profile;
    | Field         | Type    | Null | Key | Default | Extra          |
    | usrprf_id     | int(11) | NO   | PRI | NULL    | auto_increment |
    | prf_id        | int(11) | NO   | MUL | NULL    |                |
    | usr_id        | int(11) | NO   | MUL | NULL    |                |
    | usrprf_active | int(11) | NO   |     | 0       |                |
    4 rows in set (2.53 sec)
  8. Model layer (just one class (utilisateur))

    Note we will this tree of packages and classes

    // Generated 25 nov. 2014 14:54:59 by Hibernate Tools 3.4.0.CR1
    import java.util.HashSet;
    import java.util.Set;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import static javax.persistence.GenerationType.IDENTITY;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;
     * Utilisateur generated by hbm2java
    @Table(name = "utilisateur", catalog = "travel")
    public class Utilisateur implements {
     private static final long serialVersionUID = 8276067938930706574L;
     private Integer usrId;
     private String usrLogin;
     private String usrPwd;
     private Set userProfiles = new HashSet(0);
     public Utilisateur() {
     public Utilisateur(String usrLogin, String usrPwd,
       Set userProfiles) {
      this.usrLogin = usrLogin;
      this.usrPwd = usrPwd;
      this.userProfiles = userProfiles;
     @GeneratedValue(strategy = IDENTITY)
     @Column(name = "usr_id", unique = true, nullable = false)
     public Integer getUsrId() {
      return this.usrId;
     public void setUsrId(Integer usrId) {
      this.usrId = usrId;
     @Column(name = "usr_login", length = 45)
     public String getUsrLogin() {
      return this.usrLogin;
     public void setUsrLogin(String usrLogin) {
      this.usrLogin = usrLogin;
     @Column(name = "usr_pwd", length = 45)
     public String getUsrPwd() {
      return this.usrPwd;
     public void setUsrPwd(String usrPwd) {
      this.usrPwd = usrPwd;
     @OneToMany(fetch = FetchType.LAZY, mappedBy = "utilisateur")
     public Set getUserProfiles() {
      return this.userProfiles;
     public void setUserProfiles(Set userProfiles) {
      this.userProfiles = userProfiles;
  9. Dao layer, all classes under are interfaces, who knows if we will change hibernate by another orm ?
    implementations are under
    First of all web begin with generic dao classes:
    import java.util.List;
    public interface GenericDao {
        public T find(I id);
        public List findAll();
        public void delete(T obj);
        public void saveOrUpdate(T obj);
    an implementation of this class is
    import java.util.List;
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.transaction.annotation.Transactional;
    public abstract class GenericDaoImpl implements GenericDao{
         SessionFactory sessionFactory;
        private Class type;
        public GenericDaoImpl(Class type){
         this.type = type;
        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        public SessionFactory getSessionFactory() {
            return sessionFactory;
     @Transactional(readOnly = true)
        public T find(I id) {
            return (T) getSessionFactory().getCurrentSession().get(type, id);
     @Transactional(readOnly = true)
        public List findAll(){
         return (List) getSessionFactory().getCurrentSession().createQuery("from "+type.getName()).list();     
        public void delete(T obj) {
        public void saveOrUpdate(T obj) {
    NB: this class is under impl subpackage.
    @Autowired annotation is present to ensure the injection of sessionFactory bean
    Now wel will create an interface for UserDao ; here we don't need anything expect methods in GenericDao
    public interface UserDao extends GenericDao {

    a possible implementation for this interface is
    import org.springframework.stereotype.Repository;
    public class UserDaoImpl extends GenericDaoImpl implements UserDao {
     public UserDaoImpl(){
     public UserDaoImpl(Class type) {
    Note the presence og @Repository annotation it's needed for dao bean injection in service bean
    Ok now we have set the Dao layer.
  10. We pass to service layer: same idea it will be interfaces for eache service and one/many implementation for each interface
    let's start with user interface
    import java.util.List;
    //since we willl only display list of users
    public interface UserService {
     public List getUsers();

    a possible implementation for this interface is
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    public class UserServiceImpl implements UserService {
     UserDao userDao; 
     public List getUsers() {
      return userDao.findAll();
     public UserDao getUserDao() {
      return userDao;
     public void setUserDao(UserDao userDao) {
      this.userDao = userDao;
    Note the presence of @Service annotation needed for service object injection in the managed bean
  11. Last step is to create our managedbean !
    import java.util.List;
    import javax.annotation.PostConstruct;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.SessionScoped;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    public class ListUsersBean implements Serializable {
     private static final long serialVersionUID = 6675856254221490117L;
        private UserService authService;
        private List users;
        public void init() {
            users = authService.getUsers();
     public List getUsers() {
      return users;
     public void setUsers(List users) {
      this.users = users;
     public UserService getAuthService() {
      return authService;
     public void setAuthService(UserService authService) {
      this.authService = authService;
  12. We will now display all users :), then we will return to our application and we will create a folder called faces under the webapp and create our xhtml page editUsers.xhtml
  13. we have that then :

    just a remark; if you want to use primefaces themes or skins
    - go to this url -

  14. comments are welcome!

vendredi 21 novembre 2014

how debug jsf/j2ee web application

to debug jsf application or a j2ee web application, you can set PROJECT_STAGE context parameter to Developement like this (in the web.xml file):

you can turn this parameter to Production to stop debug. 

samedi 12 juillet 2014

[Problème] 404 - Component not found (joomla 3 back office)

This article is for joomla components / modules developers.
Usually you have this error when trying to run/configure your joomla 2.5 component on joomla 3.x plateform.
This error is due to non 100% compatibility of 2.5 components with joomla 3.x
For some simple components proceed as follows :
  1. In every file that references DS variable
    put at the begin :
    if(!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
  2. rename admin.your_component.php file in admin section to your_component.php
  3. Change each JController or JView classes reference to JControllerLegacy or JViewLegacy
  4. Don't forget to do that to the 2 sections site and admin

This link may be useful

jeudi 26 juin 2014

Jquery ready function and problems with media queries

yesterday i have faced a problem
i had  to make a design responsive according to a psd
i've found that some blocks that were injected by jquery thanks to
and mydiv had two styles
@media screen and (max-width: 767px){
    #mydiv STYLE1
@media screen and (min-width: 768px){
    #mydiv STYLE2
i found that mydiv had the style 2 and was the child of block 1 which is incorrect for me

finally it was wrong to use jQuery(function(){} which fires before application of media queries
i've used modernizr library
with this hack


    function doneResizing() {

        if('screen and (max-width:767px)')) {

        else if('screen and (min-width:768px)')) {


    var id;
    $(window).resize(function() {
        id = setTimeout(doneResizing, 0);


that's all

mercredi 18 juin 2014

joomla back office Failed to parse time string (jerror) at position ....

hello moto;
Pre conditions: Joomla 3.0
i've encountred this error when migrating website from a server to another...
front office worked correctly
back office  no
Try to change $log_path et $tmp_path in configuration.php file
To know the correct directory
create a php file simple.php
echo getcwd (  );
copy it at the root of the site
invoke it from web browser
get your directory
copy it an d and add /logs for logs and tmp for tmp dir

lundi 19 mai 2014

Prestashop déclaration de variable globale de configuration (Module FB/Twitter pour prestashop)

Lors de la création d'un module spécifique sous presta, nous avons souvent besoin de stocker quelques variables dans la base de données du système.
Dans le cas ou la variable est simple et que l'utilisation d'un CRUD  n'est pas aussi nécessaire, l'utilisation d'une variable système peut suffire, on parle d'une variable de configuration.
Comment la créer ?
c'est simple le fait de mettre à jour une variable de configuration qui n'existe pas la crée et lui affecte la valeur indiquée.

On met ça dans la fonction installe de notre module si vous voulez.

Comment la lire?
c'est simple aussi
Configuration::get("MA_VARIABLE") retourne la variable

Dans ce qui suit, j'ai crée un petit exemple qui illustre ce comportement:
Un module qui affiche' 2 icones (fb+twitter) dont les adresses sont configurables depuis le back-office

block-fbtwitter (lien de téléchargement)

screen shot

dimanche 23 mars 2014

Module JCounter, visits counter for joomla

Here is JCounter module, a visits counter for joomla 2.5/3.x.
You must unzip file first and install the two components (plugin then module) in order to use it.
Current version is 1.3

Why plugin ?
When webmaster decide to disable this module on some web pages for design reasons or other, plugin continue to increase visits number, everwhen  module is disabled on that page.

 Download link for joola 2.5 and joomla 3.x

Thanks for your suggestions

Module Evolution
April 2011 version 1.0 for joomla 1.5
March 2014  version 1.1 joomla 2.5/ 3.x + introduction of the plugin ( binaries of this version were removed from repository due to wrong binaries upload)
July 2014 version 1.2
September 2014 version 1.3 added parameters text before and after / display font digits

mardi 11 mars 2014

Merge Two prestashop web sites into one multi shop website (ps 1.5.x)

Let's start by pre-conditions
www1 and www2  are two websites using ps 1.5.x
=> then we have two domains (or domain and subdomain ), 2 databases and 2 prestashop working folders.

how merge ?

1- login on BO of www1
2- Activate multishop support (preferences-> generales) (may be translated) and register
3- Now may see a new menu item "multi-shop" in advanced parameters menu.

now ps is ready to work on multishop  mode

4- copy the theme of www2 in the themes directory of www1
    => if the theme of www2 (the second web site) has the same name as the first one, you must change its name then (let say 'theme2')

5- Now enter the menu item multi-shop (step 3)

you will see at the left a tree but with only one item (the name of www1)

6- Click add a shop
  i- enter the name of your site (www2)
  ii- let the two combos as they are
  iii- choose the theme (step 4 normally)
   you may then choose a least one category (default) from the tree of categories
 iv- import data ? no

Now we have to link our shop to its  url
7- Click add link
 enter web site surl of site www2 (exp: in both http and ssl modes

8- Don't forget to activate url rewriting !
(preferences -> SEO and URLs )

Great now it will not work surely :)

9- What's the problem ?
We are searching to merge data and files => one BO (back office) and one global folder containing the two sites.
In Cpanel /plesk/etc ....
www1 -> xxx/public_html/www1
www2-> xxx/public_html/www1

samedi 15 février 2014

Prestashop The database selection cannot be made.

when migrating prestahsop from one web site to other 'The database selection cannot be made.' error happened... although my user had ALL PRIVILEGES 
privs ...
granting explicit privilerges to my user (select , insert, duplicate etc ...) solved the problem.

grant select on ON db_ps.* TO 'your_user'@'host';
grant insert on ON db_ps.* TO 'your_user'@'host';
grant delete on ON db_ps.* TO 'your_user'@host';
grant update on ON db_ps.* TO 'your_user'@'host';

or simply

grant SELECT,INSERT,UPDATE,DELETE ON `db_ps`.* TO 'your_user'@'host';

MySQL doc here

mercredi 8 janvier 2014

Prestashop create admin controller with back office overload

this post talk about the implementation of admin controller in prestashop and tpl file, in cases we are not using standard CRUD operations on database tables via dao models(see ObjectModel mother class)
if your are interested by the standard way (in major cases, this article can help you)
if your template does not meet with usual templates (list, form, toolbar ....)
you can :

1- create your tpl file
2- put it in admin/themes/the_theme/template

3- set the template at the constructor by wrting:

    public function __construct() {
        $this->template = 'your____tpl.tpl';
you can see the source of adminController
it may be helpful