Sunday, August 31, 2008

Implementing your own encoder in the Encoder Tool

As I already mentioned in the Encoder's introduction post, the main feature of the Encoder Tool is an extensibility. Meaning that you can implement your own encoders and plug them to the Encoder Tool.

In this guide, I'll explain how to create a custom encoder and plug it into the Encoder Tool. This guide applies to the current Encoder's version (0.2.0).

Create Java Project

Download the distribution of the Encoder (zip file) and create a java project. Add an encoder's jar and third-parties jars from the lib folder to the project's classpath.

Create an Encoder's Class

Create a new class that extends tarlog.encoder.tool.api.AbstractEncoder.

Implement encode() Method

This is the most important method to implement, the method that is responsible to the encoder's logic. First, you'll need to pay attention that there are two encode methods that you can override:
* Object encode(String source)
* Object encode(byte[] source)
You must override at least one of these methods, but usually you will override only one.

So what is the difference?
Object encode(String source) is invoked when the input is a text.
Object encode(byte[] source) is invoked when the input is a byte array.
Simple, isn't it?

The default implementation of these methods is to call each other, which leads to endless recursion if you don't implement one of the methods. The Encoder Tool asserts that you implement one of the methods and will throw an exception if you don't.

The result of the encode method should be either a String or a byte array. If other object is returned, its toString() method will be invoked. If null is returned, the output will remain unchanged.


package tarlog.encoder.tool.encoders;


import tarlog.encoder.tool.api.AbstractEncoder;

public class MyUrlEncoder extends AbstractEncoder {

public Object encode(String source) {
try {
return URLEncoder.encode(source, "UTF-8");
} catch (UnsupportedEncodingException e) {
return null;

Plug in a Customer Encoder to the Encoder Tool

To plugin in a custom encoder to the Encoder Tool do the following:
1. Open preferences page and add a new encoder. You can add it either to the existing group or you can create a new group.
2. When you add the encoder, you should provide a name, a class name and a classpath.
3. Define classpath of the encoder, it may contain class folders or jars.
4. Press OK and start using your encoder.


In this post I have described how to create custom encoders to the Encoder Tool. As you could see, it's very very simple. However, you may say, what happens if the custom encoder needs an additional input? Just like the "Digital Signatures" encoders. So there is solution for this, but it will have to wait for the next post.

No comments: