Saturday, April 4, 2009

How to use SINGLETON pattern in a application to access Database?

This is sample code for accessing database by applying Singleton design pattern which is also thread safe because of eager initialization.

/*
Java class code for the above purpose.
*/
import java.sql.Connection;
import java.sql.DriverManager;

public class DBConf {
    private static Connection connection;
       
    static{
        try{
            String dbUrl = "jdbc:mysql://dbhost:dbport/dbname";
            String dbUname = "dbusername";
            String dbPword = "dbpassword";
            
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(dbUrl, dbUname, dbPword);
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    private DBConf(){}
    
    public static Connection getConnection(){
        return DBConf.connection;
    }
}

Look at the constructor which is defined as private so no one can instantiate it. The client can use the getConnection() method to get the Connection which is already eagerly loaded. This single connection can be used to access the Database by the whole application by not openning new connections.

Now a question comes, when to close the connection. My solution is just add a listener class to this application. 

/*
Add this code to your web.xml file. Please replace ] with > and [ with < in the following code.
*/

[listener]
        [listener-class]ApplicationWatch[/listener-class]
[/listener]

/*
Write the following class in your application default source directory.
*/
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;

public class ApplicationWatch implements ServletContextListener {
/* Application Startup Event */
public void contextInitialized(ServletContextEvent ce) {}

/* Application Shutdown Event */
public void contextDestroyed(ServletContextEvent ce) {
            try{
                DBConf.getConnection().close();
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }
}

So, when the application will be destroyed (i.e. undeploying the application from the server) the connection will be closed.

Problems
1. This connection should be alive for the application lifetime. But the real scenario is, Database like MySQL shutdown the idle connection when it reaches its wait timeout, default is 8 hours.

But for, heavy hitted application for database connection, connection pooling is a better solution. Hope I will write about it in future.

Wish this article will help you. Thanks.

Sunday, March 29, 2009

Hibernate Exception - java.net.SocketException: Broken pipe

In my current project I am using Hibernate ORM model for java to mysql bridge. And after deploying the module in a test sever I got the exception "java.net.SocketException: Broken pipe".

I have found the possible reasons may be, 

1. I didn't set the connection timeout parameters for the connection pool
2. The main scenario is, hibernate connection pool keeps the opened connection for a long time and mysql closes it when its idle time reaches for the opened connection.
3. When hibernate trys to do something with this connection which is closed by mysql got the exception.

Possible solution is, try to define the idle timeout value for the connection in hibernate lower than the mysql system connection idle timeout. This is very easy in hibernate.cfg.xml file to define the connection pool parameters and a lot of web resources can be found by google how to do it. 

Thanks. Hope it will help you.

Tuesday, September 16, 2008

MySQL Scheduled Events

At the time of my undergraduate study, I had to implement a database project. In that project I had to implement a module almost like the working style of trigger just on the event of some specific time and interval. At that time I designed that module by implementing an outside program which runs as a process and at specific time it fires and manipulates some database tables.

But , today I have learned a new feature of mysql which is called Scheduled Events which runs a batch of sqls on a specific time or intervals. See the following link, how to create a scheduled event in mysql 5.1 or later version. Hope it is useful to all developers.

http://dev.mysql.com/tech-resources/articles/mysql-events.html#1

Monday, July 21, 2008

Reading a txt file Content from URL by JavaScript

The html file having this script should be in the same domain with txt file for accessing from mozilla firefox because of security reason. From internet explorer txt file from any url can be read.

var xmlhttp;
function getFile(pURL) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",pURL,true);
xmlhttp.onreadystatechange = showFileContent;
xmlhttp.send(null);
}

function showFileContent() {
if (xmlhttp.readyState==4) {
if (xmlhttp.status==200) {
var out=xmlhttp.responseText;
document.getElementById('theExample').innerHTML=out;
}
}
}

See my codes, 1 having this script and reads contents from 2.
  1. http://debasisroy144.googlepages.com/helloworld.html
  2. http://debasisroy144.googlepages.com/helloworld.txt

Friday, July 18, 2008

Sending mail with attachment by JAVA

For this class mail-1.4.jar file will be needed as a library which can be found in this following site
http://www.java2s.com/Code/Jar/wsit/Downloadmail14jar.htm

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail {

public SendEmail() {
}
public static void sendEmail(String host, String from, String to, String subject, String infoMessage) throws Exception {
sendEmailWithAttachment(host, from, to, subject, infoMessage, "n/a");
}
public static void sendEmailWithAttachment(String host, String from, String to, String subject, String infoMessage, String fileAttachment) throws Exception {

// Get system properties
Properties props = System.getProperties();

// Setup mail server
props.put("mail.smtp.host", host);

// Get session
Session session = Session.getInstance(props, null);

// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);

// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();

//fill message
messageBodyPart.setText(infoMessage);

Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);

// Part two is attachment
if(!fileAttachment.equals("n/a")){
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("MarbilReport.pdf");
multipart.addBodyPart(messageBodyPart);
}

// Put parts in message
message.setContent(multipart);

// Send the message
Transport.send( message );
}
}

Thursday, July 17, 2008

Configuring Tomcat Server for JAX-WS Support

Step 1 – Install JAX-WS
Go to https://jax-ws.dev.java.net/2.1.3/ and click on the link to download the binary. Double click on the downloaded binary and this will extract the contents into a sub-folder jaxws-ri. If you look in jaxws-ri\lib you will see all the jars that we need for deploying to Tomcat

Step 2 – Copy JAX-WS jars to Tomcat
Copy all the jars from jaxws-ri\lib to Tomcat lib directory. Tomcat will now support WebServices.

Step 3 – Include the JAX-WS Jars in the Project Path to compile Web Services and Web Service clients
Just add the jar file jaxws-tools.jar can be found in the extracted folder jaxws-ri\lib.


For more details please visit this site, http://life-on-a-laptop.blogspot.com/