Thursday, June 28, 2012

How to Download File using JSF

Following is the simple example how to download file from Server using JSF application

1. Create new JSF bean, either ManageBean or Component Bean using Spring framework

1:  package com.jsf.app.managedbean;  
2:  import java.io.BufferedInputStream;  
3:  import java.io.BufferedOutputStream;  
4:  import java.io.File;  
5:  import java.io.FileInputStream;  
6:  import java.io.IOException;  
7:  import javax.faces.context.FacesContext;  
8:  import javax.servlet.http.HttpServletResponse;  
9:  import javax.faces.bean.ManagedBean;  
10:  @ManagedBean(name="fileDownloadBean")  
11:  public class FileDownloadBean {  
12:       private static final int DEFAULT_BUFFER_SIZE = 10240;  
13:       private String filePath = "c:\\download\\test.txt";  
14:       public void downLoad() throws IOException {  
15:            FacesContext context = FacesContext.getCurrentInstance();  
16:            HttpServletResponse response = (HttpServletResponse) context  
17:                      .getExternalContext().getResponse();  
18:            File file = new File(filePath);  
19:            if (!file.exists()) {  
20:                 response.sendError(HttpServletResponse.SC_NOT_FOUND);  
21:                 return;  
22:            }  
23:            response.reset();  
24:            response.setBufferSize(DEFAULT_BUFFER_SIZE);  
25:            response.setContentType("application/octet-stream");  
26:            response.setHeader("Content-Length", String.valueOf(file.length()));  
27:            response.setHeader("Content-Disposition", "attachment;filename=\""  
28:                      + file.getName() + "\"");  
29:            BufferedInputStream input = null;  
30:            BufferedOutputStream output = null;  
31:            try {  
32:                 input = new BufferedInputStream(new FileInputStream(file),  
33:                           DEFAULT_BUFFER_SIZE);  
34:                 output = new BufferedOutputStream(response.getOutputStream(),  
35:                           DEFAULT_BUFFER_SIZE);  
36:                 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];  
37:                 int length;  
38:                 while ((length = input.read(buffer)) > 0) {  
39:                      output.write(buffer, 0, length);  
40:                 }  
41:            } finally {  
42:                 input.close();  
43:                 output.close();  
44:            }  
45:            context.responseComplete();  
46:       }  
47:  }  

2. Now Access the file using the JSF link as shown below:

1:                      <h:form>  
2:                           <h:commandLink id="getDownload" value="Download Files"  
3:                                     action="#{fileDownloadBean.downLoad}">  
4:                                </h:commandLink>  
5:                      </h:form>  

3. Create web.xml something like:
1:  <?xml version="1.0" encoding="UTF-8"?>  
2:  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
3:       xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
4:       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
5:       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
6:       id="WebApp_ID" version="2.5">  
7:       <listener>  
8:            <listener-class>com.sun.faces.config.ConfigureListener</listener-class>  
9:       </listener>  
10:       <context-param>  
11:            <param-name>javax.faces.PROJECT_STAGE</param-name>  
12:            <param-value>Development</param-value>  
13:       </context-param>  
14:       <context-param>  
15:            <param-name>javax.faces.CONFIG-FILES</param-name>  
16:            <param-value>WEB-INF/faces-config.xml</param-value>  
17:       </context-param>  
18:       <context-param>  
19:            <param-name>com.sun.faces.expressionFactory</param-name>  
20:            <param-value>com.sun.el.ExpressionFactoryImpl</param-value>  
21:       </context-param>  
22:       <servlet>  
23:            <servlet-name>Faces Servlet</servlet-name>  
24:            <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
25:            <load-on-startup>1</load-on-startup>  
26:       </servlet>  
27:       <servlet-mapping>  
28:            <servlet-name>Faces Servlet</servlet-name>  
29:            <url-pattern>/faces/*</url-pattern>  
30:       </servlet-mapping>  
31:       <servlet-mapping>  
32:            <servlet-name>Faces Servlet</servlet-name>  
33:            <url-pattern>*.jsf</url-pattern>  
34:       </servlet-mapping>  
35:       <servlet-mapping>  
36:            <servlet-name>Faces Servlet</servlet-name>  
37:            <url-pattern>*.faces</url-pattern>  
38:       </servlet-mapping>  
39:       <servlet-mapping>  
40:            <servlet-name>Faces Servlet</servlet-name>  
41:            <url-pattern>*.xhtml</url-pattern>  
42:       </servlet-mapping>  
43:  </web-app>  

Now after deploying this in the servlets container, you will see the dialog box for Save the File/Open.


Sunday, June 17, 2012

How to create generic Repository Dao in JPA.

Repository Dao is an interface to interact with the low level database operation, specially CRUD operations. The Repository Dao interface is usually designed to hide the implementation details and provide the uniform API to the client of the Dao usually Service classes.
In the below example, I will create the basic domain, Dao Interface, Implementation and Test class for JPA implementation.

1. First Create the database schema as shown below:
 create table login_user(uuid varchar2(40), user_name varchar2(40), password varchar2(100), first_name varchar2(100), last_name varchar2(100));  


2. Create the domain class for the data model shown above:

PersistableId Class
1:  package com.jsf.app.persistence.model;  
2:  import java.io.Serializable;  
3:  import javax.persistence.Column;  
4:  import javax.persistence.Id;  
5:  import javax.persistence.MappedSuperclass;  
6:  import javax.persistence.PrePersist;  
7:  import com.jsf.app.utils.UUIDGenerator;  
8:  @MappedSuperclass  
9:  public class AbstractIdPersistable implements Serializable {  
10:       private static final long serialVersionUID = -2722115269874427565L;  
11:       @Id  
12:       @Column(name = "UUID")  
13:       private String id;  
14:       public String getId() {  
15:            return id;  
16:       }  
17:       public void setId(String id) {  
18:            this.id = id;  
19:       }  
20:       public boolean isNew() {  
21:            return null == getId();  
22:       }  
23:       @PrePersist  
24:       public void assignUUID() {  
25:            this.setId(UUIDGenerator.getUUID());  
26:       }  
27:  }  

Persistable User Class map to LOGIN_USER table.
1:  package com.jsf.app.persistence.model;  
2:  import javax.persistence.Column;  
3:  import javax.persistence.Entity;  
4:  import javax.persistence.NamedQueries;  
5:  import javax.persistence.NamedQuery;  
6:  import javax.persistence.Table;  
7:  @Entity  
8:  @Table(name = "LOGIN_USER")  
9:  @NamedQueries({  
10:            @NamedQuery(name = "user.findAll", query = "from User"),  
11:            @NamedQuery(name = "user.findByUserName", query = "from User u where u.userName = ?") })  
12:  public class User extends AbstractIdPersistable {  
13:       private static final long serialVersionUID = -6103795542566301215L;  
14:       @Column(name = "USER_NAME", nullable = false)  
15:       private String userName;  
16:       @Column(name = "PASSWORD", nullable = false)  
17:       private String password;  
18:       @Column(name = "FIRST_NAME", nullable = false)  
19:       private String firstName;  
20:       @Column(name = "LAST_NAME", nullable = false)  
21:       private String lastName;  
22:       public String getUserName() {  
23:            return userName;  
24:       }  
25:       public void setUserName(String userName) {  
26:            this.userName = userName;  
27:       }  
28:       public String getPassword() {  
29:            return password;  
30:       }  
31:       public void setPassword(String password) {  
32:            this.password = password;  
33:       }  
34:       public String getFirstName() {  
35:            return firstName;  
36:       }  
37:       public void setFirstName(String firstName) {  
38:            this.firstName = firstName;  
39:       }  
40:       public String getLastName() {  
41:            return lastName;  
42:       }  
43:       public void setLastName(String lastName) {  
44:            this.lastName = lastName;  
45:       }  
46:       @Override  
47:       public String toString() {  
48:            return "[" + this.getId() + ", " + this.getFirstName() + ", "  
49:                      + this.getLastName() + "]";  
50:       }  
51:  }  

3. Now create a generic persistence dao interface:
1:  package com.jsf.app.persistence.dao;  
2:  import java.util.Collection;  
3:  public interface AbstractPersistenceDao<Entity> {  
4:       public Entity findById(String id);  
5:       public void save(Entity e);  
6:       public void remove(Entity e);  
7:       public Collection<Entity> findByNamedQuery(String nameQuery);  
8:       public Collection<Entity> findByNamedQueryAndParams(String nameQuery,  
9:                 Object... params);  
10:  }  

4. Now create an abstract implementation of the generic persistence dao:

1:  package com.jsf.app.persistence.dao.impl;  
2:  import java.lang.reflect.ParameterizedType;  
3:  import java.util.Collection;  
4:  import javax.persistence.EntityManager;  
5:  import javax.persistence.PersistenceContext;  
6:  import javax.persistence.Query;  
7:  import com.jsf.app.persistence.dao.AbstractPersistenceDao;  
8:  public abstract class AbstractPersistenceDaoImpl<Entity> implements  
9:            AbstractPersistenceDao<Entity> {  
10:       @PersistenceContext  
11:       private EntityManager entityManager;  
12:       public AbstractPersistenceDaoImpl() {  
13:       }  
14:       @SuppressWarnings("unchecked")  
15:       public Class<Entity> returnEntityClass() {  
16:            ParameterizedType genericSuperclass = (ParameterizedType) getClass()  
17:                      .getGenericSuperclass();  
18:            return (Class<Entity>) genericSuperclass.getActualTypeArguments()[0];  
19:       }  
20:       @Override  
21:       public Entity findById(String id) {  
22:            return entityManager.find(returnEntityClass(), id);  
23:       }  
24:       @Override  
25:       public void save(Entity e) {  
26:            this.entityManager.persist(e);  
27:       }  
28:       @Override  
29:       public void remove(Entity e) {  
30:            this.entityManager.remove(e);  
31:       }  
32:       @Override  
33:       @SuppressWarnings("unchecked")  
34:       public Collection<Entity> findByNamedQuery(String query) {  
35:            Query q = this.entityManager.createNamedQuery(query);  
36:            return (Collection<Entity>) q.getResultList();  
37:       }  
38:       @Override  
39:       @SuppressWarnings("unchecked")  
40:       public Collection<Entity> findByNamedQueryAndParams(String nameQuery,  
41:                 Object... params) {  
42:            Query q = entityManager.createNamedQuery(nameQuery);  
43:            int i = 1;  
44:            for (Object o : params) {  
45:                 q.setParameter(i, o);  
46:            }  
47:            return (Collection<Entity>) q.getResultList();  
48:       }  
49:  }  

5. We can now create our customized Dao Interface and Implementation for our Domain Objects. In this case for our User domain object as shown below:

1:  package com.jsf.app.persistence.dao;  
2:  import java.util.Collection;  
3:  import com.jsf.app.persistence.model.User;  
4:  public interface UserDao extends AbstractPersistenceDao<User> {  
5:       public Collection<User> getAllUser();  
6:       public void persistChange(User user);  
7:  }  

and Implementation:
1:  package com.jsf.app.persistence.dao.impl;  
2:  import java.util.Collection;  
3:  import org.springframework.stereotype.Repository;  
4:  import org.springframework.transaction.annotation.Transactional;  
5:  import com.jsf.app.persistence.dao.UserDao;  
6:  import com.jsf.app.persistence.model.User;  
7:  @Repository("userDao")  
8:  public class UserDaoImpl extends AbstractPersistenceDaoImpl<User> implements  
9:            UserDao {  
10:       public UserDaoImpl() {  
11:            super();  
12:       }  
13:       @Override  
14:       @SuppressWarnings("unchecked")  
15:       public Collection<User> getAllUser() {  
16:            return findByNamedQuery("user.findAll");  
17:       }  
18:       @Override  
19:       @Transactional  
20:       public void persistChange(User user) {  
21:            save(user);  
22:       }  
23:  }  

6. Finally create the test case to test the Dao and Implementation:

1:  package com.jsf.app.persistence.dao.impl;  
2:  import java.util.Collection;  
3:  import java.util.List;  
4:  import org.junit.After;  
5:  import org.junit.Assert;  
6:  import org.junit.Before;  
7:  import org.junit.Ignore;  
8:  import org.junit.Test;  
9:  import org.junit.runner.RunWith;  
10:  import org.springframework.beans.factory.annotation.Autowired;  
11:  import org.springframework.test.context.ContextConfiguration;  
12:  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
13:  import org.springframework.test.context.transaction.TransactionConfiguration;  
14:  import org.springframework.transaction.annotation.Transactional;  
15:  import com.jsf.app.persistence.dao.UserDao;  
16:  import com.jsf.app.persistence.model.User;  
17:  @RunWith(SpringJUnit4ClassRunner.class)  
18:  @ContextConfiguration(locations = { "classpath*:applicationContext.xml" })  
19:  @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)  
20:  public class UserDaoTest {  
21:       @Autowired  
22:       private UserDao userDao;  
23:       @Before  
24:       public void before() {  
25:       }  
26:       @After  
27:       public void after() {  
28:       }  
29:       @Test  
30:       @Transactional  
31:       @Ignore  
32:       public void testSaveAllUsers() {  
33:            User u = new User();  
34:            u.setFirstName("Joy");  
35:            u.setLastName("Steward");  
36:            u.setUserName("joy");  
37:            u.setPassword("password");  
38:            userDao.persistChange(u);  
39:       }  
40:       @Test  
41:       public void testGetAllUser() {  
42:            List<User> users = (List<User>) userDao.getAllUser();  
43:            Assert.assertNotNull(users);  
44:            Assert.assertEquals(1, users.size());  
45:       }  
46:       @Test  
47:       public void testNamedQueryAndParam() {  
48:            Collection<User> users = userDao.findByNamedQueryAndParams(  
49:                      "user.findByUserName", "joy");  
50:            Assert.assertNotNull(users);  
51:            Assert.assertEquals(1, users.size());  
52:       }  
53:       @Test  
54:       public void testFindUserById() {  
55:            User u = userDao.findById("E5429C88F74F4A8C6B13399485587401");  
56:            Assert.assertNotNull(u);  
57:            Assert.assertEquals("joy", u.getUserName());  
58:       }  
59:  }