Skip to contentMethod: fromPerson(Person)
1: package it.tidalwave.thesefoolishthings.examples.dci.marshal.xstream.converter;
2:
3: import javax.annotation.Nonnull;
4: import com.thoughtworks.xstream.converters.Converter;
5: import com.thoughtworks.xstream.converters.MarshallingContext;
6: import com.thoughtworks.xstream.converters.UnmarshallingContext;
7: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
8: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
9: import it.tidalwave.util.Id;
10: import it.tidalwave.thesefoolishthings.examples.person.Person;
11: import lombok.AllArgsConstructor;
12: import lombok.Getter;
13: import lombok.Setter;
14:
15: /***********************************************************************************************************************
16: *
17: * The custom converter for {@link Person}, which is immutable.
18: *
19: * @author Fabrizio Giudici
20: *
21: **********************************************************************************************************************/
22: public class PersonConverter implements Converter
23: {
24: @AllArgsConstructor @Getter @Setter
25: public static class MutablePerson
26: {
27: @Nonnull
28: private Id id;
29:
30: @Nonnull
31: private String firstName;
32:
33: @Nonnull
34: private String lastName;
35:
36: @Nonnull
37: public static MutablePerson fromPerson (@Nonnull final Person person)
38: {
39: return new MutablePerson(person.getId(), person.getFirstName(), person.getLastName());
40: }
41:
42: @Nonnull
43: public Person toPerson()
44: {
45: return new Person(id, firstName, lastName);
46: }
47: }
48:
49: @Override
50: public void marshal (@Nonnull final Object source,
51: @Nonnull final HierarchicalStreamWriter writer,
52: @Nonnull final MarshallingContext context)
53: {
54: context.convertAnother(MutablePerson.fromPerson((Person)source));
55: }
56:
57: @Override
58: public Object unmarshal (@Nonnull final HierarchicalStreamReader reader,
59: @Nonnull final UnmarshallingContext context)
60: {
61: return ((MutablePerson)context.convertAnother(null, MutablePerson.class)).toPerson();
62: }
63:
64: @Override
65: public boolean canConvert (@Nonnull final Class type)
66: {
67: return type.equals(Person.class);
68: }
69: }