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.message;
20  
21  import java.io.IOException;
22  import java.nio.ByteBuffer;
23  
24  import org.eclipse.jetty.util.Utf8StringBuilder;
25  import org.eclipse.jetty.websocket.common.events.EventDriver;
26  
27  public class SimpleTextMessage implements MessageAppender
28  {
29      private final EventDriver onEvent;
30      protected final Utf8StringBuilder utf;
31      private int size = 0;
32      protected boolean finished;
33  
34      public SimpleTextMessage(EventDriver onEvent)
35      {
36          this.onEvent = onEvent;
37          this.utf = new Utf8StringBuilder(1024);
38          size = 0;
39          finished = false;
40      }
41  
42      @Override
43      public void appendFrame(ByteBuffer payload, boolean isLast) throws IOException
44      {
45          if (finished)
46          {
47              throw new IOException("Cannot append to finished buffer");
48          }
49  
50          if (payload == null)
51          {
52              // empty payload is valid
53              return;
54          }
55  
56          onEvent.getPolicy().assertValidTextMessageSize(size + payload.remaining());
57          size += payload.remaining();
58  
59          // allow for fast fail of BAD utf (incomplete utf will trigger on messageComplete)
60          this.utf.append(payload);
61      }
62  
63      @Override
64      public void messageComplete()
65      {
66          finished = true;
67  
68          // notify event
69          onEvent.onTextMessage(utf.toString());
70      }
71  }