Simple, concise Java examples that do useful things.

Thursday, November 23, 2006

Starting a worker thread in a Servlet Engine

Today's example shows how to create a background thread when your servlet context starts up, and how to end the thread's activities gracefully when the servlet context is destroyed. Take this example and add it as a "listener" in your web application, then using the Tomcat (or equivalent) manager start and stop the context and watch the stdout messages.


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class Deamon implements ServletContextListener, Runnable {

private Thread t;

public void contextDestroyed(ServletContextEvent arg0) {
t.interrupt();}

public void contextInitialized(ServletContextEvent context) {
t = new Thread(this);
t.start();
System.out.println("deamon started");}

public void run() {
try {
while (true) {
System.out.println("deamon working...");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("deamon stopped");}
}
}

Saturday, September 16, 2006

All purpose String trimmer

The java string class supports a trim() operation that trims ' '. You may find that you want to trim another character. This terse example will trim any character from the beginning and end of a String. It is based on the JDK's trim() method with a few more attempts at brevity.



public static String trim(String source, char c) {
int len = source.length();
int st = 0;
char[] val = source.toCharArray();
for (;(st < len) && (val[st] <= c);st++){}
for (;(st < len) && (val[len-1]<=c);len--){}
return ((st > 0) || (len < source.length())) ?
source.substring(st, len) : source;
}

Saturday, September 02, 2006

XMP Dumper reduced

I was able to trim this one down a bit more.


import java.io.*;

public class XMPDumper {

public String getXMP(File f) throws IOException {
return getXMP(new FileInputStream(f));
}

public String getXMP(InputStream is)
throws IOException {
for (int i=0;(i=is.read())!=-1;)
if (i==0xFF && is.read()==0xE1) {
String result = getXMPSegment(is);
if (result.startsWith("http://ns.adobe.com/xap/1.0/"))
return result.substring(29);
}
return null;
}

private String getXMPSegment(InputStream is)
throws IOException {
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[dis.readShort()-2];
dis.read(buffer);
return new String(buffer);
}
}

Saturday, August 26, 2006

Friday, August 25, 2006

XMP metadata dumper

XMP is a metatdata format from Adobe. One way to add and edit XMP is with PixVue. This is a minimalist XMP extractor/dumper for the jpeg format.


import java.io.*;

public class XMPDumper {

public static void main(String[] args) throws IOException {
File f = new File("myimage.jpg");
String xmp = new XMPDumper().getXMP(f);
System.out.println(xmp);
}

public String getXMP(File f)
throws IOException {
FileInputStream is = new FileInputStream(f);
int i=0; String result=null;
while ((i=is.read()) != -1)
if (i==0xFF && is.read()==0xE1) {
result = checkNamespace(is);
if (result!=null) break;
}
return result;
}

public static final String namespace =
"http://ns.adobe.com/xap/1.0/";

private String checkNamespace(FileInputStream is)
throws IOException {
String s = getSegment(is);
return (s.startsWith(namespace)) ? s.substring(29) : null;
}

private String getSegment(InputStream is)
throws IOException {
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[dis.readShort()-2];
dis.read(buffer);
return new String(buffer);
}
}

Resource Consumption Management API

Resource Consumption Management API JSR

This sounds like JINI or JMX to me...the JCP is becomming an echo chamber.

Thursday, August 24, 2006

Simple template replacer

Often I find I need a simple template engine to replace named regions.



public abstract class Replace {

public static void main(String[] args) {
Replace r = new Replace() {
public String lookup(String key) {
return "*newvalue*";
}
};
String s =
"Welcome ${name}, you have just won a new ${prize}.";
System.out.println(r.replace(s));
}

public String replace(String s) {
return replace(s, 0, new StringBuilder()).toString();
}

private StringBuilder replace(String s, int offset, StringBuilder b) {
int startKey = s.indexOf("${", offset);
if (startKey == -1)
return b.append(s.substring(offset));
else {
b.append(s.substring(offset, startKey));
int keyEnd = s.indexOf('}', startKey);
String key = s.substring(startKey + 2, keyEnd);
b.append(lookup(key));
return replace(s, keyEnd + 1, b);
}
}

abstract public String lookup(String key);
}