Debian Codegraph @

src/test/java/com/fasterxml/jackson/dataformat/smile/TestGeneratorBinary.java

raw
1 package com.fasterxml.jackson.dataformat.smile;
2
3 import java.io.*;
4
5 import org.junit.Assert;
6
7 import com.fasterxml.jackson.core.*;
8
9 public class TestGeneratorBinary extends SmileTestBase
10 {
11 static class ThrottledInputStream extends FilterInputStream
12 {
13 protected final int _maxBytes;
14
15 public ThrottledInputStream(byte[] data, int maxBytes)
16 {
17 this(new ByteArrayInputStream(data), maxBytes);
18 }
19
20 public ThrottledInputStream(InputStream in, int maxBytes)
21 {
22 super(in);
23 _maxBytes = maxBytes;
24 }
25
26 @Override
27 public int read(byte[] buf) throws IOException {
28 return read(buf, 0, buf.length);
29 }
30
31 @Override
32 public int read(byte[] buf, int offset, int len) throws IOException {
33 return in.read(buf, offset, Math.min(_maxBytes, len));
34 }
35
36 }
37
38 /*
39 /**********************************************************
40 /* Test methods
41 /**********************************************************
42 */
43
44 public void testStreamingBinary() throws Exception
45 {
46 _testStreamingBinary(true);
47 _testStreamingBinary(false);
48 }
49
50 public void testBinaryWithoutLength() throws Exception
51 {
52 final SmileFactory f = new SmileFactory();
53 JsonGenerator jg = f.createGenerator(new ByteArrayOutputStream());
54 try {
55 jg.writeBinary(new ByteArrayInputStream(new byte[1]), -1);
56 fail("Should have failed");
57 } catch (UnsupportedOperationException e) {
58 verifyException(e, "must pass actual length");
59 }
60 jg.close();
61 }
62
63 /*
64 /**********************************************************
65 /* Helper methods
66 /**********************************************************
67 */
68
69 private final static String TEXT = "Some content so that we can test encoding of base64 data; must"
70 +" be long enough include a line wrap or two...";
71 private final static String TEXT4 = TEXT + TEXT + TEXT + TEXT;
72
73 private void _testStreamingBinary(boolean rawBinary) throws Exception
74 {
75 final SmileFactory f = new SmileFactory();
76 f.configure(SmileGenerator.Feature.ENCODE_BINARY_AS_7BIT, !rawBinary);
77
78 final byte[] INPUT = TEXT4.getBytes("UTF-8");
79 for (int chunkSize : new int[] { 1, 2, 3, 4, 7, 11, 29, 5000 }) {
80 JsonGenerator jgen;
81
82 final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
83 jgen = f.createGenerator(bytes);
84 jgen.writeStartArray();
85 InputStream data = new ThrottledInputStream(INPUT, chunkSize);
86 jgen.writeBinary(data, INPUT.length);
87 jgen.writeEndArray();
88 jgen.close();
89
90 JsonParser jp = f.createParser(bytes.toByteArray());
91 assertToken(JsonToken.START_ARRAY, jp.nextToken());
92 assertToken(JsonToken.VALUE_EMBEDDED_OBJECT, jp.nextToken());
93 byte[] b = jp.getBinaryValue();
94 Assert.assertArrayEquals(INPUT, b);
95 assertToken(JsonToken.END_ARRAY, jp.nextToken());
96 jp.close();
97 data.close();
98 }
99 }
100 }