View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2014 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.util.BufferUtil;
26  import org.eclipse.jetty.websocket.api.MessageTooLargeException;
27  
28  public class ByteAccumulator
29  {
30      private final List<Chunk> chunks = new ArrayList<>();
31      private final int maxSize;
32      private int length = 0;
33  
34      public ByteAccumulator(int maxOverallBufferSize)
35      {
36          this.maxSize = maxOverallBufferSize;
37      }
38  
39      public void addChunk(byte buf[], int offset, int length)
40      {
41          if (this.length + length > maxSize)
42          {
43              throw new MessageTooLargeException("Frame is too large");
44          }
45          chunks.add(new Chunk(buf, offset, length));
46          this.length += length;
47      }
48  
49      public int getLength()
50      {
51          return length;
52      }
53  
54      public void transferTo(ByteBuffer buffer)
55      {
56          if (buffer.remaining() < length)
57              throw new IllegalArgumentException();
58          int position = buffer.position();
59          for (Chunk chunk : chunks)
60          {
61              buffer.put(chunk.buffer, chunk.offset, chunk.length);
62          }
63          BufferUtil.flipToFlush(buffer, position);
64      }
65  
66      private static class Chunk
67      {
68          private final byte[] buffer;
69          private final int offset;
70          private final int length;
71  
72          private Chunk(byte[] buffer, int offset, int length)
73          {
74              this.buffer = buffer;
75              this.offset = offset;
76              this.length = length;
77          }
78      }
79  }