vendredi 10 janvier 2014

File Upload is Easy in JSF2.2 and netbeans 7.4

To bring the File Upload feature in Java based web application is one of the difficult and complex job, we need to dependent on 3rd party libraries like Apache Commons FileUpload Libraries. These libraries codes are complex and most of them boilerplate code.

If we are using Java Server Faces (JSF), we have the page with some fields and file upload menu the its add more complexity, fields are binded to backing bean but these file uploads components are need to tie up with some 3rd party file upload libraries.

In Primefaces provide easy way to do the file upload in JSF web application, even though primefaces internally used the same Apache Commons FileUpload Libraries, but provide simple JSF tags. We need configure some listeners.

In Servlet 3.0 they introduced the Part Interfaces and @MultiPartConfig annotations for easy way to do the file upload without any 3rd party libs, Servlet 3.0 is part of Java EE 6 specification. so any servlet 3.0 implementation servers like Tomcat 7, Jboss 6, GlassFish 3 they can get benefit of servlet 3.0. but this feature is not available in JSF 2.1. so again still it's complex to use file upload in JSF, because we need to mix servlet and JSF backing bean.

At last JSF 2.2 is added the File Upload component, so we just use <h:inputFile> tag to make the file upload web application so easily, and this component use the Part interface, which its introduced its part of Servlet 3.0. so this JSF2.2 libraries is working perfectly with Tomcat 7 (because tomcat 7 is implemented the Servlet 3.0 spec).

To bring the File Upload feature we need to follow 3 step process

  1. Add <h:inputFile> tag in JSF page
  2. Add enctype="multipart/form-data" attribute in enclosing <h:form> tag
  3. Create the field in Backing bean with Part data type.

Setup the Environment

Add JavaServerFace framework in Netbeans and choose JSF2.2 library

Step 1: Add <h:inputFile> tag in JSF page

In JSF page add the <h:inputFile> tag where we need file upload component

  <h:inputFile value="#{demoBean.file1}" />

here we bind the value property to file1 field, which data type is Part, check the third step



Step 2: Add enctype="multipart/form-data" attribute in enclosing <h:form> tag

When u want file upload feature then we need to inform the browser that form may contain multiple normal text input field and some file upload component, so prepare the POST request in special form, like parts by part with special delimiter boundary.
<h:form enctype="multipart/form-data">
</h:form>

so index.xhtml file looks like
  1. <h:head>  
  2.     <title>Facelet Title</title>  
  3. </h:head>  
  4. <h:body>  
  5.     Hello from Facelets  
  6.       
  7.     <h:form enctype="multipart/form-data">  
  8.         <h:inputfile value="#{demoBean.file1}"></h:inputfile>  
  9.   
  10.           
  11.         <h:inputfile value="#{demoBean.file2}"> </h:inputfile>  
  12.   
  13.         <h:commandbutton action="#{demoBean.upload()}" value="Upload">  
  14.     </h:commandbutton></h:form>  
  15. </h:body>  



Step 2: Create Backing Bean

now create the backing bean for this page. we need to create the fields for input File component with Part type. Part interface is introduced in servlet 3.0 for represent the file chunks sent by browser, JSF 2.2 use this Part interface, Using the Part interface we can get the header information of each file chunk sent by browser, these header contain the file name and other meta information about the file.

Part interface also contain write() method to write the file contents into specified server location, or u can get the InputStream then we can process it.

DemoBean.java

  1. import java.io.IOException;  
  2. import javax.faces.bean.ManagedBean;  
  3. import javax.faces.bean.SessionScoped;  
  4. import javax.servlet.http.Part;  
  5.   
  6.   
  7. /** 
  8.  * 
  9.  * @author ramki 
  10.  */  
  11. @ManagedBean  
  12. @SessionScoped  
  13. public class DemoBean {  
  14.   
  15.     private Part file1;  
  16.     private Part file2;  
  17.   
  18.     // getters and setters for file1 and file2  
  19.   
  20.     public String upload() throws IOException {  
  21.          InputStream inputStream = file1.getInputStream();          
  22.         FileOutputStream outputStream = new FileOutputStream(getFilename(file1));  
  23.           
  24.         byte[] buffer = new byte[4096];          
  25.         int bytesRead = 0;  
  26.         while(true) {                          
  27.             bytesRead = inputStream.read(buffer);  
  28.             if(bytesRead > 0) {  
  29.                 outputStream.write(buffer, 0, bytesRead);  
  30.             }else {  
  31.                 break;  
  32.             }                         
  33.         }  
  34.         outputStream.close();  
  35.         inputStream.close();  
  36.          
  37.         return "success";  
  38.     }  
  39.   
  40.     private static String getFilename(Part part) {  
  41.         for (String cd : part.getHeader("content-disposition").split(";")) {  
  42.             if (cd.trim().startsWith("filename")) {  
  43.                 String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");  
  44.                 return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.  
  45.             }  
  46.         }  
  47.         return null;  
  48.     }  
  49. }  


here we need get the file name from the Header of the chunk, so there is boilerplate code can do, here i don't like this method :-(

there is no direct method to retrieve the file name. so use this code we can get the name of the file is uploaded by client, then using write method we can store into server.


Get the sample project from  Github or download from here

TomEE OpenJPA et netbeans

Passons au point où nous ferons la partie la plus intéressante. Nous allons configurer OpenJPA dans Netbeans de sorte que le générateur de NetBeans "entité" peut travailler et utiliser OpenJPA et Tomee. Donc, pour ce faire, vous devez d'abord créer une connexion à une base de données. Laisse supposer que nous créons un pour le serveur MySQL comme indiqué dans la capture d'écran ci-dessous.
Donc, une fois cette connexion est là, nous sommes prêts à créer des classes d'entité à partir de la base de données sélectionnée. Pour ce faire, suivez le menu, comme indiqué dans la capture d'écran ci-dessous.
Une fois que vous sélectionnez "classes d'entité de base de données" vous sera présenté avec la boîte de dialogue suivante


Dans cette boîte de dialogue d'abord, nous souhaitons sélectionner la connexion que nous avons créé avant dans le menu déroulant en haut . Une fois que vous sélectionnez la connexion Netbeans apporterait toutes les tables dans la liste "Tables disponibles" . Vous pouvez frapper " Ajouter tout " pour sélectionner toutes les tables pour la génération de classe d'entité . Maintenant laisse frapper "Suivant " et passez à l'écran suivant . Et puis cliquez sur suivant et dans la finition de succès écran suivant . Vous pouvez accepter les valeurs par défaut qui sont donnés par le système et terminez l'assistant de création de l'entité . Avec ce que vous avez fini de créer les entités . Mais dès que vous avez fini de créer les entités Vous obtiendrez un message d'échec de serveur Tomee ( Dans le cas où votre serveur Tomee est en cours d'exécution ) . C'est parce que par Netbeans par défaut générer des classes d'entité à l'aide de EclipseLink qui n'est pas présent dans Tomee . Donc, pour rendre tout le monde heureux. Ensuite, nous allons configurer OpenJPA . Pour ce faire, vous devez ouvrir le fichier persistence.xml du projet ( Explorateur de projet - > double-cliquez sur persistence.xml ) . Ce serait ouvrir la fenêtre de l'éditeur de persistence.xml . Comme indiqué ci-dessous

Or, dans cette fenêtre, nous allons sélectionner l'option "New Persistance Bibliothèque" dans le menu déroulant Persistance Bibliothèque. Cela va ouvrir la boîte de dialogue suivante.

Ici, vous devez choisir les deux fichiers jar suivants à partir du dossier d'installation Tomee - javaee-api-6.0-4-tomcat.jar et OpenJPA-asm-ombragée-2.2.0.jar. Ne vous assurer que vous choisissez les fichiers jar de l'endroit même où votre serveur est Tomee. Une fois que vous choisissez les bibliothèques appropriées cliquez sur OK pour fermer la boîte de dialogue et revenir à l'écran de l'éditeur de persistence.xml de NetBeans.

Maintenant, choisir OpenJPA  de la bibliothèque de persistance  et enregistrez le fichier comme indiqué dans la capture d'écran ci-dessus. Maintenant, redémarrez simplement le serveur une fois et vous êtes prêt pour exécuter Tomee avec JPA.

TomEE et NetBeans : installer TomEE dans netbeans

Netbeans et Tomee fonctionne très bien ensemble. Vous pouvez ajouter en fait Tomee comme un serveur Apache Tomcat dans Netbeans en suivant les étapes simples indiquées ci-dessous.

supposons que vous avez déjà téléchargé Tomee et vous avez NetBeans déjà configuré. Pour commencer créons un projet Web Java dans l'EDI. Commençons par ajouterle serveur.
Dans l'écran du serveur, nous pouvons ajouter Tomee comme la capture d'écran ci-dessous.
Maintenant, cliquez sur suivant. Dans l'étape suivante, vous devez sélectionner le dossier où le serveur Tomee est présent.


Dès que vous cliquez sur terminer votre travail est fait. NetBeans aurait ajouter l'utilisateur du gestionnaire sur le serveur Tomcat et vous reviendra vers la fenêtre de création de projet. Passez à l'étape pour choisir votre framework web favori et terminer le processus de création du projet. Une fois le projet créé juste l'exécuter une fois pour voir si tout va bien.

dimanche 29 décembre 2013

11 Reasons why products fail in the market

by  on December 29th, 2013 | Filed in: Agile
Source : http://www.javacodegeeks.com/2013/12/11-reasons-why-products-fail-in-the-market.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+JavaCodeGeeks+%28Java+Code+Geeks%29

  • Not having a directed product vision
  • Not enough investments for the products
  • Too late into the market
  • Too early in the market
  • No real unique features
  • Lack of focus
  • Management expectations
  • Not enough R&D investments
  • Lack of adequate technical skills / Product Management skills
  • Not enough value for money
  • Buggy Product

HTML 5 Server Sent Events on Glassfish 4

SSE (Server Sent Events) is a Web Pushing technology which was developed under HTML 5 technology. So, what is Pushing?

Pushing
It is a transmission of data sets which of them are sent at regular intervals or in any time through the server application, in the direction of server – – – >browser, without need for any request of web browser. Serving Twitter updates currently in the web page at regular intervals, appearance of Facebook shares on screen when a new share is available, serving instant financial data (exchange rate of dollar, parity etc.) immediately to users’ screen can be given as examples for pushing scenerio.

Server Sent Events is not a unique technique used for pushing of http resource, in theprevious article, we mentioned how to provide data transmission to the web browser by LongPolling technique. I think this sequencing about Push technologies would not be wrong generally in this order;
Polling –> LongPolling –> ServerSent Events –> WebSocket
ServerSent Events is a technology that its developments is already continues, such as WebSocket technology. For this reason, I would like to mention that it is not useable in every web browser and that’s for sure it is supported by new generation web browsers.

SSE technology has a few additional features unlike other ones, such as automatic connection recovery when the connection is lost, routing the message to an certain function in event/resource broadcasts. For example, you can take a look at to the discussion about the comparison of SSE and WebSocket from the entry in StackOverFlow.
How the SSE works?
The logic of operation of SSE technology can be seen in the picture illustrated below. Ahandshake request is sent to SSE supported server by the web browser and server system returns a handshake response which is “text/event-stream” MIME type. After the handshake committed among web browser and SSE service, SSE service may send any amout of data at any time. jaxrs-sse