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.
Share This
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:
More…
Share This
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:
More…
Share This
I’m really a big fan of oEmbed. My project Daily Fratze acts as oEmbed provider and consumer for example.
Now I’m really happy that twitter announced that it now acts as an oembed provider:
(I’d even be happier if twitter would autodiscover providers
)
To use this in a Java based application you can use my java-oembed lib with the following configuration:
Oembed oembed = new OembedBuilder(this.httpClient)
.withCacheManager(cacheManager)
.withBaseUri("http://yourproject")
.withConsumer("yourproject")
.withProviders(
new OembedProviderBuilder()
.withName("twitter")
.withFormat("json")
.withMaxWidth(480)
.withEndpoint("https://api.twitter.com/1/statuses/oembed.%{format}")
.withUrlSchemes("https?://twitter.com/#!/[a-z0-9_]{1,20}/status/\\d+")
.build()
)
.withHandlers(new CommonHandler("twitter"))
.build();
The handler looks like this:
import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import ac.simons.oembed.OembedResponse;
import ac.simons.oembed.OembedResponseHandler;
public class CommonHandler implements OembedResponseHandler {
private String handlerFor;
public CommonHandler(String handlerFor) {
this.handlerFor = handlerFor;
}
@Override
public String getFor() {
return handlerFor;
}
@Override
public void handle(Document document, Element a, OembedResponse response) {
final StringBuilder hlp = new StringBuilder();
final String title = StringEscapeUtils.escapeHtml(response.getTitle());
if(response.getType().equalsIgnoreCase("video") || response.getType().equalsIgnoreCase("rich")) {
hlp.append("<span style=\"display:block; text-align:center;\">");
hlp.append(response.getHtml());
hlp.append("</span>");
} else if(response.getType().equalsIgnoreCase("photo")) {
hlp.append("<span style=\"display:block; text-align:center;\">");
hlp.append(String.format("<img src=\"%s\" alt=\"%s\" title=\"%s\" style=\"width: %d; height: %d;\" />", response.getUrl(), title, title, response.getWidth(), response.getHeight()));
hlp.append("</span>");
}
a.before(hlp.toString());
a.remove();
}
}
Be careful to get the latest release, twitter has some real large values for cache ages and i needed to update a member from int to long.
To have WordPress automatically embed statusupdates, add the following line to the “functions.php” of your current theme. Create the file if it isn’t available in the root folder of your theme:
wp_oembed_add_provider('#https?://twitter.com/\#!/[a-z0-9_]{1,20}/status/\d+#i', 'https://api.twitter.com/1/statuses/oembed.json', true);
Whenever you add the plain link (whithout an anchor tag) to a statusupdate on a single line in a post, it will be embedded like the example above.
Update
If you are more into plugins, just download my Enable Twitter oEmbed WordPress plugin, install it and you’re good to go.
An alternative to oEmbed for Twitter was the Twitter Blackbird Pie Plugin for WordPress, but why adding more stuff if everything else is already there? My plugin is much more lightweight.
Embedding me looks like this, by the way:

the picture will always show my latest update on daily fratze.
As this is probably the last post here for this year, i wish every visitor some nice christmas holidays!
Share This
Here is some Java stuff I’ve written over the last year for Daily Fratze. All of the stuff is in use on Daily Fratze since June 2011.
- java-akismet
- java-akismet is a simple client for Akismet based on the latest version of Apache HttpComponents.
- java-oembed
- I really like the idea of oEmbed: A mechanism for auto embedding stuff from other sites so that users don’t have to paste some html code into a textbox but just plain links. This is my version of a configurable Java client that can autodetect oEmbed endpoints as well as statically configured endpoints.
- java-autolinker
- This is my idea of an autolinker based on jsoup. If you want to get autolinking right, you have to parse the text. Just scanning for regex that matches urls or email addresses is not enough. This autolinker first parses the text into a DOM tree and passes all text nodes to the configured linkers. At the moment it supports URLs, email addresses and twitter handles.
I’d be happy if someone can actually use this stuff too or even contribute to it
Share This