summaryrefslogtreecommitdiffstats
path: root/base/util/src/com/netscape/cmsutil/http/HttpMessage.java
blob: 8db6fc11b9c4684a904ddddeca53395022171f78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 * Basic HTTP Message, excluding message body.
 * Not optimized for performance.
 * Set fields or parse from input.
 */
public class HttpMessage {
    protected String mLine = null; // request or response line.
    protected Hashtable<String, String> mHeaders = null;
    protected String mContent = null; // arbitrary content chars assumed.

    /**
     * Instantiate a HttpResponse for write to http client.
     */
    public HttpMessage() {
        mHeaders = new Hashtable<String, String>();
    }

    /**
     * Set a header field. <br>
     * Content-length is automatically set on write.<br>
     * If value spans multiple lines must be in proper http format for
     * multiple lines.
     */
    public void setHeader(String name, String value) {
        if (mHeaders == null)
            mHeaders = new Hashtable<String, String>();
        mHeaders.put(name.toLowerCase(), value);
    }

    /**
     * get a header
     */
    public String getHeader(String name) {
        return mHeaders.get(name.toLowerCase());
    }

    /**
     * write http headers
     * does not support values of more than one line
     */
    public void writeHeaders(OutputStreamWriter writer)
            throws IOException {
        if (mHeaders != null) {
            Enumeration<String> keys = mHeaders.keys();
            String header, value;

            while (keys.hasMoreElements()) {
                header = keys.nextElement();
                value = mHeaders.get(header);
                writer.write(header + ":" + value + Http.CRLF);
            }
        }
        writer.write(Http.CRLF); // end with CRLF line.
    }

    /**
     * read http headers.
     * does not support values of more than one line or multivalue headers.
     */
    public void readHeaders(BufferedReader reader)
            throws IOException {
        mHeaders = new Hashtable<String, String>();

        int colon;
        String line, key, value;

        while (true) {
            line = reader.readLine();
            if (line == null || line.equals(""))
                break;
            colon = line.indexOf(':');
            if (colon == -1) {
                mHeaders = null;
                throw new HttpProtocolException("Bad Http header format");
            }
            key = line.substring(0, colon);
            value = line.substring(colon + 1);
            mHeaders.put(key.toLowerCase(), value.trim());
        }
    }

    public void write(OutputStreamWriter writer)
            throws IOException {
        writer.write(mLine + Http.CRLF);
        writeHeaders(writer);
        writer.flush();
        if (mContent != null) {
            writer.write(mContent);
        }
        writer.flush();
    }

    public void parse(BufferedReader reader)
            throws IOException {
        String line = reader.readLine();

        if (line == null) {
            throw new HttpEofException("End of stream reached");
        }
        if (line.equals("")) {
            throw new HttpProtocolException("Bad Http req/resp line " + line);
        }
        mLine = line;
        readHeaders(reader);

        // won't work if content length is not set.
        String lenstr = mHeaders.get("content-length");

        if (lenstr != null) {
            int len = Integer.parseInt(lenstr);
            char[] cbuf = new char[len];
            int done = reader.read(cbuf, 0, cbuf.length);
            int total = done;

            while (done >= 0 && total < len) {
                done = reader.read(cbuf, total, len - total);
                total += done;
            }

            mContent = new String(cbuf);
        } else {
            char[] cbuf = new char[8192];
            StringWriter sw = new StringWriter();
            int charsRead;
            while ((charsRead = reader.read(cbuf)) != -1) {
                sw.write(cbuf, 0, charsRead);
            }
            if (sw.getBuffer().length()>0) mContent = sw.toString();
        }
    }

    public void reset() {
        mLine = null;
        mHeaders = null;
        mContent = null;
    }

    public void setContent(String content) {
        mContent = content;
    }

    public String getContent() {
        return mContent;
    }

}