1 /*
2 * Copyright (c) 2012 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.eclipse.jetty.spdy.parser;
18
19 import java.nio.ByteBuffer;
20
21 import org.eclipse.jetty.spdy.frames.PingFrame;
22
23 public class PingBodyParser extends ControlFrameBodyParser
24 {
25 private final ControlFrameParser controlFrameParser;
26 private State state = State.PING_ID;
27 private int cursor;
28 private int pingId;
29
30 public PingBodyParser(ControlFrameParser controlFrameParser)
31 {
32 this.controlFrameParser = controlFrameParser;
33 }
34
35 @Override
36 public boolean parse(ByteBuffer buffer)
37 {
38 while (buffer.hasRemaining())
39 {
40 switch (state)
41 {
42 case PING_ID:
43 {
44 if (buffer.remaining() >= 4)
45 {
46 pingId = buffer.getInt() & 0x7F_FF_FF_FF;
47 onPing();
48 return true;
49 }
50 else
51 {
52 state = State.PING_ID_BYTES;
53 cursor = 4;
54 }
55 break;
56 }
57 case PING_ID_BYTES:
58 {
59 byte currByte = buffer.get();
60 --cursor;
61 pingId += (currByte & 0xFF) << 8 * cursor;
62 if (cursor == 0)
63 {
64 onPing();
65 return true;
66 }
67 break;
68 }
69 default:
70 {
71 throw new IllegalStateException();
72 }
73 }
74 }
75 return false;
76 }
77
78 private void onPing()
79 {
80 PingFrame frame = new PingFrame(controlFrameParser.getVersion(), pingId);
81 controlFrameParser.onControlFrame(frame);
82 reset();
83 }
84
85 private void reset()
86 {
87 state = State.PING_ID;
88 cursor = 0;
89 pingId = 0;
90 }
91
92 private enum State
93 {
94 PING_ID, PING_ID_BYTES
95 }
96 }