KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > protocol > http > proxy > HttpRequestHdr


1 // $Header: /home/cvs/jakarta-jmeter/src/protocol/http/org/apache/jmeter/protocol/http/proxy/HttpRequestHdr.java,v 1.23.2.2 2004/05/20 15:23:12 mstover1 Exp $
2
/*
3  * Copyright 2001-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17 */

18
19 package org.apache.jmeter.protocol.http.proxy;
20
21 import java.io.ByteArrayOutputStream JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.net.MalformedURLException JavaDoc;
25 import java.net.ProtocolException JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.Map JavaDoc;
29 import java.util.StringTokenizer JavaDoc;
30
31 import junit.framework.TestCase;
32
33 import org.apache.jmeter.protocol.http.config.MultipartUrlConfig;
34 import org.apache.jmeter.protocol.http.control.Header;
35 import org.apache.jmeter.protocol.http.control.HeaderManager;
36 import org.apache.jmeter.protocol.http.control.gui.HttpTestSampleGui;
37 import org.apache.jmeter.protocol.http.gui.HeaderPanel;
38 import org.apache.jmeter.protocol.http.sampler.HTTPSampler;
39 import org.apache.jmeter.testelement.TestElement;
40 import org.apache.jmeter.util.JMeterUtils;
41 import org.apache.jorphan.logging.LoggingManager;
42 import org.apache.log.Logger;
43
44 /**
45  * The headers of the client HTTP request.
46  *
47  * @version $Revision: 1.23.2.2 $
48  */

49 public class HttpRequestHdr
50 {
51     private static final Logger log = LoggingManager.getLoggerForClass();
52
53     /**
54      * Http Request method. Such as get or post.
55      */

56     public String JavaDoc method = "";
57
58     /**
59      * The requested url. The universal resource locator that hopefully uniquely
60      * describes the object or service the client is requesting.
61      */

62     public String JavaDoc url = "";
63
64     /**
65      * Version of http being used. Such as HTTP/1.0.
66      */

67     public String JavaDoc version = "";
68
69     public String JavaDoc postData = "";
70     static String JavaDoc CR = "\r\n";
71     private Map JavaDoc headers = new HashMap JavaDoc();
72
73     /*
74      * Optionally number the requests
75      */

76     private static boolean numberRequests
77         = JMeterUtils.getPropDefault("proxy.number.requests",false);
78     private static int requestNumber = 0 ;// running number
79

80     /**
81      * Parses a http header from a stream.
82      *
83      * @param in the stream to parse.
84      * @return array of bytes from client.
85      */

86     public byte[] parse(InputStream JavaDoc in) throws IOException JavaDoc
87     {
88         boolean inHeaders = true;
89         int readLength = 0;
90         int dataLength = 0;
91         boolean first = true;
92         ByteArrayOutputStream JavaDoc clientRequest = new ByteArrayOutputStream JavaDoc();
93         ByteArrayOutputStream JavaDoc line = new ByteArrayOutputStream JavaDoc();
94         int x;
95         while ((inHeaders || readLength < dataLength)
96             && ((x = in.read()) != -1))
97         {
98             line.write(x);
99             clientRequest.write(x);
100             if (inHeaders && (byte) x == (byte) '\n')
101             {
102                 if (line.size() < 3)
103                 {
104                     inHeaders = false;
105                 }
106                 if (first)
107                 {
108                     parseFirstLine(line.toString());
109                     first = false;
110                 }
111                 else
112                 {
113                     dataLength =
114                         Math.max(parseLine(line.toString()), dataLength);
115                 }
116                 log.debug("Client Request Line: " + line.toString());
117                 line.reset();
118             }
119             else if (!inHeaders)
120             {
121                 readLength++;
122             }
123         }
124         postData = line.toString().trim();
125         log.debug("postData: " + postData);
126         log.debug("Request: "+clientRequest.toString());
127         return clientRequest.toByteArray();
128     }
129     
130     public void parseFirstLine(String JavaDoc firstLine)
131     {
132         log.debug("browser request: " + firstLine);
133         StringTokenizer JavaDoc tz = new StringTokenizer JavaDoc(firstLine);
134         method = getToken(tz).toUpperCase();
135         url = getToken(tz);
136         log.debug("parsed url: " + url);
137         version = getToken(tz);
138     }
139     
140     public int parseLine(String JavaDoc nextLine)
141     {
142         StringTokenizer JavaDoc tz;
143         tz = new StringTokenizer JavaDoc(nextLine);
144         String JavaDoc token = getToken(tz);
145         // look for termination of HTTP command
146
if (0 == token.length())
147         {
148             return 0;
149         }
150         else
151         {
152             String JavaDoc name = token.trim().substring(0, token.trim().length() - 1);
153             String JavaDoc value = getRemainder(tz);
154             headers.put(name.toLowerCase(), new Header(name, value));
155             if (name.equalsIgnoreCase("content-length"))
156             {
157                 return Integer.parseInt(value);
158             }
159         }
160         return 0;
161     }
162     
163     public HeaderManager getHeaderManager()
164     {
165         HeaderManager manager = new HeaderManager();
166         Iterator JavaDoc keys = headers.keySet().iterator();
167         while (keys.hasNext())
168         {
169             String JavaDoc key = (String JavaDoc) keys.next();
170             if (!key.equals("proxy-connection")
171                 && !key.equals("content-length"))
172             {
173                 manager.add((Header) headers.get(key));
174             }
175         }
176         manager.setName("Browser-derived headers");
177         manager.setProperty(
178             TestElement.TEST_CLASS,
179             HeaderManager.class.getName());
180         manager.setProperty(TestElement.GUI_CLASS, HeaderPanel.class.getName());
181         return manager;
182     }
183     
184     public HTTPSampler getSampler()
185         throws MalformedURLException JavaDoc, IOException JavaDoc, ProtocolException JavaDoc
186     {
187         // Damn! A whole new GUI just to instantiate a test element?
188
// Isn't there a beter way?
189
HttpTestSampleGui tempGui = new HttpTestSampleGui();
190         HTTPSampler result = createSampler();
191         tempGui.configure(result);
192         tempGui.modifyTestElement(result);
193         result.setFollowRedirects(false);
194         result.setUseKeepAlive(true);
195         return result;
196     }
197     
198     public String JavaDoc getContentType()
199     {
200         Header contentTypeHeader = (Header) headers.get("content-type");
201         if (contentTypeHeader != null)
202         {
203             return contentTypeHeader.getValue();
204         }
205         return "";
206     }
207     
208     public static MultipartUrlConfig isMultipart(String JavaDoc contentType)
209     {
210         if (contentType != null
211             && contentType.startsWith(MultipartUrlConfig.MULTIPART_FORM))
212         {
213             return new MultipartUrlConfig(
214                 contentType.substring(contentType.indexOf("oundary=") + 8));
215         }
216         else
217         {
218             return null;
219         }
220     }
221     
222     private HTTPSampler createSampler()
223     {
224         MultipartUrlConfig urlConfig = null;
225         HTTPSampler sampler = new HTTPSampler();
226         sampler.setDomain(serverName());
227         log.debug("Proxy: setting server: " + sampler.getDomain());
228         sampler.setMethod(method);
229         log.debug("Proxy: method server: " + sampler.getMethod());
230         sampler.setPath(serverUrl());
231         log.debug("Proxy: setting path: " + sampler.getPath());
232         if (numberRequests){
233             requestNumber++;
234             sampler.setName(requestNumber + " " + sampler.getPath());
235         } else {
236             sampler.setName(sampler.getPath());
237         }
238         sampler.setPort(serverPort());
239         log.debug("Proxy: setting port: " + sampler.getPort());
240         if (url.indexOf("//") > -1)
241         {
242             String JavaDoc protocol = url.substring(0, url.indexOf(":"));
243             log.debug("Proxy: setting protocol to : " + protocol);
244             sampler.setProtocol(protocol);
245         }
246         else if (sampler.getPort() == 443)
247         {
248             sampler.setProtocol("https");
249             log.debug("Proxy: setting protocol to https");
250         }
251         else
252         {
253             log.debug("Proxy setting default protocol to: http");
254             sampler.setProtocol("http");
255         }
256         if ((urlConfig = isMultipart(getContentType())) != null)
257         {
258             urlConfig.parseArguments(postData);
259             sampler.setArguments(urlConfig.getArguments());
260             sampler.setFileField(urlConfig.getFileFieldName());
261             sampler.setFilename(urlConfig.getFilename());
262             sampler.setMimetype(urlConfig.getMimeType());
263         }
264         else
265         {
266             sampler.parseArguments(postData);
267         }
268         return sampler;
269     }
270     
271     //
272
// Parsing Methods
273
//
274

275     /**
276      * Find the //server.name from an url.
277      *
278      * @return server's internet name
279      */

280     public String JavaDoc serverName()
281     {
282         // chop to "server.name:x/thing"
283
String JavaDoc str = url;
284         int i = str.indexOf("//");
285         if (i > 0)
286         {
287             str = str.substring(i + 2);
288         }
289         // chop to server.name:xx
290
i = str.indexOf("/");
291         if (0 < i)
292         {
293             str = str.substring(0, i);
294         }
295         // chop to server.name
296
i = str.indexOf(":");
297         if (0 < i)
298         {
299             str = str.substring(0, i);
300         }
301         return str;
302     }
303
304     /**
305      * Find the :PORT form http://server.ect:PORT/some/file.xxx
306      *
307      * @return server's port
308      */

309     public int serverPort()
310     {
311         String JavaDoc str = url;
312         // chop to "server.name:x/thing"
313
int i = str.indexOf("//");
314         if (i > 0)
315         {
316             str = str.substring(i + 2);
317         }
318         // chop to server.name:xx
319
i = str.indexOf("/");
320         if (0 < i)
321         {
322             str = str.substring(0, i);
323         }
324         // chop XX
325
i = str.indexOf(":");
326         if (0 < i)
327         {
328             return Integer.parseInt(str.substring(i + 1).trim());
329         }
330         return 80;
331     }
332     
333     /**
334      * Find the /some/file.xxxx form http://server.ect:PORT/some/file.xxx
335      *
336      * @return the deproxied url
337      */

338     public String JavaDoc serverUrl()
339     {
340         String JavaDoc str = url;
341         int i = str.indexOf("//");
342         if (i > 0)
343         {
344             str = str.substring(i + 2);
345         }
346         i = str.indexOf("/");
347         if (i < 0)
348         {
349             return "";
350         }
351         return str.substring(i);
352     }
353     
354     /**
355      * Returns the next token in a string.
356      *
357      * @param tk String that is partially tokenized.
358      * @return The remainder
359      */

360     String JavaDoc getToken(StringTokenizer JavaDoc tk)
361     {
362         String JavaDoc str = "";
363         if (tk.hasMoreTokens())
364         {
365             str = tk.nextToken();
366         }
367         return str;
368     }
369     
370     /**
371      * Returns the remainder of a tokenized string.
372      *
373      * @param tk String that is partially tokenized.
374      * @return The remainder
375      */

376     String JavaDoc getRemainder(StringTokenizer JavaDoc tk)
377     {
378         String JavaDoc str = "";
379         if (tk.hasMoreTokens())
380         {
381             str = tk.nextToken();
382         }
383         while (tk.hasMoreTokens())
384         {
385             str += " " + tk.nextToken();
386         }
387         return str;
388     }
389
390     public static class Test extends TestCase
391     {
392         public Test(String JavaDoc name)
393         {
394             super(name);
395         }
396
397         public void setUp()
398         {
399         }
400
401         public void testRepeatedArguments() throws Exception JavaDoc
402         {
403             String JavaDoc TEST_REQ =
404                 "GET http://localhost/matrix.html?"
405                     + "update=yes&d=1&d=2&d=&d=&d=&d=&d=&d=1&d=2&d=1&d=" +
406                         "&d= HTTP/1.0\n\n";
407             HttpRequestHdr req = new HttpRequestHdr();
408             req.parse(new java.io.ByteArrayInputStream JavaDoc(TEST_REQ.getBytes()));
409             HTTPSampler s = req.getSampler();
410             assertEquals(s.getArguments().getArguments().size(), 13);
411         }
412     }
413 }
414
Popular Tags