File: CGI.java

package info (click to toggle)
skyview 3.4.2%2Brepack-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,176 kB
  • sloc: java: 29,396; makefile: 18; sh: 1
file content (244 lines) | stat: -rw-r--r-- 5,860 bytes parent folder | download | duplicates (4)
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package net.ivoa.util;

import java.util.HashMap;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import static java.net.URLDecoder.decode;


/** Simple utility for parsing CGI parameters */
public class CGI {
    
    
    private HashMap<String, String[]> params = new HashMap<String, String[]>();
    public CGI() {
	parseParams();
    }
    
    public CGI(String input) {
	if (input != null && (input.indexOf('=') < 0 && input.indexOf('%') >= 0 )) {
	    // Decode the input string...
	    try {
	        input = java.net.URLDecoder.decode(input, "UTF-8");
	    } catch (Exception e) {
		System.err.println("Decoding error?? "+e);
	    }
	}
	parseString(input);
    }
    
    public  HashMap<String, String[]> getParams() {
	return params;
    }
    
    protected void parseParams() {
	
	String type = System.getenv("REQUEST_METHOD");
	if (type != null) {
	    type = type.toUpperCase();
	}
	
	if (type == null) {
	    if (System.getenv("QUERY_STRING") != null) {
		type = "GET";
	    } else {
		type = "POST";
	    }
	} else {
	    type = type.toUpperCase();
	}
	String queryString = null;
	if (type.equals("GET")) {
	    queryString = System.getenv("QUERY_STRING");
	} else {
	    String enc = System.getenv("CONTENT_TYPE");
	    if (enc != null && enc.startsWith("multipart/form")) {
		parseMultipartForm(enc);
		return;
	    } else {
	        try {
	            BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	            queryString = bf.readLine();
	        } catch (IOException e) {
		    System.err.println("Unable to read standard input on POST");
	        }
	    }
	}
	parseString(queryString);
    }
    
    protected void parseString(String queryString) {
	if (queryString != null) {
	    String[] fields = queryString.split("\\&");
	    for (String field: fields) {
		decodeField(field);
	    }
	}
    }
    
    protected String getField(String key, String line) {
	String[] fields = line.split(";");
	for(String field: fields) {
	    field = field.trim();
	    if (field.startsWith(key+"=")) {
		String value = field.substring(key.length()+1);
		if (value.length() > 2) {
		    if (value.charAt(0) == '"'  &&
			value.charAt(value.length()-1) == '"') {
			value = value.substring(1, value.length()-1);
		    }
		}
		return value;
	    }
	}
	return null;
    }
	
    
    private interface LineReader {
	public LineReader processLine(String line);
    }
    
    private class FieldWaiter implements LineReader {
	public LineReader processLine(String line) {
	    if (line.toLowerCase().startsWith("content-disposition")) {
		fieldName = getField("name", line);
		fieldFile = getField("filename", line);
		return new BlankWaiter();
	    } else {
		return this;
	    }
	}
    }
    private class BlankWaiter implements LineReader {
	public LineReader processLine(String line) {
	    if (line.length() == 0) {
		fieldBuffer = new StringBuffer();
		return new DataReader();
	    } else {
		return this;
	    }
	}
    }
    
    private class DataReader implements LineReader {
	public LineReader processLine(String line) {
	    
	    if (line.equals(dataBoundary)) {
		addField();
		return new FieldWaiter();
		
	    } else if (line.length() == dataBoundary.length() + 2   &&
		       line.equals(dataBoundary+"--")) {
		
		// Should be all done but just in case we return a FieldWaiter
		addField();
		return new FieldWaiter();
		
	    } else {
		fieldBuffer.append(line);
		fieldBuffer.append('\n');
		return this;
	    }
	}
    }
	
    private StringBuffer fieldBuffer;
    private String dataBoundary;
	    
    private String fieldName;
    private String fieldFile;
	    
    protected void parseMultipartForm(String type) {
	
	
	LineReader lr = new FieldWaiter();
	
	dataBoundary = "--"+getField("boundary", type);
	String lastLine = null;
	
	try {  
	    BufferedReader br = new BufferedReader(
			      new InputStreamReader(System.in));
	    String line;
	
	    while ( (line=br.readLine()) != null) {
		char ch = 0;
		if (line.length() > 0) {
		    ch = line.charAt(line.length()-1);
		}
		int chr = ch;
	        
		lr = lr.processLine(line);
		lastLine = line;
	    }
	} catch (IOException e) {
	    System.err.println("Error reading standard input:"+e);
	}
	if (! (lr instanceof FieldWaiter) ) { 
	    throw new Error("Invalid state at termination of multipart form parse");
	}
    }
    
    protected void addField() {
	
	// Get rid of extra newline after normal fields.
	if (fieldFile == null && fieldBuffer.length() > 0) {
	    fieldBuffer.setLength(fieldBuffer.length()-1);
	}
	addField(fieldName, fieldBuffer.toString());
    }
    
    protected void decodeField(String field) {
	
	String[] elems = field.split("=", 2);
        try {
	    if (elems.length == 2) {
	        String key = decode(elems[0], "UTF-8");
	        String val = decode(elems[1], "UTF-8");
	        addField(key, val);
	    }
        } catch (Exception e) {	       
	    // This should be an unsupported encoding exception!
 	    throw new Error("Unexpected error:"+e);
        }
    }
    
    protected void addField(String key, String val) {
	if (params.containsKey(key)) {
	    String[] old = params.get(key);
	    String[] nw  = new String[old.length+1];
	    System.arraycopy(old, 0, nw, 0, old.length);
	    nw[old.length] = val;
	    params.put(key, nw);
	} else {
	    params.put(key, new String[]{val});
	}
    }
    
    public String value(String key) {
	if (params.containsKey(key)) {
	    return params.get(key)[0];
	} else {
	    return null;
	}
    }
    
    public String[] values(String key) {
	return params.get(key);
    }
    
    public int count(String key) {
	if (params.containsKey(key)) {
	    return params.get(key).length;
	} else {
	    return 0;
	}
    }
    
    public String[] keys() {
	return params.keySet().toArray(new String[0]);
    }

}