View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.websocket.common.extensions.compress;
20  
21  import java.nio.ByteBuffer;
22  import java.util.ArrayList;
23  import java.util.List;
24  
25  import org.eclipse.jetty.io.ByteBufferPool;
26  import org.eclipse.jetty.util.BufferUtil;
27  import org.eclipse.jetty.websocket.api.MessageTooLargeException;
28  
29  public class ByteAccumulator
30  {
31      private static class Buf
32      {
33          public Buf(byte[] buffer, int offset, int length)
34          {
35              this.buffer = buffer;
36              this.offset = offset;
37              this.length = length;
38          }
39  
40          byte[] buffer;
41          int offset;
42          int length;
43      }
44  
45      private final int maxSize;
46      private int length = 0;
47      private List<Buf> buffers;
48  
49      public ByteAccumulator(int maxOverallBufferSize)
50      {
51          this.maxSize = maxOverallBufferSize;
52          this.buffers = new ArrayList<>();
53      }
54  
55      public void addBuffer(byte buf[], int offset, int length)
56      {
57          if (this.length + length > maxSize)
58          {
59              throw new MessageTooLargeException("Frame is too large");
60          }
61          buffers.add(new Buf(buf,offset,length));
62          this.length += length;
63      }
64  
65      public int getLength()
66      {
67          return length;
68      }
69  
70      public ByteBuffer getByteBuffer(ByteBufferPool pool)
71      {
72          ByteBuffer ret = pool.acquire(length,false);
73          BufferUtil.clearToFill(ret);
74  
75          for (Buf buf : buffers)
76          {
77              ret.put(buf.buffer, buf.offset, buf.length);
78          }
79  
80          BufferUtil.flipToFlush(ret,0);
81          return ret;
82      }
83  }