-
Notifications
You must be signed in to change notification settings - Fork 0
Events
When POJOs are (de)serialized by Piriti you can register event handlers to get notified
- after a POJO was read from JSON / XML
- after a POJO is written to JSON / XML
The events, handlers and relevant interfaces are all based on the event handlers used by GWT. See [http://code.google.com/webtoolkit/doc/latest/DevGuideUiHandlers.html] for details.
JsonReader<T> and XmlReader<T> both extend the interface HasModelReadHandler<T> which offers the method addModelReadHandler(ModelReadHandler<T>).
JsonWriter<T> and XmlWriter<T> both extend the interface HasModelWriteHandler<T> which offers the method addModelWriteHandler(ModelWriteHandler<T>).
In this simple example every mapped person is logged by the event handler LogHandler<Person>:
public class Person
{
public interface PersonJsonWriter extends JsonWriter {}
public static final PersonJsonWriter JSON_WRITER = GWT.create(PersonJsonWriter.class);
public interface PersonJsonReader extends JsonReader<Person> {}
public static final PersonJsonReader JSON_READER = GWT.create(PersonJsonReader.class);
public interface PersonXmlReader extends XmlReader<Person> {}
public static final PersonXmlReader XML_READER = GWT.create(PersonXmlReader.class);
public interface PersonXmlWriter extends XmlWriter<Person> {}
public static final PersonXmlWriter XML_WRITER = GWT.create(PersonXmlWriter.class);
String firstname;
String surname;
}
public class LogHandler<C> implements ModelReadHandler<Person, C>, ModelWriteHandler<Person>
{
@Override
public void onModelRead(ModelReadEvent<Person> event)
{
logger.info("Read person " + event.getModel() + " from " + event.getContext());
}
@Override
public void onModelWrite(ModelWriteEvent<Person> event)
{
logger.info("Wrote person " + event.getModel() + " to " + event.getRepresentation());
}
}
public class Main implements EntryPoint
{
public void onModuleLoad()
{
LogHandler handler = new LogHandler();
Person.JSON_READER.addModelReadHandler(handler);
Person.JSON_WRITER.addModelWriteHandler(handler);
Person.XML_READER.addModelReadHandler(handler);
Person.XML_WRITER.addModelWriteHandler(handler);
// start reading / writing persons
...
}
}
As you can see the read event carries information about the model and the context. The context is a JSONValue for JSON and a node in case of XML. The write event holds the model written and its representation as string.