mercredi 18 septembre 2013

Simple CRUD Using JSF (standard) and MySQL with netbeans and Tomcat

The Data
  • The database (an example)
create database TestDB;
use TestDB;


CREATE TABLE TestDB.`users` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(45) DEFAULT NULL,
  `lastname` varchar(45) DEFAULT NULL,
  `dob` date DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
The handy ORM

  • The entity (POJO)
public class User {

    private int userid;
    private String firstName;
    private String lastName;
    private Date dob;
    private String email;
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Date getDob() {
        return dob;
    }
    public void setDob(Date dob) {
        this.dob = dob;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "User [userid=" + userid + ", firstName=" + firstName
                + ", lastName=" + lastName + ", dob=" + dob + ", email="
                + email + "]";
    }    
}
  • The DAO (insert, select, update, delete)
1 
 2 package dao;
 3 
 4 import entities.User;
 5 import gm.GM;
 6 import java.sql.Connection;
 7 import java.sql.PreparedStatement;
 8 import java.sql.ResultSet;
 9 import java.sql.SQLException;
10 import java.sql.Statement;
11 import java.util.ArrayList;
12 import java.util.List;
13 import javax.naming.NamingException;
14 
15 /**
16  *
17  * @author pascalfares
18  */
19 public class UserDao {
20     public static void addUser(User user) throws SQLException, NamingException {
21             Connection connection = GM.getTestDB().getConnection();
22             PreparedStatement preparedStatement = connection
23                     .prepareStatement("insert into users(firstname,lastname,dob,email) values (?, ?, ?, ? )");
24             // Parameters start with 1
25             preparedStatement.setString(1, user.getFirstName());
26             preparedStatement.setString(2, user.getLastName());
27             preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
28             preparedStatement.setString(4, user.getEmail());
29             preparedStatement.executeUpdate();
30 
31       
32     }
33 
34     public static void deleteUser(int userId) throws NamingException, SQLException {
35         Connection connection = GM.getTestDB().getConnection();
36             PreparedStatement preparedStatement = connection
37                     .prepareStatement("delete from users where userid=?");
38             // Parameters start with 1
39             preparedStatement.setInt(1, userId);
40             preparedStatement.executeUpdate();
41 
42     }
43 
44     public static void updateUser(User user) throws NamingException, SQLException {
45         Connection connection = GM.getTestDB().getConnection();
46             PreparedStatement preparedStatement = connection
47                     .prepareStatement("update users set firstname=?, lastname=?, dob=?, email=?" +
48                             "where userid=?");
49             // Parameters start with 1
50             preparedStatement.setString(1, user.getFirstName());
51             preparedStatement.setString(2, user.getLastName());
52             preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
53             preparedStatement.setString(4, user.getEmail());
54             preparedStatement.setInt(5, user.getUserid());
55             preparedStatement.executeUpdate();
56 
57         
58     }
59 
60     public static List<User> getAllUsers() throws NamingException, SQLException {
61         List<User> users = new ArrayList<User>();
62         Connection connection = GM.getTestDB().getConnection();
63             Statement statement = connection.createStatement();
64             ResultSet rs = statement.executeQuery("select * from users");
65             while (rs.next()) {
66                 User user = new User();
67                 user.setUserid(rs.getInt("userid"));
68                 user.setFirstName(rs.getString("firstname"));
69                 user.setLastName(rs.getString("lastname"));
70                 user.setDob(new java.util.Date(rs.getDate("dob").getTime()));
71                 user.setEmail(rs.getString("email"));
72                 users.add(user);
73             }
74         
75 
76         return users;
77     }
78 
79     public static User getUserById(int userId) throws NamingException, SQLException {
80         User user = new User();
81         Connection connection = GM.getTestDB().getConnection();
82             PreparedStatement preparedStatement = connection.
83                     prepareStatement("select * from users where userid=?");
84             preparedStatement.setInt(1, userId);
85             ResultSet rs = preparedStatement.executeQuery();
86 
87             if (rs.next()) {
88                 user.setUserid(rs.getInt("userid"));
89                 user.setFirstName(rs.getString("firstname"));
90                 user.setLastName(rs.getString("lastname"));
91                 user.setDob(rs.getDate("dob"));
92                 user.setEmail(rs.getString("email"));
93             }
94        
95         return user;
96     }
97 }
98 
The UI

  • The ManagedBean
Create the UserControl managedBean


 1 package mb;
 2 
 3 import dao.UserDao;
 4 import entities.User;
 5 import java.sql.SQLException;
 6 import java.util.List;
 7 import javax.faces.bean.ManagedBean;
 8 import javax.faces.bean.SessionScoped;
 9 import javax.naming.NamingException;
10 
11 /**
12  * A minimal Managed Bean for CRUD 2 attributes
13  * one for current User
14  * one for the list of users
15  * @author pfares
16  */
17 @ManagedBean
18 @SessionScoped
19 public class UserControl {
20     private User selectedUser;
21     private List<User> lusers;
22     /**
23      * Creates a new instance of UserControl
24      */
25     public UserControl() {
26         selectedUser=new User();
27     }
28 
29     /**
30      * @return the selectedUser
31      */
32     public User getSelectedUser() {
33         return selectedUser;
34     }
35 
36     /**
37      * @param selectedUser the selectedUser to set
38      */
39     public void setSelectedUser(User selectedUser) {
40         this.selectedUser = selectedUser;
41     }
42 
43     /**
44      * @return the lusers
45      */
46     public List<User> getLusers() throws NamingException, SQLException {
47         lusers=UserDao.getAllUsers();
48         return lusers;
49     }
50 
51     /**
52      * @param lusers the lusers to set
53      */
54     public void setLusers(List<User> lusers) {
55         this.lusers = lusers;
56     }
57     
58     public String create() throws SQLException, NamingException {
59         UserDao.addUser(selectedUser);
60         
61         return "index";
62         
63     }
64 }

Minimal pages : List Users and Create Users
1 <?xml version='1.0' encoding='UTF-8' ?>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 3 <html xmlns="http://www.w3.org/1999/xhtml"
 4       xmlns:h="http://java.sun.com/jsf/html"
 5       xmlns:f="http://java.sun.com/jsf/core">
 6     <h:head>
 7         <title>Facelet Title</title>
 8     </h:head>
 9     <h:body>
10         <f:view>
11             <h:form>
12                 <h:dataTable border="1" value="#{userControl.lusers}" var="item">
13                     <h:column>#{item.firstName}</h:column>
14                     <h:column>#{item.lastName}</h:column>
15                     <h:column>#{item.userid}</h:column>
16                     <h:column>#{item.email}</h:column>
17                     <h:column>
18                         <h:outputText value="#{item.dob}" />
19                     </h:column>
20                 </h:dataTable>
21             </h:form>
22         </f:view>
23 
24     </h:body>
25 </html>
===
1 <?xml version='1.0' encoding='UTF-8' ?>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 3 <html xmlns="http://www.w3.org/1999/xhtml"
 4       xmlns:h="http://java.sun.com/jsf/html"
 5       xmlns:f="http://java.sun.com/jsf/core">
 6     <h:head>
 7         <title>Crud Example : Create a user</title>
 8     </h:head>
 9     <h:body>
10         <f:view>
11             <h:form>
12                 <h:outputLabel value="Nom" for="nom" />
13                 <h:inputText id="nom" value="#{userControl.selectedUser.lastName}" />
14                 <h:outputLabel value="PreNom" for="prenom" />
15                 <h:inputText id="prenom" value="#{userControl.selectedUser.firstName}" />
16                  <h:outputLabel value="Email" for="email" />
17                 <h:inputText id="email" required="true" label="email" size="40"
18                              requiredMessage="Please enter your email address."
19                              validatorMessage="Invalid email format"
20                              value="#{userControl.selectedUser.email}">
21                     <f:validateRegex
22                         pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />
23                 </h:inputText>
24                 <h:message for="email" />
25                 <h:inputText value="#{userControl.selectedUser.dob}" >
26                     <f:convertDateTime pattern="dd-MM-yyyy" />
27                 </h:inputText>
28                 <h:commandButton action="#{userControl.create()}" value="Create" />
29             </h:form>
30         </f:view>
31     </h:body>
32 </html>

samedi 14 septembre 2013

PrimeFaces EL Extensions for UI Authorization


  • #{p:ifGranted(‘ROLE_ADMIN’)} 
  • #{p:ifAllGranted(‘ROLE_EDITOR, ROLE_APPROVER’)} 
  • #{p:ifAnyGranted(‘ROLE_USER, ROLE_ADMIN’)} 
  • #{p:ifNotGranted(‘ROLE_GUEST’)} 
  • #{p:remoteUser()} 
  • #{p:userPrincipal()} 
<h:commandButton value="Delete" rendered="#{p:ifGranted('ROLE_ADMIN')}" />
<p:commandButton value="View" disabled="#{p:ifNotGranted('ROLE_USER, ROLE_ADMIN')}" />

Java EE7 : Glassfish 4

Glassfish4




To learn more about the new Java EE 7 capabilites, read the Java EE 7 Tutorial.

Java Server Face

JavaServer(TM) Faces technology simplifies building user interfaces for JavaServer applications. Developers of various skill levels can quickly build web applications by: assembling reusable UI components in a page; connecting these components to an application data source; and wiring client-generated events to server-side event handlers.
visit for download and docs : Glassfish Majora : https://javaserverfaces.java.net/

vendredi 6 septembre 2013

Apache OpenJPA project

Configuring Security in Glassfish v3 – Creating a JDBC Realm


Configuration d'un domaine de sécurité (Realm) dans Glassfish v3 pour coorespondre avec votre base de données MySQL préexistante contenant les informations d'identification utilisateur (2 tables users et group ou rôles). C'est plus facile que vous ne le pensez. Voyez plutôt:
 //TODO translate french
Step 1 – Create a connection pool and JNDI source
Make sure that the current MySQL JDBC connector jar file is in the following directory:-
$GLASSFISH_HOME/glassfish/lib

Restart your app server then fire up the admin console and from the navigation tree on the left click:-
JDBC -> Connection_Pools -> New

Give your connection pool a name and fill in the rest of the fields as shown below, click next.
add-connection-pool
Add new connection pool

The datasource classname should have populated to
com.mysql.jdbc.jdbc2.optional.MysqlDataSource

Next we need to fill in a few fields in the ‘additional properties’ section:-
  • user – (your database user name)
  • password – (the password for your database user)
  • databaseName – (your database name)
  • portNumber – (usually 3306)
  • serverName – (e.g. localhost)
  • URL – jdbc:mysql://localhost:3306/your_DB_name_here

Save these settings and then click ‘ping’ to test everything is ok:-
The message you should see

From the navigation tree on the left click:-
JDBC -> JDBC_Resources -> New

Give the Resource a name and select your connection pool from the previous step then go ahead and hit the save button.
New JDBC Resource

Step 2 – Create a new security realm
Ok, so before we  point Glassfish to our database, we’ll need to have the following information from your database available:-
  1. The name of the table in which your user’s username and password are stored.
  2. The column names where the username and password are stored.
  3. The name of the table where the users are assigned to user groups.
  4. The column name in this table which stores the user group name.

Here’s an example:-

Users Table – user_details
user_namepassword
user1password
user2mypassword

Groups Table – user_groups
usernamegroup
user1Admin-Group
user1Regular-Group
user2Regular-Group


So, to create a new Realm; from the navigation tree, click:-
Security -> Realms -> New

Give your realm a name.
Select com.sun.enterprise.security.auth.realm.jdbc.JDBCRealm in the ‘Class Name’ field.
Enter the ‘JAAS Context’ as jdbcRealm.
In the ‘JNDI’ field, enter the name of your JDBC Resource from the previous step.
Fill in the table and column fields with your database info you have ready from the above step.
If your passwords are stored as MD5 hashes, enter MD5 in the ‘Digest Algorithm’ field.
The database username and password is already set in the connection pool so no need to duplicate here.
You can leave the rest of the fields blank.
New Security Realm

That’s it s far as Glassfish is concerned! easy huh?

Next we’ll take a quick look at how to implement basic authentication in a web app.

Step 3 – Set up your web app to use this security method
If you’re not familiar Java EE security using realms, users, groups and roles here is a good tutorial to get you started.

Ok, so we’re gonna use some example user credentials, groups and roles to implement security in our web app.
Users can belong to:-
Admin-Group or Regular-Group (these are mapped to users in the group table in your database).

First we’ll map some security roles to our groups; this is done in our sun-web.xml config file in the WEB-INF folder of our web application.
For convenience sake, we’ll create one role for each group with the same name as the group.
So, Admin-Group will have the role Admin-Group assigned to it (and the same goes for Regular-Group).

Go ahead and paste this into your sun-web.xml file:-
<security-role-mapping>
<role-name>Regular-Group</role-name>
<group-name>Regular-Group </group-name>
</security-role-mapping>
<security-role-mapping>
<role-name> Admin-Group</role-name>
<group-name>Admin-Group </group-name>
</security-role-mapping>

Next we’ll set a security constraint in our web.xml file (also in the WEB-INF folder of our web application).
You have to give the constraint a name, set the url pattern and state which roles are allowed to access this secure area.
As you can see we are securing the whole web app by supplying  ’/*’ as the url pattern.

Add this snippet to your web.xml file:-
     <security-constraint>
        <display-name>SecurePlace</display-name>
        <web-resource-collection>
         <web-resource-name>Secure Place</web-resource-name>
         <description>Description here</description>
          <url-pattern>/* </url-pattern>
    </web-resource-collection>
       <auth-constraint>
         <description>descrition here</description>
         <role-name>Regular-Group</role-name>
         <role-name>Admin-Group</role-name>
        </auth-constraint>
    </security-constraint>
We also need to tell the web app to actually implement security by forcing the users to login (this is also done in the web.xml file).
For this example we are using basic authentication, so we set the auth-method to ‘BASIC’.
Then we specify the jdbcRealm we created earlier for the realm-name.
Then we add all of the roles we want to be able to log in.

Add this snippet to your web.xml file:-
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>myRealm</realm-name>
    </login-config>
    <security-role>
       <role-name>Regular-Group</role-name>
    </security-role>
   <security-role>
        <role-name>Admin-Group</role-name>
    </security-role>


And that’s it! If you test your web application in a browser, you should get prompted for a username and password to continue.

L'administration sécurisée doit être activée pour l'accès distant au DAS.

Après une première installation par zip, pour résoudre ce problème, faire les étapes suivante

/installpath/glassfish4/bin/asadmin change-admin-password (car normalement pas de password)
ensuite 
/installpath/glassfish4/bin/asadmin enable-secure-admin

Maintenant accéder a votre console d'admin http://adresse:4848

GlassFish Server Open Source Edition 4.0 Download