View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 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<byte[]> 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 copyChunk(byte buf[], int offset, int length)
40      {
41          if (this.length + length > maxSize)
42          {
43              throw new MessageTooLargeException("Frame is too large");
44          }
45  
46          byte copy[] = new byte[length - offset];
47          System.arraycopy(buf,offset,copy,0,length);
48  
49          chunks.add(copy);
50          this.length += length;
51      }
52      
53      public int getLength()
54      {
55          return length;
56      }
57  
58      public void transferTo(ByteBuffer buffer)
59      {
60          if (buffer.remaining() < length)
61          {
62              throw new IllegalArgumentException(String.format("Not enough space in ByteBuffer remaining [%d] for accumulated buffers length [%d]",
63                      buffer.remaining(),length));
64          }
65  
66          int position = buffer.position();
67          for (byte[] chunk : chunks)
68          {
69              buffer.put(chunk,0,chunk.length);
70          }
71          BufferUtil.flipToFlush(buffer,position);
72      }
73  }