View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
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   * Write out events as java objects.
27   * 
28   * @author Ceki Gülcü
29   *
30   * @param <E>
31   */
32  public class ObjectStreamEncoder<E> extends EncoderBase<E> {
33  
34    static public int START_PEBBLE = 1853421169;
35    //static public int START_PEBBLE = 1;
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  }