private String toXML(Application app) throws Exception {
XStream xStream = new XStream(new DomDriver());
xStream.registerConverter(new ApplicationConverter());
xStream.alias("application", Application.class);
return xStream.toXML(app);
}
private Application toApplication(String xml) throws Exception {
XStream xStream = new XStream(new DomDriver());
xStream.registerConverter(new ApplicationConverter());
xStream.alias("application", Application.class);
return (Application) xStream.fromXML(xml);
}
class ApplicationConverter implements Converter {
private static final String FULLDATE_FORMAT = "dd/MM/yyyy HH:mm:ss";
/** Marshall xml into application object */
public void marshal(Object obj,
HierarchicalStreamWriter writer,
MarshallingContext context) {
Application app = (Application) obj;
pushContent(writer, "applicationId", app.getApplicationId());
DateFormat formatter = new SimpleDateFormat(FULLDATE_FORMAT);
pushContent(writer, "createdDate", formatter.format(app.getCreatedDate()));
pushMapContent(writer, app.getFields());
}
/** Push content into xml */
private void pushContent(HierarchicalStreamWriter writer,
String key, Object value) {
writer.startNode(key);
writer.setValue(value.toString());
writer.endNode();
}
/** Push map content into xml */
private void pushMapContent(HierarchicalStreamWriter writer, Map map) {
Iterator iter = map.keySet().iterator();
while(iter.hasNext()) {
String key = (String) iter.next();
Object value = map.get(key);
writer.startNode(key);
if (value instanceof Map) {
pushMapContent(writer, (Map) value);
}
else if (value instanceof String) {
writer.setValue((String) value);
}
writer.endNode();
}
}
/** Unmarshall application into xml */
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
Application app = new Application();
DateFormat formatter = new SimpleDateFormat(FULLDATE_FORMAT);
while (reader.hasMoreChildren()) {
reader.moveDown();
try {
if ("applicationId".equals(reader.getNodeName())) {
app.setApplicationId(reader.getValue());
}
else if ("createdDate".equals(reader.getNodeName())) {
app.setCreatedDate(formatter.parse(reader.getValue()));
}
else {
popMapContent(reader, app.getFields());
}
}
catch(ParseException e) {
LOG.debug("Parsing date for "+reader.getNodeName()+" has failed", e);
}
reader.moveUp();
}
return app;
}
/** Pop xml into map content */
private void popMapContent(HierarchicalStreamReader reader,
Mapmap) {
if (reader.hasMoreChildren()) {
MapchildMap = new TreeMap ();
map.put(reader.getNodeName(), childMap);
while (reader.hasMoreChildren()) {
reader.moveDown();
popMapContent(reader, childMap);
reader.moveUp();
}
}
else {
map.put(reader.getNodeName(), reader.getValue());
}
}
public boolean canConvert(Class clazz) {
return clazz.equals(Application.class);
}
}
Showing posts with label xstream. Show all posts
Showing posts with label xstream. Show all posts
9/30/2008
xstream: custom converter
marshal/unmarshal
Subscribe to:
Posts (Atom)