I came across a little challenge today when modifying an existing java collaboration in Java CAPS.
I'm calling an AccuWeather service to get a short-range forecast for a given location. In the reply, there's a small two-digit numerical element which refers to the icon which represents that day's weather. I need to take that icon and base64 encode it before sending it out of Java CAPS.
You can fetch the relevant image by constructing a URL quite easily but obviously I don't want to be doing this too often and I'd prefer to have a local cache of those images. But how to access them from a java collaboration?
The solution is simple when you know how to do it - it took a fair amount of searching (and a stupid bug of my own making) before I came up with an answer.
- Have all your images in a directory, then create a jar file with the contents of that directory. Mine are named 01.gif, 02.gif, ... and so on.
- Import the jar into your java collaboration.
- Access the image you need using
getResourceAsStream().
- Read the bytestream.
- Perform the Base64 encoding.
Here's the relevant code snippet:
java.io.BufferedInputStream is = new java.io.BufferedInputStream(
this.getClass().getResourceAsStream( "/WeatherImages/" +
iconNum +
".gif" ) );
if (is != null) {
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
byte[] buf = new byte[1024];
int bytesRead = 0;
while ((bytesRead = is.read( buf, 0, buf.length )) > 0) {
bos.write( buf, 0, bytesRead );
}
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String iconEncoded = encoder.encode( bos.toByteArray() );
// Next line removes CRLFs which mobility pack Base64 decoder
// doesn't seem to like
iconEncoded = iconEncoded.replaceAll( "\r|\n", "" );
output.getForecastResponseType().getForecast( i1 ).setIcon( iconEncoded );
is.close();
}
|
Well that wasn't very obvious now, was it... ;)
Posted by ioj on August 08, 2008 at 05:09 PM BST #