Archive for the ‘ Java ’ Category

NullPointerException at org.enhydra.jdbc.pool.GenericPool.getFromPool

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 4 out of 10)
Loading ... Loading ...

While many concurrent connections connect to database, my web application sometime will hit NullPointerException error from GenericPool.getFromPool method. This is weird, after i googling a while, i find out this is a bug in XAPool 1.5.jar, it already fix in XAPool 1.6 beta released (Fix for #303462). After i upgraded to XAPool1.6 beta, error message is gone.

Error detail
http://forge.objectweb.org/tracker/index.php?func=detail&aid=303673&group_id=59&atid=300059

Here to download latest XAPool
http://xapool.experlog.com/

java.lang.NullPointerException
	at org.enhydra.jdbc.pool.GenericPool.getFromPool(GenericPool.java:200)
	at org.enhydra.jdbc.pool.GenericPool.checkOut(GenericPool.java:351)
	at org.enhydra.jdbc.pool.StandardPoolDataSource.getConnection(StandardPoolDataSource.java:194)
	at org.enhydra.jdbc.pool.StandardPoolDataSource.getConnection(StandardPoolDataSource.java:164)
	at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:112)
	at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
	at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:513)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:581)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:610)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:618)
	at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:650)

How to download file from website- Java / Jsp

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (3 votes, average: 8.67 out of 10)
Loading ... Loading ...

Here i show a simple java example to demonstrate how to let user download a file from website. No matter you are using struts , JSP, Spring or whatever other java framework, the logic is same.

1) First we have to set HttpServletResponse response to tell browser about system going to return an application file instead of normal html page

response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=downloadfilename.csv");

we can also specified a download file name in attachment;filename=, above example export a csv file name “downloadfilename.csv” for user download.

2) There have 2 ways to let user download a file from website

Read file from physical location

File file = new File("C:\\temp\\downloadfilename.csv");
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
 
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, 4096) != -1)
{
	out.write(outputByte, 0, 4096);
}
fileIn.close();
out.flush();
out.close();

Export database data or string directly to InputStream for user download.

StringBuffer sb = new StringBuffer("whatever string you like");
InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
ServletOutputStream out = response.getOutputStream();
 
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(in.read(outputByte, 0, 4096) != -1)
{
	out.write(outputByte, 0, 4096);
}
in.close();
out.flush();
out.close();

3) Done

Here i show my struts example to demonstrate how to directly write data into InputStream and output it as “temp.cvs” to let user download.

public ActionForward export(ActionMapping mapping, ActionForm form,
	HttpServletRequest request, HttpServletResponse response)
	throws Exception {
 
	//tell browser program going to return an application file instead of html page
      response.setContentType("application/octet-stream");
      response.setHeader("Content-Disposition","attachment;filename=temp.csv");
 
		try 
		{
			ServletOutputStream out = response.getOutputStream();
			StringBuffer sb = generateCsvFileBuffer();
 
			InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
 
 
			byte[] outputByte = new byte[4096];
			//copy binary contect to output stream
			while(in.read(outputByte, 0, 4096) != -1)
			{
				out.write(outputByte, 0, 4096);
			}
			in.close();
			out.flush();
			out.close();
 
		}
		return null;
	}
 
private static StringBuffer generateCsvFileBuffer()
{
	StringBuffer writer = new StringBuffer();
 
		writer.append("DisplayName");
		writer.append(',');
		writer.append("Age");
		writer.append(',');
		writer.append("HandPhone");
		writer.append('\n');
 
            writer.append("mkyong");
		writer.append(',');
		writer.append("26");
		writer.append(',');
		writer.append("0123456789");
		writer.append('\n');
 
 
		return writer;
}

How to export data to CSV file - Java

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 5 out of 10)
Loading ... Loading ...

CSV is stand for Comma-separated values, CSV is a delimited data format that has fields/columns separated by the comma character and records/rows separated by newlines.

More detail please check http://en.wikipedia.org/wiki/Comma-separated_values

Please take a look at CSV sample,

Display Name,   Age, Hand Phone
Micheal , 30, 0123456789
Bill, 25, 0129876543

Actually CSV is just like a text file with a certain delimited like comma “,” or semi-comma “;” or any other delimited character you want. Here i will show how to use java to export data or writing data into a CSV file.

This sample is very simple and straight froward, it just use java FileWriter object to create a normal text file (CSV file).

package com.mkyong.test;
 
import java.io.FileWriter;
import java.io.IOException;
 
public class GenerateCsv
{
   public static void main(String [] args)
   {
	   generateCsvFile("c:\\test.csv"); 
   }
 
   private static void generateCsvFile(String sFileName)
	{
		try
		{
		    FileWriter writer = new FileWriter(sFileName);
 
			writer.append("DisplayName");
			writer.append(',');
			writer.append("Age");
			writer.append('\n');
 
			writer.append("MKYONG");
			writer.append(',');
			writer.append("26");
			writer.append('\n');
 
			writer.append("YOUR NAME");
			writer.append(',');
			writer.append("29");
			writer.append('\n');
 
			//generate whatever data you want
 
			writer.flush();
			writer.close();
		}
		catch(IOException e)
		{
		 e.printStackTrace();
		} 
	}
}

Simple right? Writing / export data to CSV file is exactly same with writing data into a normal text file. This is simple, we do not need any third party library to do it.

How to install java jdk on ubuntu (linux)

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (2 votes, average: 7 out of 10)
Loading ... Loading ...

How to install java jdk on Ubuntu? here i provide few steps to demonstrate how it’s work.

Installation Setup

1 ) Issue following command to find out current jdk version in apt-get

apt-cache search jdk

2 ) Install java JDK and JRE with apt-get install

apt-get install sun-java6-jdk sun-java6-jre

3 ) Ubuntu will auto download necessary file from web for installation.

Do you want to continue [Y/n]? y
Get:1 http://my.archive.ubuntu.com hardy/main java-common 0.28ubuntu3 [78.2kB]
Get:2 http://my.archive.ubuntu.com hardy/multiverse sun-java6-jre 6-06-0ubuntu1 [6334kB]
Get:3 http://my.archive.ubuntu.com hardy/main odbcinst1debian1 2.2.11-16build1 [66.2kB]
Get:4 http://my.archive.ubuntu.com hardy/main unixodbc 2.2.11-16build1 [289kB]
Get:5 http://my.archive.ubuntu.com hardy/multiverse sun-java6-bin 6-06-0ubuntu1 [27.3MB] 
Get:6 http://my.archive.ubuntu.com hardy/multiverse sun-java6-jdk 6-06-0ubuntu1 [9625kB] 
85% [6 sun-java6-jdk 3208002/9625kB 33%]


4) After installation done, jdk and jre will install at /usr/lib/jvm/java-6-sun-1.6.0.06

5) Ubuntu help to create a java symbolic link and put in /usr/bin for shortcut access

4 ) type java -version, DONE !!

Post-Installation Setup

Set JAVA_HOME into environment variable

Copy following statement and append to /etc/profile or .bashrc file, make system set JAVA_HOME into system environment variable.

export JAVA_HOME="/usr/lib/jvm/java-6-sun-1.6.0.06;"


P.S Please visit How to install JDK on Fedora Core, if you want to know how to install java jdk manually.

java.lang.UnsupportedClassVersionError: Bad version number in .class file

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 3 out of 10)
Loading ... Loading ...

This is always cause by conflict between different Java JDK at compile time and runtime.

For Example,
I use a JDK1.6 to compile a class file, WAR it and deploy to Tomcat server (another machine), but Tomcat server JAVA_HOME or JRE_HOME environment variable is set to JDK.1.5, it will cause

java.lang.UnsupportedClassVersionError:
Bad version number in .class file

This is same with other web server or application server as well, we have to make sure we are using same JDK version to compile it and run it.

Java Web Start (Jnlp) Tutorial - UnOfficial Guide

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (2 votes, average: 8.5 out of 10)
Loading ... Loading ...

Here is a brief explanation about Java Web Start from SUN

“Java Web Start is a mechanism for program delivery through a standard Web server. Typically initiated through the browser, these programs are deployed to the client and executed outside the scope of the browser. Once deployed, the programs do not need to be downloaded again, and they can automatically download updates on startup without requiring the user to go through the whole installation process again.”

This Java Web Start (Jnlp) Tutorial - UnOfficial Guide will guide you to do following

1) Create a simple AWT program and jar it as TestJnlp.jar
2) Add keystroke into TestJnlp.jar
3) Create a Jnlp file
4) Put all into Tomcat Folder
5) Access TestJnlp.jar from web through http://localhost:8080/Test.Jnlp

1) Install Java JDK/JRE version above 1.5 and Tomcat

2) Create a simple Java AWT program, file structure as picture below

AWT Source code

package com.mkyong;
 
import java.awt.*;
import javax.swing.*;
import java.net.*;
import javax.jnlp.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
 
public class TestJnlp {
  static BasicService basicService = null;
  public static void main(String args[]) {
    JFrame frame = new JFrame("Mkyong Jnlp UnOfficial Guide");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel label = new JLabel();
    Container content = frame.getContentPane();
    content.add(label, BorderLayout.CENTER);
    String message = "Jnln Hello Word";
 
    label.setText(message);
 
    try {
      basicService = (BasicService)
        ServiceManager.lookup("javax.jnlp.BasicService");
    } catch (UnavailableServiceException e) {
      System.err.println("Lookup failed: " + e);
    }
 
    JButton button = new JButton("http://www.mkyong.com");
 
    ActionListener listener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        try {
          URL url = new URL(actionEvent.getActionCommand());
          basicService.showDocument(url);
        } catch (MalformedURLException ignored) {
        }
      }
    };
 
    button.addActionListener(listener);
 
    content.add(button, BorderLayout.SOUTH);
    frame.pack();
    frame.show();
  }
}

P.S If “import javax.jnlp.*;” not found, please include jnlp library which located at JRE/lib/javaws.jar.

3) Jar It , located to java class file folder and issue following command in command prompt

jar -cf TestJnlp.jar *.*

4) Same location, Add keystroke name “testkeys”

keytool -genkey -keystore testKeys -alias jdc

It will ask for keystroke password, first name, last name , organization’s unit…etc..just fill them all.

5) Same location, Attached newly keystroke “testkeys” to TestJnlp.jar file

jarsigner -keystore testKeys TestJnlp.jar jdc

It will ask password for your newly created keystroke

6) Copy TestJnlp.jar to tomcat default web server folder.

C:\Program Files\Apache\Tomcat 6.0\webapps\ROOT

7) Create Test.jnlp file to execute TestJnlp.jar.

<?xml version="1.0" encoding="utf-8"?> 
<jnlp spec="1.0+" codebase="http://localhost:8080/" href="Test.jnlp">
	<information>
		<title>Jnlp Testing</title>
		<vendor>YONG MOOK KIM</vendor>
		<homepage href="http://localhost:8080/" />
		<description>Testing Testing</description>
	</information>
	<security>
		<all-permissions/>
	</security>
	<resources>
		<j2se version="1.6+" />
		<jar href="TestJnlp.jar" />
	</resources>
	<application-desc main-class="com.mkyong.TestJnlp" />
</jnlp>

Configuration is quite simple, please change accordingly.

8 ) Copy Test.jnlp to tomcat default web server folder also.

C:\Program Files\Apache\Tomcat 6.0\webapps\ROOT

9) Start Tomcat

C:\Tomcat folder\bin\tomcat6.exe

P.S Latest Tomcat like version 6, it already configure jnlp in web.xml properly. If jnlp is not response, please add following statement in your web.xml which located in tomcat conf folder.

  <mime-mapping>
    <extension>jnlp</extension>
    <mime-type>application/x-java-jnlp-file</mime-type>
  </mime-mapping>

10) Access URL http://localhost:8080/Test.jnlp, download Test.jnlp and double click on it

11) It will run as following if everything go fine

11) If you want to execute it again, just double click on Test.jnlp that you downloaded just now, it is no need to visit http://localhost:8080/Test.jnlp again

12) Done

If statement Becareful !!!

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 1 out of 10)
Loading ... Loading ...

Becareful!!, this is what i encounter today, what a stupid “If statement” i created….ai..do you seen what error below?

1
2
3
4
5
if(this.putNode(estraierFts, ftsUrlSync));
{
	//delete record after update
	ftsUrlSyncBO.deleteFtsUrlSync(ftsUrlSync.getId());
}

Above statement compile successfully in Java, what i trying want to do is , when condition true, it will delete my records. However with above statement, it will delete my record no matter condition true or false. This is funny, did you notice what error above? …. haha notice carefully , “;” after a “If statement”..what a stupid mistake i made.. TT…. my eyes are blur…take a rest first

Correct statement should be following

1
2
3
4
5
if(this.putNode(estraierFts, ftsUrlSync))
{
	//delete record after update
	ftsUrlSyncBO.deleteFtsUrlSync(ftsUrlSync.getId());
}

How to remove Whitespace between String - Java

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (3 votes, average: 6 out of 10)
Loading ... Loading ...

Today i play around with some funny and simple thing in Java, frankly i really do not know about it. I created following code like below

if(StringUtils.hasLength(sText)
 {
     sText= sText.replaceAll(" ", " AND ");			   
}

What i trying to do is remove all whitespace between a string. for example, user key in “Hello Google”, it will replace as “Hello AND Google”, ya this is correct if user only enter one space between word.

"Hello Google"  ---> "Hello AND Google"

But how about user key in many space in between? Haha.. For example

"Hello           Google"  ---> "Hello AND AND AND AND AND Google"

Above is not what i want, should i replace it as below?

if(StringUtils.hasLength(sText)
 {
     sText= sText.replaceAll(" ", " AND ");
     sText= sText.replaceAll("  ", " AND ");	
     sText= sText.replaceAll("   ", " AND ");	
     sText= sText.replaceAll("    ", " AND ");	
     sText= sText.replaceAll("     ", " AND ");				   
}

ya we can replace as many as we like, but this is not so effective and dynamic enough. Finally Regular Expression come to place and solve it.

if(StringUtils.hasLength(sText)
 {
     sText= sText.replaceAll("\\s+", " AND ");		   
}

Great , exactly what i want, Regular Expression ROCK!!!

Java Decompiler Plugin For Eclipse

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (4 votes, average: 4.25 out of 10)
Loading ... Loading ...

After integrated Java Decompiler (Jad) into Eclipse, when we click any java class file in eclipse, it will automatically decompile for us. This is very convenient and useful.

How to Integrated Java Decompiler with Eclipse

1) Download Jab and extract it
http://www.kpdus.com/jad.html

2) Download Jabclipse (net.sf.jadclipse_x.x.x.jar)
http://sourceforge.net/projects/jadclipse/

3) Copy Jabclipse(jadclipse_x.x.x.jar) to eclipse plugin folder

4) Restart Eclipse

5) Set Jadclipse Preference, Window –> Preference –> Java –> Jadclipse
Key in Jad path in Path to Decompiler field

6) Done, now we select any java class file, it will auto decompile it

Open Browser in Java windows or Linux

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 6 out of 10)
Loading ... Loading ...

Today i found a very useful java code, it can open browser from java application in windows or Linux.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.mkyong;
 
public class StartBrowser {
 
	public static void main(String args[])
	{
		String url = "http://www.google.com";
		String os = System.getProperty("os.name").toLowerCase();
	    Runtime rt = Runtime.getRuntime();
	    try{
	        if (os.indexOf( "win" ) >= 0) {
	        	// this doesn't support showing urls in the form of "page.html#nameLink" 
	            rt.exec( "rundll32 url.dll,FileProtocolHandler " + url);
	        } else if (os.indexOf( "mac" ) >= 0) {
	            rt.exec( "open " + url);
	        } else if (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0) {
	        	// Do a best guess on unix until we get a platform independent way
	        	// Build a list of browsers to try, in this order.
	        	String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
	        			"netscape","opera","links","lynx"};
 
	        	// Build a command string which looks like "browser1 "url" || browser2 "url" ||..."
	        	StringBuffer cmd = new StringBuffer();
	        	for (int i=0; i<browsers.length; i++)
	        		cmd.append( (i==0  ? "" : " || " ) + browsers[i] +" \"" + url + "\" ");
 
	        	rt.exec(new String[] { "sh", "-c", cmd.toString() });
	        } else {
	        	return;
	        }
	    }catch (Exception e){
	    	return;
	    }
	    return;	
 
	}
 
}