Oct 3, 2010

Rich Faces consists of some really useful components that can be used to make as they say  some very "rich web applications".
In this tutorial i will be explaining about how to use richfaces file upload component to store a file into the database and then retrieve the file using a Jersey restful web service.

The file upload component of rich faces supports two modes of uploading.
  1. To store the uploaded file in a temporary directory or
  2. To keep an in memory representation of it.
I will be explaining about how to use the latter one the reason being that  as we are going to store files in the database there's no point in creating temporary files.

If you want to create temp files then specify the following filter initialization parameter in the web.xml file.

But we are going to set it to false.
Following is the filter configuration for richfaces
<display-name>RichFaces Filter</display-name>
<servlet-name>Faces Servlet</servlet-name>

The relevant code for jsp file is listed below.
<h:form enctype="multipart/form-data">
   <h:panelGrid columns="2" columnClasses="top,top">
            <rich:fileUpload fileUploadListener="#{fileUpload.listener}"
                <a4j:support event="onuploadcomplete" reRender="info" />
            <h:panelGroup id="info">
                <rich:panel bodyClass="info">
                    <f:facet name="header">
                        <h:outputText value="Uploaded Files Info" />
                    <h:outputText value="No files currently uploaded"
                        rendered="#{fileUpload.size==0}" />
                    <rich:dataGrid columns="1" value="#{fileUpload.files}"
                        var="file" rowKeyVar="row">
                        <rich:panel bodyClass="rich-laguna-panel-no-header">
                            <h:panelGrid columns="2">
                                <a4j:mediaOutput element="img" mimeType="#{file.mime}"
                                    createContent="#{fileUpload.paint}" value="#{row}"
                                    style="width:100px; height:100px;" cacheable="false">
                                    <f:param value="#{fileUpload.timeStamp}" name="time"/>  
                                <h:panelGrid columns="2">
                                    <h:outputText value="File Name:" />
                                    <h:outputText value="#{file.name}" />
                                    <h:outputText value="File Length(bytes):" />
                                    <h:outputText value="#{file.length}" />
                <rich:spacer height="3"/>
                <br />
                <a4j:commandButton action="#{fileUpload.clearUploadData}"
                    reRender="info, upload" value="Clear Uploaded Data"
                    rendered="#{fileUpload.size>0}" />

The code for the fileUpload backing bean is mentioned below.
In the code below all the parameters are passed to the DAO class directly i recommend that you use a DTO and pass it instead.

public class FileUploadBacking {

 private ArrayList<filevo> files = new ArrayList<filevo>();
 private int uploadsAvailable = 10;
 private boolean autoUpload = false;
 private boolean useFlash = false; 
 public int getSize() {
  if (getFiles().size() > 0) {
   return getFiles().size();
  } else {
   return 0;

 //used to write in the display pane 

 public void paint(OutputStream stream, Object object) throws IOException {
  stream.write(getFiles().get((Integer) object).getData());

 public void listener(UploadEvent event) throws Exception {
  UploadItem item = event.getUploadItem();
  FileStoreDAO fdao=FileStoreDAO.getInstance();
  FacesContext fctx=FacesContext.getCurrentInstance();
  HttpServletRequest request=(HttpServletRequest)fctx.getExternalContext().getRequest();
  HttpSession session=request.getSession();
  // Call the storeFile method of fileStoreDAO passing it the params. //Create a DTO for such calls
                String result=fdao.storeFile(item.getData(),item.getFileName(),item.getContentType(),session.getAttribute("userID").toString());
  FileVO fileVO = new FileVO();
                fileVO.setName("your application domain"+" context root"+"rest resource mapping"+item.getFileName());
   FacesMessage fmsg=new FacesMessage(FacesMessage.SEVERITY_ERROR,"Db error","Some Db error  has occured could not upload your files");
   fctx.addMessage(null, fmsg);

//clear the data
 public String clearUploadData() {
  for(int i=0;i<files.size();i++){
    FileStoreDAO fdao=FileStoreDAO.getInstance();
  return "success";

//rest of the code

The DAO class for storing,reading or updating files is listed below:-

public class FileStoreDAO {
    private FileStoreDAO(){
    public static FileStoreDAO getInstance(){
        return new FileStoreDAO();
public void removeData(String fileName){
    DBConnection conn = null;
    PreparedStatement pstmt = null;
    Statement stmt=null;
         conn = new DBConnection();
        stmt = conn.getStatement();
        stmt.executeUpdate("delete from file_store where file_name like '"+fileName+"'");        
     catch (Exception e) {
        finally {
            try {
                if (stmt != null) {

            } catch (Exception e1) {
    public String storeFile(byte data[],String fileName,String fileType,String userID){
        DBConnection conn = null;
        PreparedStatement pstmt = null;
        Statement stmt=null;
        ResultSet rs = null;
        String outcome;
        boolean flag=false;
            conn = new DBConnection();
            stmt = conn.getStatement();
            ByteArrayInputStream bis=new ByteArrayInputStream(data);
            rs=stmt.executeQuery("Select count(*) from file_store  where file_name like '"+fileName+"'"); 
                pstmt=conn.getPreparedStatement("update file_store set file_data=? , file_type=? , user_id=? , file_size=? , mod_date=sysdate() where file_name like ?" );
            pstmt = conn.getPrepareStatement("Insert into file_store (file_name,file_data,file_type,user_id,file_size,mod_date) values (?,?,?,?,?,sysdate())");
            System.out.println("After insert");
        catch (Exception e) {
        finally {
            try {
                if (rs != null) {
                if (pstmt != null) {

                if (stmt != null) {

            } catch (Exception e1) {
        return outcome;
public FileDTO readFile(String fileName){
        DBConnection conn = null;
    Statement stmt = null;
        ResultSet rs = null;
        FileDTO fileDTO=new FileDTO();
        try {
            conn = new DBConnection();
String query="Select file_name,file_type,file_size,file_data from file_store where file_name=?";             
pstmt = conn.getPrepardedStatement(query);
            pstmt.setString(1,"'"+fileName +"'");
            catch (Exception e) {
            finally {
                try {
                    if (rs != null) {
                    if (stmt != null) {

                } catch (Exception e1) {
            return fileDTO;

Now all we have to do is write the code of the jersey based restful web service and configure the jersey servlet.

The jersey servlet configuration is shown below:-

The jersey servlet intercepts any call to the resource under /rest.
The code for the resource class is shown below.

public class FileResource {
     * @param filename passed in the get request
     * @returns builds and returns the response
public Response returnFileAsStream(@PathParam("filename") String fileName){
FileStoreDAO ftDAO=FileStoreDAO.getInstance();
FileDTO fdto=ftDAO.readFile(fileName);
String contentType=fdto.getMime();
InputStream is=fdto.getFileData();
return Response.ok(is,contentType).build();
return Response.noContent().build();
The FileResouce class has a mapping of /files/{filename} specified where filename is the path parameter. For example if a call to http://your-domain/yourcontextroot/rest/files/abc.jpg comes the method annotated with the get annotation simply call's the DAO class's readFile method passing it the file name as abc.jpg and get the data as a stream(if the file exists), The method then builds a response and returns it to the client.

Hope this tutorial was helpful

Posted on Sunday, October 03, 2010 by Unknown

Aug 29, 2010

If you want to secure connection to a resource on your apache web-server by using public key encryption technique then you can add the mod_ssl module into the apache web-server for that purpose.

Here are the list of things that are explained in this tutorial:-
  1. Installing OpenSSL
  2. Public key encryption standard.
  3. Certificate Signing Authority(CA) and Digital Signatures
  4. Encryption Of Data (shared secret key encryption) 
  5. Creating the Digital Certificate.
  6. Installing the certificate's and keys in proper directory
  7. Setting up the apache configuration(httpd.conf)
  8. Testing the configuration

1.Installing OpenSSL

The apache web server comes now bundled with and mod_ssl module.You can directly download the version 2.13 of apache web server from this link.

We need OpenSSL for producing digital certificates and what are these will be examined later on.

Just open and run the installer and after you have done that proceed to the second step and note that you may also need to download the OpenSSL module seperately for windows and also need to have the visual C++ modules for it to run. You can download these from this link.

2.Public key encryption standard: The public key encryption in short works as follows:-

There are essentially two pairs of keys per entity. One key which is shared and used to encrypt the contents and is publicly available is called public key whereas the other key which is used for decryption is called the private key is kept secret.

So if an entity 'A' has to send a secret message to entity 'B' then entity 'A' uses entity 'B's' public key to encrypt the message and on the receiving side entity 'B' uses its private key to decrypt the message and since only entity 'B' is in possession of it's private key therefore no third party can decrypt the content's of message.Unless Of-course the private key has been compromised.

The point that should  be noted is that entity 'B' cannot guarantee that it is receiving message from entity 'A' because anyone with access to 'B's' public key can send B a message , therefore this communication lacks authentication.

3. Certificate Signing Authority(CA) and Digital Signatures:-

The only problem with the previous scheme was that the client cannot be sure that the sender is who he claims to be and this is where a CA comes in as it is responsible for verifying the details of the sender and issuing the X.509 digital certificate to it. The X.509 digital certificate contains the sender's public key,domain identifiers,serial number for the certificate and most importantly the encrypted hashed(md5 hash, RSA encryption) data (Encryption is done using CA's private key,The hashed data encrypted using CA'S key serves as Digital signature of the CA). This constitutes sender's certificate.

The sender (server), when sending information to the client may choose to encrypt the entire contents or just calculate an SHA-1 hash and encrypt it using it's private key and sends the X.509 digital certificate it obtained from the CA along with this.

On the client side firstly the the CA is identified by 'CA attribute' in the X509v3 extension section of x.509 digital certificate, then using CA's public key (stored in the browser in the CA certificate public key info)   the hash is decrypted and this decrypted hash is compared with the hash that is calculated over the rest of the x.509 digital certificate that was sent by the sender. If these hash values match then client can be sure that this certificate really was signed by the CA and hence can be sure of the server that is sending the data because it was signed by the CA. The client then can decrypt the contents of the message by using the public key found in the x.509 digital certificate.

There are many well known certificate authorities such as Verisign etc whose certificates are not to be signed by any authority as they are the root certificate authorities and there certificates already come pre-installed in the browsers like Firefox, Internet Explorer etc. you can view them in mozilla firefox by going to Tools->Options->Advanced-> Encyption and then choosing View Certificates.

The only concern with getting the certificate signed by a CA is the cost factor.But on the other hand, This trusted third party scheme is more secure because in case the sender(server) loses its private key then it can ask the CA to revoke its certificate doing so places the certificate in CRL (Certificate Revocation List) which  ensures that no one else can pretend to be the sender.

It may happen that once in a while you may encounter that if you are viewing a site in mozilla you may encounter that mozilla displays you a warning message as shown below which warns you that you may be at risk viewing the website, this happens only due to the fact that the certificate may be self-signed by the server or a CA not known to the browser and therefore the authenticity of the sender cannot be known and hence you should avoid sending personal details over to a web server like that because if the  private key of the server is compromised then it can lead to potential fraudulent activity. However, if you do trust the server you can click on proceed and this leads to saving of the CA certificate of the server's CA on your browser and then you can view the certificate as mentioned above. In our sample installation we are going to create our own CA and we are going to sign that certificate signing request to produce a X.509 digital certificate.

I hope this was informational enough theory and now we can really proceed with the installation of mod_ssl on apache.

4. Encryption Of Data (Shared secret key Encryption):-

The actual data b/w the client and the server is encrypted using shared secret key because it is faster and the server does not need to know the client's public key for encrypting the data that it sends to the client.
The key exchange however occurs through public key encryption  as follows:-

As the client knows of server's public key so it generates a random secret key (to be used for encrypting the data) and then encrypts it using server's public key and on the server's end it uses its private key to decrypt the shared secret key. Hence the public key encryption scheme helps to transfer the shared secret key.

5.Creating the x.509 digital certificate:-

To create the digital certificate we have to do the 5 following steps:-

  1. Generate the Server's Private and Public key
  2. Generate the CA's Private and Public key
  3. Generate the CA's x.509 Digital Certificate (Self-Signed)
  4. Generate the Server's Certificate Signing Request
  5. CA signing the certificate signing request
  1. Generate the Server's Private and Public key:-
  2. To generate the server's private key execute the following command in the directory above the directory that contains the OpenSSL module which in windows would be (if you have installed it using the windows binary) "C:\OpenSSL\bin" :-
    openssl genrsa -out server.key 1024
    This command produces an private rsa key of 1024 bits long and you do not have to create a separate public key. You can choose to encrypt these key by adding -des3 oprion after the genrsa option which will encrypt this key by using 3-DES symmetric encryption standard.
  3. Generate the CA's Private and Public key:-
    Repeat the same step as above and generate the private key for the CA and also encrypt this key. You will be asked for the pass-phrase for the key that would be required in case you want to use that key. Now execute the following command.

    openssl genrsa -des3 -out CA.key 1024

  4. Generate the CA's x.509 Digital Certificate (Self-Signed):-
    Execute the following command to generate a self signed x.509 digital certificate.

    openssl req -new -x509 -key CA.key -out cacert.pem -days 1095

    When you execute this command you would be asked for the pass-phrase of the key which you entered in the previous step so enter it and fill in the details asked for.
    This command produces a self signed certificate(cacert.pem) using the encrypted rsa key CA.key with validity of 1095 days.

  5. Generate the Server's Certificate Signing Request:-
    Now execute the following command to generate the server's certificate signing request (CSR).

    openssl req -new -key server.key -out server.csr

    Enter the details as requested and this will produce the csr that is sent to real CA authorities but in our case we are our own CA so we'll sign the certificate on our own.

  6. CA signing the certificate signing request:-
    This command when executed will sign the certificate request server.csr to produce a x.509 digital certificate signed by our own CA.

    openssl x509 -CA cacert.pem -CAkey CA.key -in server.csr -req -days 365 -out server.crt -CAcreateserial

    This command signs the certificate signing request and note that the last option(CAcreateserial)is required because there has to be a serial file server.crl for CA to sign the certificate and is required only the first time.

6.Installing the certificate's and keys in proper directory:-

The certificate's and the key files should be installed anywhere outside the web root directory of apache like a directory c:/secret and placed in that directory. The certificate's should be installed outside of the directory because they are inaccessible to visitor of your site.

7.Setting up the Apache configuration(httpd.conf):-

There are many mod_ssl directives that you can implement i am just going to discuss some basic ones for more information there is an excellent tutorial available at this link www.modssl.org

Here's the sample configuration

Few of the mod_ssl directives:-

  1. SSLEngine on/off :- This is the basic directive which enables or disables the ssl on apache. Prior to version 2 of apache this was called as SSLEnable /SSLDisable.
  2. SSLCertificateFile server_cert_file :- This specifies the certificate file for the server ie the server's x.509 digital certificate. Use /for absolute path or dir-name/file for the relative directory under the apache directory. In this case server.cert .
  3. SSLCertificateKeyFile server_key_file :-This specifies the private key file for the certificate file. In this case server.key .
  4. SSLCACertificateFile ca_cert_file:- This specifies the certificate file of the CA ie the CA's self signed x.509 digital certificate. Use /for absolute path or dir-name/file for the relative directory under the apache directory. In this case cacert.pem .
  5. SSLRequireSSL:- This forbids access to resource unless http over ssl is enabled for the current active connection.
  6. SSLProtocol (SSLv2,SSLv3,TLSv1,All):- By default all the protocols are enabled.You can disable a particular protocol like this: SSLProtocol all -TLSv1 which disables the Transport layer security protocol v1.
  7. SSLSessionCacheTimeout time_in_sec:- This sets the time in seconds till which the session key will be cached locally after which the key will be changed.
Now you have to setup a virtual host for which http over ssl i.e https would be enabled.
You can create a named host or a host based on ip address. In this we are going to setup the ip based virtual host.

Then we have to add the AddType directives so that apache recognizes the certificate files and their extensions. We will be adding the following two directives:
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl .crl

From the code box below just copy and paste the code into the httpd.conf.

But before that you would have to enable the mod_ssl module in the httpd.conf. To do that just open the httpd.conf and scroll down to the LoadModule directives and find one with the name mod_ssl and remove the # comment from before it as shown in the following figure.

From the code box below just copy and paste the code into the httpd.conf

############################################## ############# mod_ssl configuration ############ AddType application/x-x509-ca-cert .crt AddType application/x-pkcs7-crl .crl SSLEngine off #change this to directory where your certificate's are installed SSLCertificateFile conf/server.cert SSLCertificateKeyFile conf/server.key SSLCACertificateFile conf/cacert.pem #set the server to listen on port 8080 Listen <VirtualHost> #enable ssl engine for port 8080 SSLEngine on SSLSessionCacheTimeout 300 SSLProtocol SSLv3 # here you can setup access to directories and authentication # by using the <directory dir_name=""> directive and AuthType,AuthName,etc ############################################## ############# end mod_ssl conf ############### </VirtualHost>

8. Testing the configuration:Now all you have to do is just open the browser and type in the url https://localhost:8080 and after which you will be displayed with a warning message by your browser as was mentioned before. The warning message look like the following in Mozilla Firefox.

You should add an exception for this after which the browser will download the CA certificate and you should see default apache web server page if successful. In mozilla certificate details can be seen by clicking on the navigation bar as shown below.

This is about it now we have set up and tested the SSL over http and hope this tutorial was helpful in making you understand the core concept behind digital certificates(X.509) public key encryption standard and setting up mod_ssl on your apache installation.

Posted on Sunday, August 29, 2010 by Unknown

Aug 15, 2010

In case you want to schedule or automate tasks like shutting down, restarting, hibernating , Standby and Locking then you can use this simple application made by me. It utilizes the psshutdown application and has a automated counter for planning the aforementioned tasks.

  • Just extract the rar file and after you extract there will be two folders, one will be install and the other one will be the application folder and there will also be an executable psshutdown utility.
  • Run the installer application by using the command "java -jar installer.jar"(without the quotes) on the install folder and click on the "Select extracted file psshutdown" button, select the extracted psshutdown file, click on the install button and the application will be ready to use.
  • Now just navigate to the application directory execute the command java -jar shutdown.jar from command prompt to launch the application.
Using the application:-
  • Just launch the application by opening command prompt at the application folder and invoking "java -jar shutdown.jar" (without the quotes) command .
  • Select the time and date for the scheduling the operation.
  • Select the operation from the drop down box that you want to execute and click on the submit button.
  • One can always abort the current operation in between by clicking on the abort button.
  • The label at the bottom will display the time left for the execution of the operation.
Download the application from the link below:-

Following are the snapshots of the application:-

Note:- Its always recommended to create a shortcut for running jar files. So just create a shortcut and in the target prefix the command 'javaw -jar' and save the shortcut.

Posted on Sunday, August 15, 2010 by Unknown

Jun 14, 2010

Browser's have same origin policy for ajax requests which means you cannot make a cross domain ajax request.

To overcome this barrier the following methods may be used.

  1. Use JSONP
  2. Make a service proxy
  3. Use dynamic script element

In this post i will be explaining  about how to use JSONP . I will be writing a simple script in dojo that will communicate with twitter api and return user's latest tweet's. The dojo.io.script method works by sending name of the callback method along with the asynchronous request and on completion of the request the callback method is called automatically by server side code.
The code snippet for the request is shown below.

var init=function(){

I have not used the load parameter in the above get call because i have done processing in the callback method itself.

The data received is passed as a json object to the callback method statusCallback as shown below.
var statusCallback=function(response)

The response object can now be parsed to get the relevant information.

The twitter box that you can see on the right side has been made using similar script.

The entire code can be seen below.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.4/dojo/dojo.xd.js" djconfig="parseOnLoad:true"></script>
<script type="text/javascript">
var doAddInfo=true;
var intervalId;
var statusCallback=function(response)
     var anims=[];
       for(var i=0;(i<response.length)&&(i<20);i++){
        var nodeName='index';  
  anims.push(dojox.fx.text.backspace({node:nodeName , interval:60 , fixed:true ,unhide:true}));
  var addInfo= function(username,screen_name,description,image){
     dojo.create("div",{id:'bigtext',align:'left',innerHTML:"<a href='http://www.twitter.com/"+screen_name+"'>"+"<img class='myimg'  src='"+image+"' width=50 height=50 /> </img></a>"+"<p align:'left'>"+username+"</p>"+"<p align='left' id='bio'>Bio:"+description+"</p>"},dojo.query("#twitter")[0],'first');
var addBird=function(){
dojo.create("div",{id:'plainimg',innerHTML:"<img src='http://dl.dropbox.com/u/42099017/smallflyingbirdsparklesright.png' width='50' height='50' />"},dojo.query("#bigtext")[0]);
dojo.attr('plainimg',{innerHTML:"<img src='http://dl.dropbox.com/u/42099017/smallflyingbirdsparklesright.png' width='50' height='50' />"});
var mainbox=dojo.marginBox(dojo.byId("twitter"));
var imgbox=dojo.marginBox(dojo.byId("plainimg"));
onEnd:function(){dojo.byId('plainimg').innerHTML="<img src='http://dl.dropbox.com/u/42099017/smallflyingbirdsparkles.png' align:'left' width='50' height='50' />";dojo.fx.slideTo({node:dojo.byId('plainimg'),
left:0,duration:1200,easing:dojo.fx.easing.elasticIn()}).play(); },easing:dojo.fx.easing.elasticOut()}).play();}
var display_tweet=function(element,index){
var a='index'+index;
dojo.create('div',{id:a,align:'left',innerHTML:"<p align='left'>"+element.text+"</p>"+"<a class='special' href='http://twitter.com/?status=@"+element.user.screen_name+"&in_reply_to_status_id="+element.id+"&in_reply_to="+element.user.screen_name+"'> reply"+"</a>"+"<hr/>"},dojo.query('#tweetbox')[0]);
    dojo.attr(a,{innerHTML:"<p align='left'>"+element.text+"</p>"+"<a class='special' href='http://twitter.com/?status=@"+element.user.screen_name+"&in_reply_to_status_id="+element.id+"&in_reply_to="+element.user.screen_name+"'> reply"+"</a>"+"<hr/>"} );
var errorHandler= function(err){
    dojo.publish("error", [{message:"Twitter is too 'Busy' cant render tweets",type:"error",duration:0}]);
dojo.addOnLoad(function (){
 <div id="twitter"><div id="tweetbox"></div></div>
<div dojotype="dojox.widget.Toaster" duration="0" messagetopic="error" positiondirection="tr-left" >

Posted on Monday, June 14, 2010 by Unknown

May 20, 2010

The display problems in linux occur mostly due to misconfiguration of X-server config file (xorg.conf) this may happen when you install or update graphics driver for your display card or due to various other reasons.

So to troubleshoot GUI display problem just follow these steps:
  1. Login as root
  2. At the shell prompt navigate to /etc/X11 directory (cd /etc/X11)
  3. Copy the failsafe configuration file to original file
    "cp xorg.conf.failsafe xorg.conf"
  4. Start the x-server
The aforementioned steps should resolve the display problems :-) .

Posted on Thursday, May 20, 2010 by Unknown

Apr 18, 2010

You might encounter a problem that when you start the kmix sound mixer you would not see any thing happening. It happens because it runs as an hidden application, so to access it you would need to add the system tray widget.

To add the system tray widget to your panel perform the following steps:-

1. Right click on the panel that you want to add your widget to.

2. Select the system tray widget as shown in the figure below.

3. Now you will be able to access the all the hidden applications and kmix being one of them, you would get the sound control applet where you can control the volume functionality.

Note: In case the above solution does not work you may try upgrading the kmix package by executing the following command.

sudo apt-get upgrade kmix

Posted on Sunday, April 18, 2010 by Unknown