01: /*
02: * Copyright (C) 2007 XStream Committers.
03: * All rights reserved.
04: *
05: * The software in this package is published under the terms of the BSD
06: * style license a copy of which has been included with this distribution in
07: * the LICENSE.txt file.
08: *
09: * Created on 17. May 2007 by Joerg Schaible
10: */
11: package com.thoughtworks.acceptance;
12:
13: import com.thoughtworks.xstream.XStream;
14: import com.thoughtworks.xstream.converters.reflection.FieldDictionary;
15: import com.thoughtworks.xstream.converters.reflection.FieldKey;
16: import com.thoughtworks.xstream.converters.reflection.FieldKeySorter;
17: import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
18:
19: import java.util.Comparator;
20: import java.util.Map;
21: import java.util.TreeMap;
22:
23: /**
24: * @author Jörg Schaible
25: */
26: public class CustomFieldKeySorterTest extends AbstractAcceptanceTest {
27:
28: protected XStream createXStream() {
29: return new XStream(new PureJavaReflectionProvider(
30: new FieldDictionary(new AlphabeticalFieldkeySorter())));
31: }
32:
33: static class Base {
34: String yyy = "y";
35: String ccc = "c";
36: String bbb = "b";
37: }
38:
39: static class First extends Base {
40: String aaa = "a";
41: }
42:
43: static class Second extends First {
44: String xxx = "x";
45: String zzz = "z";
46: }
47:
48: public void testSortsAlphabetically() {
49: xstream.alias("second", Second.class);
50:
51: String xml = "" + "<second>\n" + " <aaa>a</aaa>\n"
52: + " <bbb>b</bbb>\n" + " <ccc>c</ccc>\n"
53: + " <xxx>x</xxx>\n" + " <yyy>y</yyy>\n"
54: + " <zzz>z</zzz>\n" + "</second>";
55:
56: assertBothWays(new Second(), xml);
57: }
58:
59: private static class AlphabeticalFieldkeySorter implements
60: FieldKeySorter {
61:
62: public Map sort(Class type, Map keyedByFieldKey) {
63: Map map = new TreeMap(new Comparator() {
64:
65: public int compare(Object o1, Object o2) {
66: final FieldKey fieldKey1 = (FieldKey) o1;
67: final FieldKey fieldKey2 = (FieldKey) o2;
68: return fieldKey1.getFieldName().compareTo(
69: fieldKey2.getFieldName());
70: }
71: });
72: map.putAll(keyedByFieldKey);
73: return map;
74: }
75:
76: }
77: }
|