Java Application – Make sure only single/one instance running – with File Lock and ShutdownHook Monday, Jul 21 2008 

Often we want to make sure that only 1 instance our application running.
Because something terrible could happen when more than 1 instance running (for example the whole server would exploded and that would make you fired 😉 )

Nevertheless what the reason, one of the way to make this happen is by creating a lock file as a sign that an instance is currently running.
So you application will have this flow:

  1. Check if the lock file exists.
  2. Try to delete the lock file to check if there’s really a running process lock the file.
  3. Get the file lock.
  4. If failed to get the lock file, show error that there’s already an instance running –> the end
  5. If successfully get the lock then go on with your application want to do.
  6. When application ended/closed release the lock and delete the file lock.

package test.jimmy.filelock;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class MyApp {

    private static File f;
    private static FileChannel channel;
    private static FileLock lock;

    public static void main(String[] args) {
        try {
            f = new File("RingOnRequest.lock");
            // Check if the lock exist
            if (f.exists()) {
                // if exist try to delete it
                f.delete();
            }
            // Try to get the lock
            channel = new RandomAccessFile(f, "rw").getChannel();
            lock = channel.tryLock();
            if(lock == null)
            {
                // File is lock by other application
                channel.close();
                throw new RuntimeException("Only 1 instance of MyApp can run.");
            }
            // Add shutdown hook to release lock when application shutdown
            ShutdownHook shutdownHook = new ShutdownHook();
            Runtime.getRuntime().addShutdownHook(shutdownHook);

            //Your application tasks here..
            System.out.println("Running");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        catch(IOException e)
        {
            throw new RuntimeException("Could not start process.", e);
        }

    }

    public static void unlockFile() {
        // release and delete file lock
        try {
            if(lock != null) {
                lock.release();
                channel.close();
                f.delete();
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    static class ShutdownHook extends Thread {

        public void run() {
            unlockFile();
        }
    }

}

Technorati Tags: , , , , , ,

Advertisements

Using mock object with jmock 2 Wednesday, Dec 26 2007 

Okay, finally you decide it’s time to create a unit testing for your project (after a long ad hoc programming life :p).
When you create a sample unit testing, it’s all seem so simple.. you fascinate by the junit easiness, how it can do reflection and make it simple.

When you want to create a real unit testing for your project, you realize that a ‘real’ method is not like just adding 2 int argument and return a result. It’s more complex and using interface as parameter is common…
Now a thought cross your mind “do I have to create all stupid classes to implement all the interface I need?”, you starting to think that creating unit testing is really waste of time & you don’t want to do it anymore :p

It’s time mock object framework come to rescue… before you fall to the darkness of untested code 🙂
There’re several mock object framework like jMock, easymock, etc

Here’s an example creatin HttpMethod mock-object with jMock 2 & JUnit 3

public class sampleJMockTest extends MockObjectTestCase {
  public void testCreateHTTPMethod() {
    final HttpMethod httpMethod = mock(HttpMethod.class);
    checking(new Expectations() {
    {
      allowing(httpMethod).getResponseBodyAsString();
      will(returnValue("sample response"));
    }
    });
    SomeObject someObject = new SomeObject();
    someObject.someMethod(httpMethod);
  }
}

This sample will create an instance of HttpMethod (which is an interface) and when this mock object’s ‘getResponseBodyAsString’ method called it’ll return “sample response”.
So now we can easily create all interface implementation we need.Of course there’re more in jMock than just this simple feature, check it more at jMock Cookbook

Java – Adding new Classpath at Runtime Wednesday, Dec 19 2007 

There are cases where we need to add classpath at runtime. For example adding jar to classpath, but depends on configuration or some logic at runtime.

The class who responsible for handling classpath list is URLClassloader.
You can get current system URLClassLoader with:
URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

If you check javadoc about this class you’ll see:

protected void addURL(URL url)
Appends the specified URL to the list of URLs to search for classes and resources.

So you’ll just need to call the addUrl method to add new path/jar file.
But wait a minute, the method is protected… 😦 do I need to create a subclass or put the caller class on same package?
Creating a subclass is one way to do it, but there’s simpler way (I’ll create article about creating URLClassLoader subclass next time :p)

Here come the savior : Reflection
By using reflection we can break OOP concept about encapsulating method. It’s feel good to break the rules right (warning : use this at your own risk, you know you’re breaking the OO rule. So I won’t responsible if your computer explode or you’ll fighting with OO fans because of this)

Here a sample how to called it with reflection:

public static void addPath(String s) throws Exception {
  File f = new File(s);
  URL u = f.toURL();
  URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
  Class urlClass = URLClassLoader.class;
  Method method = urlClass.getDeclaredMethod("addURL", new Class[]{URL.class});
  method.setAccessible(true);
  method.invoke(urlClassLoader, new Object[]{u});
}

Happy reflecting.. 🙂

NetBeans 6 Bug – ConfigurationException Class in Apache Common Configuration is not Throwable? Wednesday, Dec 12 2007 

When I using Netbeans 6 (final released) and using Apache Common Configuration library, I encounter this bug.
Here’s how I found the bug :

  • Create a java application project
  • Add the library, I create a library name ‘Apache_Common_Configuration’ and add commons-configuration-1.5.jar to that library
  • Then I wrote the code

public static void main(String[] args) {
try {
INIConfiguration ini = new INIConfiguration("sample.ini");
} catch (ConfigurationException ex) {
ex.printStackTrace();
}
}

  • But the editor showing error on ‘ConfigurationException ex’ saying that ConfigurationException is not subclass of Throwable Class (I’ve upload the screenshot)

NetBeans 6 Bug - ConfigurationException Class

  • When I try to build it’s showing different error “class file for org.apache.commons.lang.exception.NestableException not found”
  • It’s look like Apache Common Configuration is using Apache Common Lang library (I also look to the source-code ‘ConfigurationException extends NestableException’). Error when compile showing me more help than error in editor.
  • So I create a library name ‘Apache_Common_Lang’ and add commons-lang-2.3.jar to that library
  • After add the library the editor still showing the same error : “ConfigurationException is not subclass of Throwable Class”
  • But when I run build, it run successful . No error at all. (Now I confused)
  • It’s look like there’s a bug in the Editor. And that red line & error icon in project window really bugging me, although I know it’s the editor bug not my code error.
  • So to make this ‘red-line’ disappeared, I combined commons-configuration-1.5.jar & commons-lang-2.3.jar into 1 jar file. And set a library to this jar (instead using 2 library or 2 jar file).
  • After this combined the editor not showing the error again.

Anyone having this problem too?

You can vote for this bug on : http://www.netbeans.org/issues/show_bug.cgi?id=124241

NetBeans IDE 6 final released Tuesday, Dec 4 2007 

Finally Netbeans 6 final released 🙂
Download it at NetBeans 6 Download

Can’t wait to download and install it.
I hope they’ve already fixed bugs in previous release (RC2).

Netbeans 6 – Configure which editor (representative class) for new type extension Tuesday, Nov 20 2007 

A friend who is using Netbeans 6 ask how to configure Netbeans so it’ll open his start.tml as an html file not just as ordinary text file (So the editor will full with color I assume, not just black text :p)

I didn’t asked him why the hell he using .tml not just .html 🙂 but I tell him that he can configure Netbeans 6 with:

  1. Choose Tools – Options
  2. Click on ‘Advanced Options’ button (on bottom left)
  3. Open the tree : ‘IDE Configuration’ – ‘System’ – ‘Object Types’
  4. Find ‘HTML Objects’
  5. Add extension tml to ‘Extension and MIME Types’ property
  6. Close
  7. Now evertime you double click .tml file it’ll call HTML objects’ representative class 🙂

*Check this article on NetBeans Community Doc ^^

Simple Log4J implementation Thursday, Nov 15 2007 

Why do we need a library for logger? doesn’t System.out.println help us enough?
When you try log4j you wouldn’t use System.out.println ever again… (Ok.. you will still used it.. occasionally :p)

What do you need? of course you need to download log4j first 😉 , get it at log4j download page
And open your favorite Java IDE.

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
*
* @author jimmy
*/
public class SampleLog4j {

private final static Logger LOGGER = Logger.getLogger(SampleLog4j.class);

public static void main(String[] args) {
PropertyConfigurator.configure(“log4j.properties”);
LOGGER.trace(“Level trace”);
LOGGER.debug(“Level debug”);
LOGGER.info(“Level info”);
LOGGER.warn(“Level warn”);
LOGGER.fatal(“Level fatal”);
}

}

This program will read file log4j.properties in the folder for log4j configuration.
Example of log4j.properties:

### file appender
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=sample.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ISO8601} — %p %C(%M):%L — %m%n
### console appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{ISO8601} — %p %C(%M):%L — %m%nlog4j.rootLogger=debug, console
# uncomment the line below if you want log output to file
# log4j.rootLogger=debug, file

And it’ll produce output:

2007-11-15 18:19:09,812 — DEBUG testing.SampleLog4j(main):26 — Level debug
2007-11-15 18:19:09,828 — INFO testing.SampleLog4j(main):27 — Level info
2007-11-15 18:19:09,828 — WARN testing.SampleLog4j(main):28 — Level warn
2007-11-15 18:19:09,828 — FATAL testing.SampleLog4j(main):29 — Level fatal

Why the log “Level trace” doesn’t logged, because we set the log level only to debug.
You should learn the configuration. There are 2 appender, 1 will log to console and other will log to a file.

Now why shouldn’t I used standard System.out.println?

  • You can’t set the level of log with println only
  • You will end up delete/comment the log using println
  • It won’t be that easy to create log to file with different filename daily (daily-rolling)
  • I wonder how your println can print class name, line number easily 🙂
  • … you can add more after you try it 😉

Change junit & run file (main class) working directory at Netbeans 5.5 Web Project Tuesday, Nov 13 2007 

If you create a new project with Netbeans and select to create “web application”.
You’ll notice that at ‘project properties’ – ‘Run’ there’s no ‘Working Directory’ configuration, unlike General Java Project.

But what if you want to create some console application (with main method) in that project with Netbeans. You run it with Netbeans shortcut shift+F6 (run file) and realize that Netbeans set the working directory to project base path.
Then you also try to run your unit testing (junit) and realize the same thing.
You put some configuration file to specific directory in your source folder, and of course your console app & unit testing can’t find it.

I’m not very familiar with Netbeans, but after some googling I found out that Netbeans using ant : file build-impl.xml in nbproject folder. If we change the project properties configuration Netbeans will re-generate the build-impl.xml.
Netbeans also provider file build.xml in project base folder for customizing project build & run.

So i add at build.xml (copy from build-impl.xml and modify the tag ‘dir’ value)

 <target name=”-init-macrodef-junit”>
<macrodef name=”junit” uri=”http://www.netbeans.org/ns/web-project/2″&gt;
<attribute name=”includes” default=”**/*Test.java”/>
<sequential>
<junit showoutput=”true” fork=”true” dir=”${basedir}/build/web/WEB-INF/classes” failureproperty=”tests.failed” errorproperty=”tests.failed”>
<batchtest todir=”${build.test.results.dir}”>
<fileset dir=”${test.src.dir}” includes=”@{includes}”/>
</batchtest>
<classpath>
<path path=”${run.test.classpath}”/>
</classpath>
<syspropertyset>
<propertyref prefix=”test-sys-prop.”/>
<mapper type=”glob” from=”test-sys-prop.*” to=”*”/>
</syspropertyset>
<formatter type=”brief” usefile=”false”/>
<formatter type=”xml”/>
</junit>
</sequential>
</macrodef>
</target>

<target name=”-init-macrodef-java”>
<macrodef name=”java” uri=”http://www.netbeans.org/ns/web-project/1″&gt;
<attribute name=”classname” default=”${main.class}”/>
<element name=”customize” optional=”true”/>
<sequential>
<java fork=”true” classname=”@{classname}” dir=”${basedir}/build/web/WEB-INF/classes”>
<jvmarg line=”${runmain.jvmargs}”/>
<classpath>
<path path=”${build.classes.dir.real}:${javac.classpath}:${j2ee.platform.classpath}”/>
</classpath>
<syspropertyset>
<propertyref prefix=”run-sys-prop.”/>
<mapper type=”glob” from=”run-sys-prop.*” to=”*”/>
</syspropertyset>
<customize/>
</java>
</sequential>
</macrodef>
</target>

So every unit test & run-file at Netbeans will have working directory to {project basedir}/build/web/WEB-INF/classes

Using svn+ssh with Netbeans 5.5 + Windows Tuesday, Nov 6 2007 

After you install Netbeans 5.5 you need to download/install subversion module.
At Netbeans menu select ‘Tools’ – ‘Update Center’ to add subversion module.
If the installation finished, you will see menu Subversion on Netbeans menu.

You’ll also need to install SVN : download page here

I’m using PuTTY’s plink.exe for ssh. You can get PuTTY package here.
Extract PuTTYto a directory and add path to that directory.
How to setting enviroment variables in Windows:

  • Open System Properties (by right click ‘My Computer’ – ‘Properties or by press button ‘windows’ + ‘break’)
  • Select tab Advanced & click button ‘Environment Variables’
  • You can edit System Variable : ‘path’
  • Add path to your PuTTY directory. (don’t delete other path, just add with ‘;’ as separator)
  • OK
  • You can check whether you have correctly add PuTTY’s path by running console (cmd) and run plink.exe without fullpath.

Then open subversion configuration file at : %APPDATA%\Subversion\config
Assuming you using default folder it will be : “c:\Documents and Settings\username\Application Data\Subversion\config”
Open file config using notepad or other text-editor.
Edit the [tunnels] section and add :

ssh = $SVN_SSH plink.exe -l <username> -pw <password>

Of course change the <username> and <password> with yours. lol.

Then save it & restart your Netbeans.
After that you should able to check out/import project via svn+ssh.

  • Select menu ‘Subversion’ – ‘Checkout…’
  • URL example : svn+ssh://100.1.1.1/opt/subv/myproject/trunk
  • Leave username & password empty
  • Click next & follow the instructions.

If there’s no errors then Congratulations 🙂

Integer, Byte, Long Constant Pool in Java Monday, Aug 13 2007 

Following the topic about constant pool.
Let’s look inside the source code JDK 1.6, java\lang\Integer.java :

public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}

From the source we can see when the value is -128 to 127 it’ll using cache / constant-pool.
So when we run the following code:

Integer i = 20;
Integer i2 = 20;
Integer i3 = 170;
Integer i4 = 170;
System.out.println(“i==i2 : ” + (i==i2) ); // true
System.out.println(“i==i2 : ” + (i3==i4) ); // false

Only value -128 until 127 will be cache. And of course the operator new wil create new object : new Integer(10)!=10.

Next Page »