KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > util > ProxiedHttpMethod


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.util;
21
22 import java.io.BufferedInputStream JavaDoc;
23 import java.io.ByteArrayInputStream JavaDoc;
24 import java.io.ByteArrayOutputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import java.util.Enumeration JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.StringTokenizer JavaDoc;
32 import java.util.Vector JavaDoc;
33
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.mortbay.util.MultiMap;
37
38 import com.maverick.http.HttpConnection;
39 import com.maverick.http.HttpMethod;
40 import com.maverick.http.HttpRequest;
41 import com.maverick.http.HttpResponse;
42 import com.maverick.util.URLUTF8Encoder;
43 import com.sslexplorer.boot.Util;
44 import com.sslexplorer.policyframework.LaunchSession;
45 import com.sslexplorer.security.SessionInfo;
46
47 public class ProxiedHttpMethod extends HttpMethod {
48
49     private BufferedInputStream JavaDoc content;
50     private long contentLength = 0;
51     private HttpRequest proxiedHeaders = new HttpRequest();
52     private ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc();
53     private String JavaDoc charsetEncoding = null;
54     private boolean wwwURLEncodedParameters;
55     private int bufferSize = 0;
56     private MultiMap uriParameters;
57     private boolean sendOriginalURI = false;
58     
59     static Log log = LogFactory.getLog(ProxiedHttpMethod.class);
60     /**
61      * @param name
62      * @param uri
63      * @param parameters
64      * @param session
65      * @param i
66      * @param string
67      * @param multiPartForm
68      */

69     public ProxiedHttpMethod(String JavaDoc name, String JavaDoc path, MultiMap parameters, SessionInfo session, boolean wwwURLEncodedParameters) { // ,
70

71         super(name, path);
72         
73         this.wwwURLEncodedParameters = wwwURLEncodedParameters;
74         String JavaDoc key;
75         Object JavaDoc val;
76         
77         uriParameters = getURIParameters();
78         
79 // Make sure the launch ID parameter is not passed on
80
uriParameters.remove(LaunchSession.LONG_LAUNCH_ID);
81         parameters.remove(LaunchSession.LONG_LAUNCH_ID);
82         
83         for(Iterator JavaDoc it = parameters.keySet().iterator();it.hasNext();) {
84
85             key = (String JavaDoc) it.next();
86
87             List JavaDoc values = parameters.getValues(key);
88             List JavaDoc uriValues = uriParameters.getValues(key);
89             
90             for(Iterator JavaDoc it2 = values.iterator(); it2.hasNext();) {
91                 
92                 val = (String JavaDoc) it2.next();
93     
94                 if(val instanceof String JavaDoc) {
95                     if(uriValues!=null && uriValues.contains(val))
96                         continue;
97                     addParameter(key, (String JavaDoc)val);
98                 } else if(val instanceof List JavaDoc) {
99                     // Multiple parameter values.
100
List JavaDoc l = (List JavaDoc)val;
101                     for(Iterator JavaDoc it3 = l.iterator(); it3.hasNext();) {
102                         String JavaDoc tmp = (String JavaDoc) it3.next();
103                         if(uriValues!=null && uriValues.contains(tmp))
104                             continue;
105                         addParameter(key, tmp);
106                     }
107                 }
108                 else if(uriValues!=null && val instanceof String JavaDoc[]) {
109                     String JavaDoc[] tmp = (String JavaDoc[]) val;
110                     for(int i=0;i<tmp.length;i++) {
111                         if(uriValues.contains(tmp[i]))
112                             continue;
113                         addParameter(key, tmp[i]);
114                     }
115                 }
116             }
117         }
118     }
119     
120     public void setCharsetEncoding(String JavaDoc charsetEncoding) {
121         this.charsetEncoding = charsetEncoding;
122     }
123
124     public OutputStream JavaDoc getOutputStream() {
125         return out;
126     }
127
128     public void setContent(InputStream JavaDoc content, long contentLength, String JavaDoc contentType) {
129         this.content = new BufferedInputStream JavaDoc(content, bufferSize == 0 ? (int)contentLength : bufferSize);
130         this.contentLength = contentLength;
131         if(contentType!=null)
132             proxiedHeaders.setHeaderField("Content-Type", contentType);
133         proxiedHeaders.setHeaderField("Content-Length", String.valueOf(contentLength));
134     }
135     
136     public void setContentType(String JavaDoc contentType) {
137         if(contentType!=null)
138             proxiedHeaders.setHeaderField("Content-Type", contentType);
139     }
140
141     public void setContent(InputStream JavaDoc content, long contentLength) {
142         setContent(content, contentLength, null);
143     }
144
145     public HttpRequest getProxiedRequest() {
146         return proxiedHeaders;
147     }
148
149     public HttpResponse execute(HttpRequest request, HttpConnection connection) throws IOException JavaDoc {
150
151         String JavaDoc encodedContent = "";
152         /**
153          * Encode parameters into content if application/x-www-form-urlencoded
154          */

155         if (wwwURLEncodedParameters) {
156             String JavaDoc key;
157             String JavaDoc value;
158             Vector JavaDoc v;
159             for (Enumeration JavaDoc e = getParameterNames(); e.hasMoreElements(); ) {
160
161                 key = (String JavaDoc) e.nextElement();
162                 v = getParameterValueList(key);
163
164                 for (Iterator JavaDoc it2 = v.iterator(); it2.hasNext();) {
165                     value = (String JavaDoc) it2.next();
166                     encodedContent += (encodedContent.length() > 0 ? "&" : "") + Util.urlEncode(key, (charsetEncoding==null ? System.getProperty("sslexplorer.urlencoding", "UTF-8") : charsetEncoding)) + "="
167                     + Util.urlEncode(value, (charsetEncoding==null ? System.getProperty("sslexplorer.urlencoding", "UTF-8") : charsetEncoding));
168                 }
169             }
170
171             if(charsetEncoding==null) {
172                 ByteArrayInputStream JavaDoc in = new ByteArrayInputStream JavaDoc(encodedContent.getBytes());
173                 setContent(in, in.available(), "application/x-www-form-urlencoded");
174             } else {
175                 ByteArrayInputStream JavaDoc in = new ByteArrayInputStream JavaDoc(encodedContent.getBytes(charsetEncoding));
176                 setContent(in, in.available(), "application/x-www-form-urlencoded");
177             }
178         }
179
180         // Setup all the proxied headers
181
for (Enumeration JavaDoc e = proxiedHeaders.getHeaderFieldNames(); e.hasMoreElements();) {
182             String JavaDoc header = (String JavaDoc) e.nextElement();
183             if (header.equalsIgnoreCase("Authorization"))
184                 if (request.getHeaderField("Authorization") != null)
185                     continue;
186             String JavaDoc[] values = proxiedHeaders.getHeaderFields(header);
187             for (int i = 0; i < values.length; i++) {
188                 request.addHeaderField(header, values[i]);
189             }
190         }
191
192         request.performRequest(this, connection);
193         
194         // If the request is multipart/form-data then copy the streams now
195
if (content != null) {
196             
197             if(log.isDebugEnabled())
198                 log.debug("Sending " + contentLength + " bytes of content");
199             
200             content.mark(bufferSize);
201             
202             try {
203                 int read;
204                 byte[] buf = new byte[4096];
205                 long total = 0;
206                 
207                 do {
208                     read = content.read(buf, 0, (int) Math.min(buf.length, contentLength - total));
209                     
210                     if(log.isDebugEnabled())
211                         log.debug("Sent " + read + " bytes of content");
212                     if(read > -1) {
213                         total += read;
214                         connection.getOutputStream().write(buf, 0, read);
215                         connection.getOutputStream().flush();
216                     }
217                 } while(read > -1 && (contentLength - total) > 0);
218             
219             } finally {
220                 content.reset();
221             }
222             
223             if(log.isDebugEnabled())
224                 log.debug("Completed sending request content");
225         }
226
227         return new HttpResponse(connection);
228     }
229     
230     public String JavaDoc getDecodedURI() {
231         return URLUTF8Encoder.decode(super.getURI());
232     }
233     
234     public String JavaDoc getDecodedURIParameters() {
235         int idx = super.getURI().indexOf('?');
236         if(idx > -1) {
237             return URLUTF8Encoder.decode(super.getURI().substring(idx+1));
238         } else {
239             return "";
240         }
241     }
242     
243     
244     public MultiMap getURIParameters() {
245         MultiMap output = new MultiMap();
246         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(getDecodedURIParameters(), "&");
247         int idx;
248         String JavaDoc name;
249         while(tokens.hasMoreTokens()) {
250             name = tokens.nextToken();
251             idx = name.indexOf('=');
252             if(idx > -1) {
253                 output.add(name.substring(0, idx), name.substring(idx+1));
254             } else {
255                 output.add(name, "");
256             }
257         }
258         return output;
259     }
260     
261     public String JavaDoc getEncodedURIParameters() {
262         String JavaDoc encodedParams = "";
263         String JavaDoc key;
264         String JavaDoc val;
265         for(Iterator JavaDoc it = uriParameters.keySet().iterator(); it.hasNext();) {
266             key = (String JavaDoc) it.next();
267                 for(Iterator JavaDoc it2 = uriParameters.getValues(key).iterator(); it2.hasNext();) {
268                     val = (String JavaDoc) it2.next();
269                     if(val.length()==0)
270                         encodedParams += (encodedParams.equals("") ? "" : "&") + URLUTF8Encoder.encode(key, true);
271                     else
272                         encodedParams += (encodedParams.equals("") ? "" : "&") + URLUTF8Encoder.encode(key, true) + "=" + URLUTF8Encoder.encode(val, true);
273                 }
274         }
275         return encodedParams;
276     }
277     
278     public String JavaDoc getDecodedURIPath() {
279         int idx = super.getURI().indexOf('?');
280         if(idx > -1) {
281             return URLUTF8Encoder.decode(super.getURI().substring(0, idx));
282         } else {
283             return URLUTF8Encoder.decode(super.getURI());
284         }
285     }
286     
287     public String JavaDoc getEncodedURIPath() {
288         return URLUTF8Encoder.encode(getDecodedURIPath(), false);
289     }
290     
291     public String JavaDoc getURI() {
292
293         /**
294          * LDP - I've added this option because sometimes clients/servers send
295          * bad URIs that do not conform to the specification (Outlook RPC/IIS for example). This
296          * allows us to bypass the encoding and simply send the URI as it was received.
297          */

298         if(sendOriginalURI)
299             return super.getURI();
300         
301         /**
302          * LDP - Jetty decodes POST application/x-www-form-urlencoded parameters so we don't add them
303          * onto the URI. If we have parameters and the method IS NOT POST and content type IS NOT
304          * application/x-www-form-urlencoded then add them to the URI as its the only place they
305          * could have come from.
306          */

307         String JavaDoc uri = getEncodedURIPath();
308         String JavaDoc params = getEncodedURIParameters();
309         
310         if(!params.equals(""))
311             uri += "?" + params;
312
313         return uri;
314     }
315
316     public void setContentBufferSize(int bufferSize) {
317         this.bufferSize = bufferSize;
318     }
319
320     public void setSendOriginalURI(boolean sendOriginalURI) {
321         this.sendOriginalURI = sendOriginalURI;
322     }
323 }
324
Popular Tags