Sunday, June 27, 2010

apache.commons.dbcp.BasicDataSource Losts Connection with MySql after Long Time Inactive

I deployed my webapp into could server last week. Of course, I'm the only user of this webapp and just use it once a day currently. But when I use it, it reports the same exception every day:
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.TransactionException: JDBC begin failed

After I scroll down the Exception, the root cause is:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was49672 seconds ago.The last packet sent successfully to the server was 49672 seconds ago, which is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.

To solve this problem, the best way is to add property "testOnBorrow" in the dataSource configuration in you applicationContext.xml :

true


By adding testOnBorrow dbcp parameter, it will force a sanity check on every connection before it's used.

Friday, June 18, 2010

Linux for Java Programmer - Maven and Subversion

This part will setup the build environment, using subversion to check out source code and building it with Maven.

1.Install Maven2


sudo apt-get install maven2


2. Install Subversion


sudo apt-get install subversion

3. SVN check out

svn checkout http://your-repo.com/project/trunk projectname

4. Build with Maven

mvn clean package

Now you can copy your app.war to tomcat's webapps' directory.

Thursday, June 17, 2010

Linux for Java Programmer - Tomcat and File Operation

1. Download Tomcat


wget http://apache.mirror.aussiehq.net.au/tomcat/tomcat-6/v6.0.26/bin/apache-tomcat-6.0.26.tar.gz


2.Extract tar file


tar xvzf apache-tomcat-6.0.26.tar.gz


3. list directory


ls
-l
-s show hide file

4. Move file to another directory


sudo mv apache-tomcat-6.0.26 /usr/local/tomcat
Folder "apache-tomcat-6.0.26" will be moved to "usr/local" and renamed as "tomcat"

5. go to directory


cd /usr/local/tomcat/webapps
Press "tab" key can get your directory name completed automatically.
cd ..
cd ~

6. Delete file or directory

Let's delete a single file, "RUNNTING.txt"
rm RUNNTING.txt
Let's delete the example webapp
rm -rf examples
Remove all files and directories (recursive removal)

7. Start and shutdown Tomcat

start:
sh /usr/local/tomcat/bin/startup.sh
shutdown:
sh /usr/local/tomcat/bin/shutdown.sh

Linux for Java Programmer - setup Java environment

It is said that Ubuntu 10.04 removed sun-java package and replaced it with openjdk. So we need to add another souce manually.

1. Add jdk6 source

edit sources.list file
sudo vim /etc/apt/sources.list
The sources.list file is a key factor in adding or upgrading applications to your Ubuntu installation. This is also used by your system for system updates. The file is basically the roadmap for your system to know where it may download programs for installation or upgrade.
Append this line at the end:
#for ubuntu 9
deb http://archive.canonical.com/ lucid partner
#for ubuntu 10
deb http://archive.canonical.com/ubuntu maverick partner

#update source
sudo apt-get update

2. install jdk6



sudo apt-get install sun-java6-jdk
The jdk will be installed in this directory:
/usr/lib/jvm/java-6-sun

3. Check your jdk version


java -version
This is my jdk information
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)

4. Set JAVA_HOME variable


vi ~/.bashrc
append the following line at the end:
export JAVA_HOME=/usr/lib/jvm/java-6-sun

Wednesday, June 16, 2010

Using Dropbox as your image host

I was writing my blog in Blogger and suddenly sick about listing "in Windows, in Mac or in Linux". So I decide to find icons and design css styles for different operating systems' instructions. After a little search, I found three icons. My next problem is, where should I put those pictures.

Blogger? No, I don't want my image's src end like this:
http://1.bp.blogspot.com/_tkhEgj4TEWY/TBhB1C1q23I/AAAAAAAAAFo/M2PVlry6cOs/s1600/select_ubuntu_10.04.png. 

So I keep searching and find Dropbox can do image hosting job well. Here is how to do that.

1. Save the images in your Dropbox's Public folder



2. Simply right click (or control click) on a file, click the Dropbox submenu,
and then click 'Copy public link.'



Then you will get your image url like http://dl.dropbox.com/u/1350386/icons/mac.png.
It's very easy, just drag-drop-copylink.
Here is demo:

.os {
 background-repeat: no-repeat;
 background-position: left top;
 padding-left:40px;
}
.mac {
 background-image: url(http://dl.dropbox.com/u/1350386/icons/mac.png);
}
.win {
 background-image: url(http://dl.dropbox.com/u/1350386/icons/windows.png);
}
.linux {
 background-image: url(http://dl.dropbox.com/u/1350386/icons/linux.png);
}


Mac OS instruction here.


Linux OS instruction here.



Windows OS instruction here.



Have a try:

Linux for Java Programmer - Install

1. Install Ubuntu in Cloud Server


Install OS is very easy in cloud server, just one click:
just select the Ubuntu 10.04 LTS (Lucid Lynx)image then everything has done for you.

For those who install Ubuntu on your local mechine, make sure you choose SSH server during installation or you can use this command to install it after:

sudo aptitude install ssh


2. Conntect Server via SSH


After you finish installation of Ubuntu image, there will be a email regarding your ip adress and root password. Now you can connect to your cloud server via SSH.
(If you install it on your computer, you already have those information).

Fire your terminal, use the following command:
ssh username@123.456.789.0
username@server ip address

You can download a SSH client, such as putty
input your server's ip address and connect.

3. Create a new user for your server


adduser --home /home/kecai --ingroup sudo kecai
create sudo user "kecai" and set "/home/kecai" as his home directory.

4. Update and upgrade


apt-get update
update package cache


apt-get upgrade
upgrade the packages on your server to keep it secure.


5. Secure copy (Upload files to sever)


scp file.txt caike@123.345.678.90:/home/caike

5. Shutdown or reboot server
sudo shutdown -h now
Shutdown server immediately.


sudo reboot
reboot server.

Running Your Java Web Application in Cloud --- Linux for Java Programmer (0)

Today is my birthday and I decide to do something special to celebrate: I'm going to write a series of posts about how to setup a cloud server and make your Java web application running on the Internet. It will cover the completely steps of a cloud web server's setup, including JDK, apache http server, Tomcat and MySQL database's installation in Linux. This series are most about Linux, so it can also be called as "Linux for Java programmer:)

Why Java programmers need to learn Linux?


The short answer is, Linux enables your Java Web application to say hello to the world. Your talent can be recognized and maybe your web application can be next google or twitter.

Years ago, I read a article argued why there are more web applications developed in PHP than in Java. It pointed out that the cheapest hosting price was one of main reason why PHP+MYSQL is over Java for the web applications. This is because PHP web applications only need Apache (some mods, of course) and one Linux server can host many web applications.

On the contrary, even the simplest Java web applications need JVM and Servelt container. It is hard for different web apps to share one server. So the price for Java Web applications are much higher than PHP, even ASP hosting. And their hosting is limited, sometimes you can only upload a war file. We cannot get fully control of the server. So, most of my Java web applications are shown in "http://localhost:8080/myapp". I believe there are tons of excellent web applications are buried in "localhost:8080".

Last year, my two friends and I developed a vertical Chinese search engine, based on Nutch and Lucene. Nutch is not a web application, so we cannot simply buy a Servlet container hosting. We three did all the works to make our web application served the world: we bought a Dell rack server and installed Ubuntu Linux on it. Then we installed JDK, MySQL databases, Apache Http Sever, Tomcat and connected those two servers in Linux. At last, we send this Dell server to co-location center and remotely connect it do some jobs via SSH.

We spent about $2000 for the Dell server and pay $100 to the co-location center (this is the cheapest one I found in Sydney). Things are going well, except our web application is not very successful and the high cost. Without many visitors, we didn't suffer any performance problem.


However, things changed, there are many cloud services available at very cheap price, and the same fully control as co-location server with potential scalability. I decide to have a try with the cloud server. Similar to my last search web application's journal except we don't have to buy another server. And my last experience about setting up Linux server is painful. I am a java programmer with limited Linux experience, so I did a lot of reading and search. I wish there cloud be a guide specific for tuning Linux serving Java web application. This is why I decide to write this series. Following this series, you can easily make your server running without other references.

The cloud server provider I chosen is rackspacecloud and the Linux distribution is Ubuntu Server 10.04. It's my first time to use their service so there is nothing I can guarantee. You don't have to buy a cloud server to follow this tutorials. You can just install Ubuntu on your computer and try everything with it.

Friday, June 4, 2010

Eclipse Code Templates for JPA

I'm a lazy programmer or so called "copy-paste" programmer, always write code by edit previous code copy. Especially when they are tedious, repeated database CRUD operation. There are some quick develop tools, such as Appfuse and Spring Roo which, can generate basic code. But it is unavoidable to create some specific query operation by hand. I did a lot of copy&paste and finally find eclipse's code template can do this job for me.

To add your own code template, go to Windows->Preferences->Java->Editor->Templates
Then click "New".


put this code into "Pattern":
${:import(javax.persistence.EntityManager,javax.persistence.Query)}  

  String select = "select o from ${name} o WHERE o.${argname}=:${argname}";
  Query query = entityManager.createQuery(select);
  query.setParameter("${argname}", ${argname});
  return query.setFirstResult(firstResult).setMaxResults(maxResults)
    .getResultList();

When you need to use jpa query, type "jpaquery" and press "ctral+space" to fire code assistant(I change the default shortcut key to "alt+.", use whatever you customized).

now you can see the template code appers and focus on "name" then it will go to "argname".

Wonderful, here is a little explanation about the code template:

1. This will add import EntityManager and Query in your code if they are not. Feel free to add import, eclipse will check if it existed before add.
${:import(javax.persistence.EntityManager,javax.persistence.Query)}  


2. ${name}, ${argname} are the variables. The good part is all the variable will be changed as you edit.

This tutorial will show you how to create JPA code template and you can apply it to other code you copy-paste repeatedly.