// shall I write some keywords here to boost search engine ranking?

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, November 14, 2008

Java: convert UCS2 to UTF-8

While convert UCS2 into UTF-8, I hit UnsupportedEncodingException. So I use UTF-16 instead and it work well (at least till the time I write this post):


public String ucs2ToUTF8(byte[] ucs2Bytes) throws UnsupportedEncodingException{

String unicode = new String(ucs2Bytes, "UTF-16");

String utf8 = new String(unicode.getBytes("UTF-8"), "Cp1252");

return utf8;
}

Saturday, November 01, 2008

Duplicate Underscore in XML generated by XStream

When using XStream to serialise Java object into XML, alias name with undercore (_) will get duplicate. For example, "first_name" will be serialised as "first__name".

The reason is explained in their FAQ and the workaround is to provide your own XmlFriendlyReplacer. However, it do not give any example. So here is the example:


// replace $ with "ddd"
// replace underscore with underscore
XmlFriendlyReplacer replacer = new XmlFriendlyReplacer("ddd", "_");
XStream xstream = new XStream(new DomDriver("UTF-8", replacer));

Sunday, October 19, 2008

Java: Check if Socket Connection Broken

Most common ways of check if a socket connection to server was broken is by send a heartbeat message to server. However, for application that connect to server that do not support heardbeat, we can check connection by listen to the InputStream:

('is' refer to java.io.InputStream)


int bytesRead = is.read(receiveBuffer, 0, 1024);

// this is the trick to identify connection drop
if(bytesRead == -1){
throw new IOException("byteRead = -1, Connection closed.");
}

Sunday, September 28, 2008

Java: remove non-printable characters from String

Regular expression in Java is handy to remove non-printable character (control character, ASCII 0 - 31, 127) from a String:


String truncated = originalString.replaceAll("\\p{Cntrl}", "");

Sunday, September 21, 2008

ActiveMQ Failover with Async Send

Apche ActiveMQ is a popular open source JMS Message Broker. As in version 5.0, it support failover transport, and async send. But not both at the same time.

Both connection string below will NOT work:

failover:(tcp://remotehost:61616,tcp://localhost:61616)?jms.useAsyncSend=true
failover:(tcp://remotehost:61616?jms.useAsyncSend=true,tcp://localhost:61616?jms.useAsyncSend=true)

So the dirty trick I use is to write my own ContextFactory that override 'org.apache.activemq.jndi.ActiveMQInitialContextFactory'


package org.apache.activemq.jndi;

import java.net.URISyntaxException;
import java.util.Hashtable;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ActiveMQOptimisedSendInitialContextFactory extends ActiveMQInitialContextFactory{

@Override
protected ActiveMQConnectionFactory createConnectionFactory(
Hashtable environment
) throws URISyntaxException {
ActiveMQConnectionFactory connFactory = super.createConnectionFactory(environment);

connFactory.setUseAsyncSend(true);

return connFactory;

}

@Override
protected ActiveMQConnectionFactory createConnectionFactory(
String name,
Hashtable environment
) throws URISyntaxException {
ActiveMQConnectionFactory connFactory = super.createConnectionFactory(name, environment);

connFactory.setUseAsyncSend(true);

return connFactory;
}

}


Using this class as JNDI's 'java.naming.factory.initial', then the connection will be using async send by default, inlude failover transport.

Thursday, July 31, 2008

Reading List: July 2008 Wrapup

Just collection of article, blog post, etc that I come across and would like to share:

Scaling Your Your Java EE Application - Part 1, Part 2
Summary of various methods to make the application more scalable, vertically and horizontally.

Introducing Multithreaded Programming to JavaScript
In this multi-core era, everything multithreaded = good?

Java Performance Tuning: A Conversation With Java Champion Kirk Pepperdine
Interview that focus on Java performance tuning. Besides "measure, don't guess", "The box", also cover his opinion on dumb code vs complex code, etc.

Top 10 Concepts That Every Software Engineer Should Know
There is sure more than 10 concepts for software engineer to survive, but this is the top 10 from ReadWriteWeb.

Programmer Competency Matrix
Interesting matrix to do some self-evaluation. :P

Sunday, July 13, 2008

Get PID of Java program in Windows

In Linux, we can use ps to get process status of all process, include running Java program.

However, in Windows no matter using Task Manager or tasklist command, we can only see our running Java program as java.exe. So you cant differentiate them if you have multiple Java program running in same server.

And the good news is, we can now use a new command jps that bundle with JDK 1.6 to get the PID and main class/JAR file of running Java process.

For example, I start running Tomcat and ActiveMQ on my laptop, and with command jps -l, below is the output:

5280 C:\apache-activemq-5.0.0\bin\../bin/run.jar
1824 org.apache.catalina.startup.Bootstrap
2652 sun.tools.jps.Jps
By the way, Sun still mark jps as "experimental" status. For more information of jps, you may check it out here.

Wednesday, July 09, 2008

This is Java EE 5

I can't stop myself from laughing while I listening to this song from Roumen. Thanks to Arun Gupta for rediscover this. :P

Below is the lyric, hope you like it too. :D

Ladies and gentlemen, this is Java EE 5!

One, two, three, four, five
There's a technology I use day and night
For my application with a web frontend
They told me to use .Net
But I really don´t wanna

So many bugs I fixed last week.
My code is neat and talk is a cheap
I like Glassfish, JSF, persistence API
And as I continue you know they´re gettin´ sweeter

So what can I do I really beg you my Lord
To me codin' it´s just like a sport
All the bad code from the past, let me dump it
Please set in the trumpet

A little bit of injection in my life
A little bit of persistence by my side
A little bit of NetBeans is all I need
A little bit of EJB's what I see
A little bit of standards in the sun
A little bit of XML all night long
A little bit web services here I am
A little bit of code makes me real man

This is Java EE 5!

Jump up and down and move your code around
Shake your head to the sound bury bad code under ground
Move one step left and one step right
One to the front and one to the side
Refactor it once and refactor it twice
If it looks like this you're doin´ it right

A little bit of injection in my life
A little bit of persistence by my side
A little bit of NetBeans is all I need
A little bit of EJB's is what I see
A little bit of standards in the sun
A little bit of XML all night long
A little bit web services here I am
A little bit of code makes me real man

This is Java EE 5!

Tuesday, April 29, 2008

Spring PropertyPlaceholderConfigurer with default value

I like to use Spring framework's PropertyPlaceholderConfigurer to link to a .properties file to access my application configuration.

However, if a properties entry is missing from properties file, you will get BeanDefinitionStoreException. This is reasonable in most of time. But sometime you will just want to set some default value for certain entry (i.e. new entry that only applicable for new version and you want it to be backward compatible with old version configuration file).

For those scenarios, default value is supported by PropertyPlaceholderConfigurer as well by its setProperties(Properties props) method. Below is how it will look like:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>my_config.properties</value></property>
<property name="properties">
<props>
<prop key="entry.1">123</prop>
</props>
</property>
</bean>

Thursday, March 20, 2008

Classpath Explained

Classpath is one of the basic and yet confusing topic for many Java developer. I had spend some time to do some google and below is some of my summaries:

1. Classloading Sequence
Java load the classes with the sequence of: Bootstrap classes -> Extension classes -> User classes.

Bootstrap classes is the Java platform core classes such as rt.jar. Extension classes is the JAR file found in extension folder, normally JAVA_HOME/jre/lib/ext/. User classes is all the classes or JAR file set in the CLASSPATH.

2. Sequence does matter
When setting CLASSPATH, the sequence does matter. Java locate class file according to sequence of path/jar file in CLASSPATH. For example below:

set CLASSPATH=bin/;lib/MyJar.jar;.;

If bin/ and MyJar.jar contains the class file of same name (include package name), the class in bin/ will be load. If Bootstrap classes or Extension classes contains class of same name, it will have higher priority to be loaded.

3. Executable JAR file, the Good and Evil
Executable is convenient where you may just specify the main class of you application, and distribute it as a JAR file. And start it up by just double click the JAR file.

However, if you are to start you application with "java -jar MyJar.jar", all the user CLASSPATH will be ignored. Include the -cp and --classpath option in your java launcher command. The executable JAR file, and the classpath specified in the MANIFEST file will be the only place to search for user classes.

This also means that your program that load properties file from classpath will failed to locate the file. Unless you jar the properties file into the executable JAR file itself.

For example, if your program use log4j and it load configuration from default file 'log4j.properties', you need to add the log4j.properties into the JAR file inorder for log4j to locate it.

References & Further Reading

Wednesday, November 21, 2007

Determine Java class file version

Although latest version of JDK is already JDK 1.6, many servers in production might be still running with JRE 1.4. It is irritating to get error when running a Java program that compile with newer version of JDK.

So it will be good if there is a way to check the Java class file is compiled into which version.

And this is not difficult. The command is as below (if the class file you want to inspect is MyClass.class):

javap -verbose MyClass
And below is the example output:
Compiled from "MyClass.java"
public class MyClass extends java.lang.Object
SourceFile: "MyClass.java"
minor version: 0
major version: 50
Constant pool:
const #1 = class #2; // MyClass
const #2 = Asciz MyClass;
const #3 = class #4; // java/lang/Object
const #4 = Asciz java/lang/Object;
.
.


Below is the details of JDK version (source: Check the class version):

major  minor Java platform version 
45       3           1.0
45       3           1.1
46       0           1.2
47       0           1.3
48       0           1.4
49       0           1.5
50       0           1.6
Update 3 Oct 2014:

J2SE 8 = 52 (0x34 hex),
J2SE 7 = 51 (0x33 hex),

source: http://en.wikipedia.org/wiki/Java_class_file#General_layout

Wednesday, November 14, 2007

Enable JMX on Tomcat 5 and above

Since Tomcat 5.0, Tomcat manager webapp was introduced. JMX is not enabled by default on Tomcat 5.0 and above.

However, it is easy to enable it. The only pre-requisite is to run the Tomcat on JDK 1.5 or above.

In order to enable JMX on Tomcat 5.0, simply add this line to your catalina.bat:

set JAVA_OPTS=-Dcom.sun.management.jmxremote.port=7009 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false
Then you may use JConsole that come with JDK 1.5 and above or your favourite JMX client to monitor the Tomcat though port 7009.

Anyway, this will make the JMX open for unauthorised access. Will illustrate the steps to secure the JMX access to Tomcat in coming post.

Monday, October 01, 2007

Error: no 'server' JVM at '...'

Some workstation or server will not come with server JVM after you install JDK on it. When you run server JVM by 'java -server MyApp', you will get the error such as:

Error: no `server' JVM at `C:\Program Files\Java\jre1.6.0\bin\server\jvm.dll'.
There is a little trick to get the server JVM up and running:
  1. Copy 'server' folder from the JDK's JRE's bin folder (example: C:\Program Files\Java\jdk1.6.0\jre\bin\server)
  2. Paste the 'server' folder to JRE's bin folder(example: C:\Program Files\Java\jre1.6.0\bin)
  3. Done

Sunday, July 01, 2007

Executor Framework for JDK 1.4 and below

Executor Framework (java.util.concurrent) is one of the great feature in Java 5.0. However, the world is never perfect that all server is already in Java 5 or Java 6. For them who still stuck at 1.4, there is a backport of this framework: backport-util-concurrent

This is a good-to-have API in your classpath so that you may develop based on Executor Framework while you are in JDK 1.4. While it can be easily port to Java 5 or Java 6 in future.


Technorati Tags: ,

Saturday, April 14, 2007

Java Swing Application failed to start in Windows

Symptom:



Java Application with Swing GUI unable to start in server with Microsoft Windows and JRE 1.4.2.



When run in -verbose option, the program hang/stopped at:

......

......

[Loaded sun.awt.windows.WPanelPeer from C:\Program Files\Java\j2re1.4.2_04\lib\rt.jar]

[Loaded java.awt.peer.WindowPeer from C:\Program Files\Java\j2re1.4.2_04\lib\rt.jar]

[Loaded sun.awt.windows.WWindowPeer from C:\Program Files\Java\j2re1.4.2_04\lib\rt.jar]

[Loaded java.awt.peer.FramePeer from C:\Program Files\Java\j2re1.4.2_04\lib\rt.jar]

[Loaded sun.awt.windows.WFramePeer from C:\Program Files\Java\j2re1.4.2_04\lib\rt.jar]

[Loaded java.awt.dnd.peer.DragSourceContextPeer from C:\Program Files\Java\j2re1.4.2_04\lib\rt.jar]

[Loaded sun.awt.dnd.SunDragSourceContextPeer from C:\Program Files\Java\j2re1.4.2_04\lib\rt.jar]

[Loaded sun.awt.RepaintArea from C:\Program Files\Java\j2re1.4.2_04\lib\rt.jar]

[Loaded java.awt.event.ActionEvent from C:\Program Files\Java\j2re1.4.2_04\lib\rt.jar]

[Loaded sun.awt.EmbeddedFrame from C:\Program Files\Java\j2re1.4.2_04\lib\rt.jar]

[Loaded sun.awt.im.InputMethodWindow from C:\Program Files\Java\j2re1.4.2_04\lib\rt.jar]



Solution:



Run the Java Swing App with -Dsun.java2d.noddraw=true. Example:



java -Dsun.java2d.noddraw=true MySwingApp



Explanation:

DirectX's DirectDraw not working on the server. (Just a server, no reason to have a high end graphic card :p ).



As the directive name implied, -Dsun.java2d.noddraw=true will turnoff the DirectDraw. noddraw means&nbsp; no DirectDraw.



Resources:



List of undocumented properties to change the behavior of Swing in Suns JVM.





Technorati Tags: , , ,

Tuesday, March 13, 2007

Cross Platform File Path in Java

Recently come across some a Java program that have problem to work on Linux due the the program used "\" for directory.



It remind me of a dirty trick I used last time. Just used "/" in the code, it will work in both Windows and Linux.



Java as a cross platform language, already provide simple way to solve this with a static variable File.seperator . A much better alternative to my dirty trick.



Friday, January 05, 2007

My New Toy - JAG

JAG (Java Application Generator), as its name implied, ia a code generation tool.

I had test it by generating CRUD code from database schema and it is quite impressive. It is more than a toy.

Wednesday, September 27, 2006

Generate CRUD webapp from Database

This demo look cool!

Tuesday, August 15, 2006

Java, sound interesting...

Today had come across 2 exciting news on Java:

In my opinion, support for VB in their Java SE 7 (codename Dolphin) is just a marketing tactics to attract VB developers. The open source roadmap is more interesting to be watch out.

As in the roam map, it start with J2ME. Then follow by its J2SE compiler (javac) and HotSpot VM. This is a good strategy to start the open source incrementally from J2ME, a relatively smaller (both platform and community). Then based on experience gain from J2ME, the risk of open sourcing javac compiler and HotSpot VM will be lower.

I just have one concern. From Java SE 5 (Tiger) to Java SE 6 (Mustang) and later Java SE 7 (Dolphin), the time between each version is short compare to the gap among J2SE 1.3 and J2SE 1.4.

I wonder could J2EE cope up with this speed. And will this affect the population of J2EE developer community.


Monday, July 31, 2006

Session Persistent in Tomcat

Based on my past experience, I know that Tomcat is able to persist session. Which means user session can be restore after proper shutdown or restart of Tomcat.

However, recently all of my webapps on a Tomcat fail to restore the session. This is strange to me. I do some google to find out where to tweak my Tomcat to enable this. Then I found that it is enable by default, and many people is asking how to disable it.

I try to look into my work directory. When I shutdown, the file "SESSION.ser" which store session is created. When I start Tomcat, it was read then removed. But I still fail to retrieve the items in session.

Then something flash into my mind. The file is "SESSION.ser", ".ser" means serialized object file. The object I put into the session is not serialized, could this be the reason?

After some experiment, what I guess is true. If want to restore the object from session, the object must be serialized.

After doing years of Servlet/JSP, I only realised this by today. What a shame. -_-'''