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.message;
20  
21  import java.io.ByteArrayOutputStream;
22  import java.io.IOException;
23  import java.nio.ByteBuffer;
24  
25  import org.eclipse.jetty.util.BufferUtil;
26  import org.eclipse.jetty.websocket.common.events.EventDriver;
27  
28  public class SimpleBinaryMessage implements MessageAppender
29  {
30      private static final int BUFFER_SIZE = 65535;
31      private final EventDriver onEvent;
32      private final ByteArrayOutputStream out;
33      private int size;
34      private boolean finished;
35  
36      public SimpleBinaryMessage(EventDriver onEvent)
37      {
38          this.onEvent = onEvent;
39          this.out = new ByteArrayOutputStream(BUFFER_SIZE);
40          finished = false;
41      }
42  
43      @Override
44      public void appendMessage(ByteBuffer payload) throws IOException
45      {
46          if (finished)
47          {
48              throw new IOException("Cannot append to finished buffer");
49          }
50  
51          if (payload == null)
52          {
53              // empty payload is valid
54              return;
55          }
56  
57          onEvent.getPolicy().assertValidMessageSize(size + payload.remaining());
58          size += payload.remaining();
59  
60          BufferUtil.writeTo(payload,out);
61      }
62  
63      @Override
64      public void messageComplete()
65      {
66          finished = true;
67          byte data[] = out.toByteArray();
68          onEvent.onBinaryMessage(data);
69      }
70  }