Get the uptime of your Java VM

You don’t need JConsole or similar for just displaying the approximate uptime of your application respectively your Java Virtual Machine:

import java.lang.management.ManagementFactory;
 
public class Demo {
	public static void main(String... args) {
		final long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
		System.out.println(String.format("Up for %dms", uptime));
	}
}

If you use Joda-Time (and you should if you have anything to do with date/datetime processing), you can format it nicely like so:

import java.lang.management.ManagementFactory;
import java.text.MessageFormat;
 
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
 
public class Demo {
	public static void main(String... args) {
		final Period vmUptime = new Period(ManagementFactory.getRuntimeMXBean().getUptime()).normalizedStandard(PeriodType.yearDayTime());
		final PeriodFormatter pf = new PeriodFormatterBuilder()
				.printZeroAlways()
				.appendDays().appendLiteral(MessageFormat.format("{0,choice,0# days, |1# day, |2# days, }", vmUptime.getDays()))
				.minimumPrintedDigits(2)
				.appendHours().appendLiteral(":").appendMinutes()
				.toFormatter();
		System.out.println(String.format("Up for %s", pf.print(vmUptime)));
	}
}

You also have a nice example of the often unknown MessageFormat.

| Comments (0) »

08-Feb-12


The dangers of Javas ImageIO

Javas ImageIO works… well, most of the time. It contains some unfixed, jpeg related bugs, but it works.

It may contain some dangers when used in a webbased application for generation large images on the fly.

Most problems are related to ImageIOs filed based caching and not flushing buffers when an IOException in an underlying stream occurs.

First, the javax.imageio.ImageReader. It caches some data in files. It is essential to dispose the reader and the underlying ImageInputStream after use if it’s not needed anymore like so:

if(imageReader.getInput() != null && imageReader.getInput() instanceof ImageInputStream)			
  ((ImageInputStream)imageReader.getInput()).close();
imageReader.dispose();

If it isn’t closed and disposed, the temporary cache files are either deleted not at all or maybe at the next garbage collection. I was able to bring down a VM by “java.io.FileNotFoundException: (Too many open files)” several times because i didn’t close a reader in a loop. Even the classloader wasn’t able to load any new classes after the ImageReader going mad on the file handle.

The other side is the javax.imageio.ImageWriter. There is an issue mentioned in the Tomcat Wiki.

I used the ImageWriter to dynamically create large images. I directly passed the javax.servlet.ServletOutputStream to the ImageWriter. If the generation of images takes long enough, there’s a good chance that the client aborts the request and the ServletOutputStream gets flushed right when the ImageWriter is writing to it. I didn’t have the exceptions mentioned in the wiki but my VM crashed. Great. I guess it had something to do with the native org.apache.coyote.ajp.AjpAprProtocol Ajp Apr connector i use, but that’s just guessing.

I solved this problem by using a temporary file and its related outputstream which i then stream like described here. This solution is not only faster but i also can catch any exception related to an aborting client.

Also take care to dispose the write as well like so:

try {
	 imageWriter.setOutput(out);
	 imageWriter.write(null, new IIOImage(image, null, null), iwp);
	 out.flush();
 } catch(IOException e) {                        
	 imageWriter.abort();                    
	 throw e;
 } finally {
	 try {                           
		 out.close();                            
	 } catch(Exception inner) {                              
	 }
	 imageWriter.dispose();
 }

This took me several hours to figure out… I hope someone finds this post useful.

| Comments (7) »

25-Jan-12


Optimizing web resources with wro4j, Spring and ehcache

I think that almost no website today can do without JavaScript. There are some incredible good JavaScript libraries like jQuery for which an enormous mass of plugins and extensions exits.

The downside of this is, that for example the JavaScript code of my daily picture project Daily Fratze is bigger than the whole startpage of my first “homepage” was.

With every problem there is a solution, namely JavaScript compressors and minifier. Those tools can compress the code by removing superfluous whitespaces, renaming variables and functions or even by optimizing the code.

So far i have used the YUI compressor maven mojo in my Spring based projects. This is a build time solution that compresses JavaScript and CSS files when creating a war file.

For me it had several disadvantages: I don’t see the effect of compressing when i develop my application and it could not concatenate multiple script files.

The later is important because every additional request a browser makes slows down the loading of a webpage. And manual hacking all JavaScript into one file? No way…

wro4j to the rescue:

Free and Open Source Java project which brings together almost all the modern web tools: JsHint, CssLint, JsMin, Google Closure compressor, YUI Compressor, UglifyJs, Dojo Shrinksafe, Css Variables Support, JSON Compression, Less, Sass, CoffeeScript and much more. In the same time, the aim is to keep it as simple as possible and as extensible as possible in order to be easily adapted to application specific needs.

My goal was to integrate wro4j with Spring and ehcache with a minimum number of additional configuration files.

If you’re interested in some of my ideas, read on:

Read the complete article »

| Comments (1) »

18-Jan-12


Creating a CSRF protection with Spring 3.1

Note: This tutorial is for Spring Security 3.1, an updated version that uses the build-in CSRF protection of Spring Security 3.2 can be found here

CSRF Attacks still seems to be a problem, a pity that there is no standard solution in the Spring 3.1 framework. Although not probably, i wanted to protect my projects by malicious crafted links.

I didn’t want to use an extra library but something which is already available in the Spring framework. Here is what i come up with:

Read the complete article »

| Comments (17) »

11-Jan-12


Mac OS X Lion loses network connection after sleep

Sleep related problems have never been a problem for me with OS X (at least the sleep of the machine) since Lion.

Sleep works perfectly fine but after wake my machine has no internet connection anymore, at least it looks like this. It’s only domains that aren’t resolved anymore. It also affects wired and wifi networks. There are a lot of threads in the Apple forums that blame USB drives, Optical drives and the like but this sounds a bit like voodoo.

I found the following working solution:

Edit “/System/Library/LaunchDaemons/com.apple.mDNSResponder.plist” like so:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Label</key>
	<string>com.apple.mDNSResponder</string>
	<key>OnDemand</key>
	<false/>
	<key>UserName</key>
	<string>_mdnsresponder</string>
	<key>GroupName</key>
	<string>_mdnsresponder</string>
	<key>ProgramArguments</key>
	<array>
		<string>/usr/sbin/mDNSResponder</string>
		<string>-launchd</string>
		<string>-AlwaysAppendSearchDomains</string>
		<string>-DisableSleepProxyClient</string>		
	</array>
	<key>MachServices</key>
	<dict>
		<key>com.apple.mDNSResponder</key>
		<true/>
	</dict>
	<key>Sockets</key>
	<dict>
		<key>Listeners</key>
		<dict>
			<key>SockFamily</key>
			<string>Unix</string>
			<key>SockPathName</key>
			<string>/var/run/mDNSResponder</string>
			<key>SockPathMode</key>
			<integer>438</integer>
		</dict>
	</dict>
	<key>EnableTransactions</key>
	<true/>
</dict>
</plist>

and relaunch the mDNSResponder like so:

sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist 
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist

This fixes to things: The domain resolution described here and the 2 hourly automatic wake from sleep described here.

Update:

It seems that fixed the problem just for that one time. To fix it every wake i use “SleepWatcher” by . Installed as said in the read me, save this file somewhere as restart_mDNSResponder

#!/bin/bash
killall -HUP mDNSResponder

and copy this

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>de.bernhard-baehr.sleepwatcher</string>
        <key>ProgramArguments</key>
        <array>
                <string>/usr/local/sbin/sleepwatcher</string>
                <string>-V</string>
                <string>-w /path/to/restart_mDNSResponder</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>KeepAlive</key>
        <true/>
</dict>
</plist>

to /Library/LaunchDaemons/de.bernhard-baehr.sleepwatcher-20compatibility.plist.

and execute

sudo launchctl load -w /Library/LaunchDaemons/de.bernhard-baehr.sleepwatcher-20compatibility.plist

This did the trick for me.

| Comments (0) »

05-Jan-12