1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.encoder;
15
16 import java.io.ByteArrayOutputStream;
17 import java.io.IOException;
18 import java.io.ObjectOutputStream;
19 import java.io.OutputStream;
20 import java.util.ArrayList;
21 import java.util.List;
22
23 import ch.qos.logback.core.CoreConstants;
24
25
26
27
28
29
30
31
32 public class ObjectStreamEncoder<E> extends EncoderBase<E> {
33
34 static public int START_PEBBLE = 1853421169;
35
36
37 static public int STOP_PEBBLE = 640373619;
38
39 private int MAX_BUFFER_SIZE = 100;
40
41 List<E> bufferList = new ArrayList<E>(MAX_BUFFER_SIZE);
42
43 public void doEncode(E event) throws IOException {
44 bufferList.add(event);
45 if (bufferList.size() == MAX_BUFFER_SIZE) {
46 writeBuffer();
47 }
48 }
49
50 void writeHeader(ByteArrayOutputStream baos, int bufferSize) {
51 ByteArrayUtil.writeInt(baos, START_PEBBLE);
52 ByteArrayUtil.writeInt(baos, bufferSize);
53 ByteArrayUtil.writeInt(baos, 0);
54 ByteArrayUtil.writeInt(baos, START_PEBBLE^bufferSize);
55 }
56
57 void writeFooter(ByteArrayOutputStream baos, int bufferSize) {
58 ByteArrayUtil.writeInt(baos, STOP_PEBBLE);
59 ByteArrayUtil.writeInt(baos, STOP_PEBBLE ^ bufferSize);
60 }
61 void writeBuffer() throws IOException {
62 ByteArrayOutputStream baos = new ByteArrayOutputStream(10000);
63
64 int size = bufferList.size();
65 writeHeader(baos, size);
66 ObjectOutputStream oos = new ObjectOutputStream(baos);
67 for (E e : bufferList) {
68 oos.writeObject(e);
69 }
70 bufferList.clear();
71 oos.flush();
72
73 writeFooter(baos, size);
74
75 byte[] byteArray = baos.toByteArray();
76 oos.close();
77 writeEndPosition(byteArray);
78 outputStream.write(byteArray);
79
80 }
81
82 void writeEndPosition(byte[] byteArray) {
83 int offset = 2*CoreConstants.BYTES_PER_INT;
84 ByteArrayUtil.writeInt(byteArray,offset, byteArray.length-offset);
85 }
86
87 @Override
88 public void init(OutputStream os) throws IOException {
89 super.init(os);
90 bufferList.clear();
91 }
92
93 public void close() throws IOException {
94 writeBuffer();
95 }
96 }