01: /*
02: * <copyright>
03: *
04: * Copyright 1997-2007 BBNT Solutions, LLC
05: * under sponsorship of the Defense Advanced Research Projects
06: * Agency (DARPA).
07: *
08: * You can redistribute this software and/or modify it under the
09: * terms of the Cougaar Open Source License as published on the
10: * Cougaar Open Source Website (www.cougaar.org).
11: *
12: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
13: * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
14: * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
15: * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
16: * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
17: * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
18: * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
22: * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23: *
24: * </copyright>
25: */
26:
27: package org.cougaar.lib.web.micro.base;
28:
29: import java.io.InputStream;
30: import java.io.IOException;
31: import java.util.ArrayList;
32: import java.util.List;
33:
34: /**
35: * A standard request callback implementation that reads from an
36: * {@link InputStream}.
37: */
38: public class RequestCallbackImpl implements RequestCallback {
39:
40: private final InputStream is;
41:
42: public RequestCallbackImpl(InputStream is) {
43: this .is = is;
44: }
45:
46: public String readRequest() throws IOException {
47: return readLine();
48: }
49:
50: public List readHeaders() throws IOException {
51: List ret = new ArrayList();
52: while (true) {
53: String s = readLine();
54: if (s == null)
55: break;
56: if (s.length() == 0)
57: break;
58: ret.add(s);
59: }
60: return ret;
61: }
62:
63: public byte[] readBody(int contentLength) throws IOException {
64: int n = (contentLength > 0 ? contentLength : 0);
65: byte[] body = new byte[n];
66: for (int offset = 0; offset < n;) {
67: int count = is.read(body, offset, (n - offset));
68: if (count < 0)
69: break;
70: offset += count;
71: }
72: return body;
73: }
74:
75: private String readLine() throws IOException {
76: StringBuffer buf = new StringBuffer();
77: while (true) {
78: int b = is.read();
79: if (b < 0)
80: break;
81: if (b == '\r')
82: b = is.read();
83: if (b == '\n')
84: break;
85: buf.append((char) b);
86: }
87: return buf.toString().trim();
88: }
89: }
|