1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.fcgi.parser;
20
21 import java.nio.ByteBuffer;
22
23 import org.eclipse.jetty.fcgi.FCGI;
24 import org.eclipse.jetty.util.log.Log;
25 import org.eclipse.jetty.util.log.Logger;
26
27 public class StreamContentParser extends ContentParser
28 {
29 protected static final Logger logger = Log.getLogger(StreamContentParser.class);
30
31 private final FCGI.StreamType streamType;
32 private final Parser.Listener listener;
33 private State state = State.LENGTH;
34 private int contentLength;
35
36 public StreamContentParser(HeaderParser headerParser, FCGI.StreamType streamType, Parser.Listener listener)
37 {
38 super(headerParser);
39 this.streamType = streamType;
40 this.listener = listener;
41 }
42
43 @Override
44 public boolean parse(ByteBuffer buffer)
45 {
46 while (buffer.hasRemaining())
47 {
48 switch (state)
49 {
50 case LENGTH:
51 {
52 contentLength = getContentLength();
53 state = State.CONTENT;
54 break;
55 }
56 case CONTENT:
57 {
58 int length = Math.min(contentLength, buffer.remaining());
59 int limit = buffer.limit();
60 buffer.limit(buffer.position() + length);
61 ByteBuffer slice = buffer.slice();
62 onContent(slice);
63 buffer.position(buffer.limit());
64 buffer.limit(limit);
65 contentLength -= length;
66 if (contentLength > 0)
67 break;
68 state = State.LENGTH;
69 return true;
70 }
71 default:
72 {
73 throw new IllegalStateException();
74 }
75 }
76 }
77 return false;
78 }
79
80 @Override
81 public void noContent()
82 {
83 try
84 {
85 listener.onEnd(getRequest());
86 }
87 catch (Throwable x)
88 {
89 logger.debug("Exception while invoking listener " + listener, x);
90 }
91 }
92
93 protected void onContent(ByteBuffer buffer)
94 {
95 try
96 {
97 listener.onContent(getRequest(), streamType, buffer);
98 }
99 catch (Throwable x)
100 {
101 logger.debug("Exception while invoking listener " + listener, x);
102 }
103 }
104
105 protected void end(int request)
106 {
107 }
108
109 private enum State
110 {
111 LENGTH, CONTENT
112 }
113 }