Tests for Metadata.
| 47 | * Tests for {@link Metadata}. |
| 48 | */ |
| 49 | @RunWith(JUnit4.class) |
| 50 | public class MetadataTest { |
| 51 | |
| 52 | private static final Metadata.BinaryMarshaller<Fish> FISH_MARSHALLER = |
| 53 | new Metadata.BinaryMarshaller<Fish>() { |
| 54 | @Override |
| 55 | public byte[] toBytes(Fish fish) { |
| 56 | return fish.name.getBytes(UTF_8); |
| 57 | } |
| 58 | |
| 59 | @Override |
| 60 | public Fish parseBytes(byte[] serialized) { |
| 61 | return new Fish(new String(serialized, UTF_8)); |
| 62 | } |
| 63 | }; |
| 64 | |
| 65 | private static class FishStreamMarshaller implements Metadata.BinaryStreamMarshaller<Fish> { |
| 66 | @Override |
| 67 | public InputStream toStream(Fish fish) { |
| 68 | return new ByteArrayInputStream(FISH_MARSHALLER.toBytes(fish)); |
| 69 | } |
| 70 | |
| 71 | @Override |
| 72 | public Fish parseStream(InputStream stream) { |
| 73 | try { |
| 74 | return FISH_MARSHALLER.parseBytes(ByteStreams.toByteArray(stream)); |
| 75 | } catch (IOException ioe) { |
| 76 | throw new AssertionError(); |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | private static final Metadata.BinaryStreamMarshaller<Fish> FISH_STREAM_MARSHALLER = |
| 82 | new FishStreamMarshaller(); |
| 83 | |
| 84 | /** A pattern commonly used to avoid unnecessary serialization of immutable objects. */ |
| 85 | private static final class FakeFishStream extends InputStream { |
| 86 | final Fish fish; |
| 87 | |
| 88 | FakeFishStream(Fish fish) { |
| 89 | this.fish = fish; |
| 90 | } |
| 91 | |
| 92 | @Override |
| 93 | public int read() throws IOException { |
| 94 | throw new IOException("Not actually a stream"); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | private static final Metadata.BinaryStreamMarshaller<Fish> IMMUTABLE_FISH_MARSHALLER = |
| 99 | new Metadata.BinaryStreamMarshaller<Fish>() { |
| 100 | @Override |
| 101 | public InputStream toStream(Fish fish) { |
| 102 | return new FakeFishStream(fish); |
| 103 | } |
| 104 | |
| 105 | @Override |
| 106 | public Fish parseStream(InputStream stream) { |