Runtime tools : Core components : Formatters : Tasks : Handling binary message : Formatting a JavaBean into binary message : Usage tips
  
Usage tips
1 You can create a facade class in your application. With this facade class, you can call the formatJavaBean and unformatJavaBean methods. Following is the code sample:
public class FormatFacade {
public static byte[] formatJavaBean(String formatID, Object javaBean)
throws FormatterException {
ReadAdapter adapter = new JavaReadAdapter(javaBean);
FormatElement format = FormatFactory.getFormatElement(formatID);
Message message = format.format(adapter);
return message.toBytes();
}
public static void unformatJavaBean(String formatID, byte[] data,
Object javaBean) throws FormatterException {
WriteAdapter adapter = new JavaWriteAdapter(javaBean);
FormatElement format = FormatFactory.getFormatElement(formatID);
format.unformat(new Message(data), adapter);
}
}
2 For each formatID, there is only one instance of format element.
You can call method public static FormatElement FormatFactory.getFormatElement(String formatID) to get the instance of format element for the formatID defined in the xml file. FormatFactory caches the format element instance of each formatID for further usage.
3 There are two ways to instantiate FormatElement.
Creating format element from xml definition.
To create a format element from xml definition, you need to define the format element in the xml file first. Following is a sample defintion:
<format.xml>
<format id="PersonFormat">
<record>
<fString dataName="name" encoding="cp937"/>
<selfLength/>
<fInteger dataName="age" byteOrdering="host"/>
<selfLength/>
</record>
</format>
</format.xml>
After the definition is ready, you can create the format element instance using the following code:
FormatElement format = FormatFactory.getFormatElement(formatID);
Creating format element by hard code. Following is the sample code:
FormatDefine format = new FormatDefine();
format.setId("PersonFormat");
RecordFormat record = new RecordFormat();
StringFormat strF = new StringFormat();
strF.setDataName("name");
strF.setEncoding("cp937");
SelfLength selfLength1 = new SelfLength();
IntegerFormat intF = new IntegerFormat();
intF.setDataName("age");
intF.setByteOrdering("host");
SelfLength selfLength2 = new SelfLength();
record.addChild(strF);
record.addChild(selfLength1);
record.addChild(intF);
record.addChild(selfLength2);
format.addChild(record);
Go up to
Formatting a JavaBean into binary message