KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > acceptance > ExternalizableTest


1 package com.thoughtworks.acceptance;
2
3 import java.io.Externalizable JavaDoc;
4 import java.io.IOException JavaDoc;
5 import java.io.ObjectInput JavaDoc;
6 import java.io.ObjectOutput JavaDoc;
7
8 public class ExternalizableTest extends AbstractAcceptanceTest {
9
10     public static class SomethingExternalizable extends StandardObject implements Externalizable JavaDoc {
11
12         private String JavaDoc first;
13         private String JavaDoc last;
14
15         public SomethingExternalizable() {
16         }
17
18         public SomethingExternalizable(String JavaDoc first, String JavaDoc last) {
19             this.first = first;
20             this.last = last;
21         }
22
23         public void writeExternal(ObjectOutput JavaDoc out) throws IOException JavaDoc {
24             out.writeInt(first.length());
25             out.writeObject(first + last);
26         }
27
28         public void readExternal(ObjectInput JavaDoc in) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
29             int offset = in.readInt();
30             String JavaDoc full = (String JavaDoc) in.readObject();
31             first = full.substring(0, offset);
32             last = full.substring(offset);
33         }
34     }
35
36     public void testExternalizable() {
37         xstream.alias("something", SomethingExternalizable.class);
38         
39         SomethingExternalizable in = new SomethingExternalizable("Joe", "Walnes");
40
41         String JavaDoc expected = ""
42                 + "<something>\n"
43                 + " <int>3</int>\n"
44                 + " <string>JoeWalnes</string>\n"
45                 + "</something>";
46
47         assertBothWays(in, expected);
48     }
49
50     static class Owner extends StandardObject {
51         SomethingExternalizable target;
52     }
53
54     public void testExternalizableAsFieldOfAnotherObject() {
55         xstream.alias("something", SomethingExternalizable.class);
56         xstream.alias("owner", Owner.class);
57
58         Owner in = new Owner();
59         in.target = new SomethingExternalizable("Joe", "Walnes");
60
61         String JavaDoc expected = ""
62                 + "<owner>\n"
63                 + " <target>\n"
64                 + " <int>3</int>\n"
65                 + " <string>JoeWalnes</string>\n"
66                 + " </target>\n"
67                 + "</owner>";
68
69         assertBothWays(in, expected);
70     }
71
72 }
73
Popular Tags