KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > protocol > http > modifier > AnchorModifier


1 // $Header: /home/cvs/jakarta-jmeter/src/protocol/http/org/apache/jmeter/protocol/http/modifier/AnchorModifier.java,v 1.14.2.3 2005/01/05 01:05:29 sebb 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.modifier;
20
21 import java.io.FileInputStream JavaDoc;
22 import java.io.Serializable JavaDoc;
23 import java.io.UnsupportedEncodingException JavaDoc;
24 import java.net.MalformedURLException JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.LinkedList JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Random JavaDoc;
31
32 import org.apache.jmeter.config.Argument;
33 import org.apache.jmeter.config.Arguments;
34 import org.apache.jmeter.config.ConfigElement;
35 import org.apache.jmeter.junit.JMeterTestCase;
36 import org.apache.jmeter.processor.PreProcessor;
37 import org.apache.jmeter.protocol.http.parser.HtmlParsingUtils;
38 import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult;
39 import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase;
40 import org.apache.jmeter.samplers.SampleResult;
41 import org.apache.jmeter.samplers.Sampler;
42 import org.apache.jmeter.save.SaveService;
43 import org.apache.jmeter.testelement.AbstractTestElement;
44 import org.apache.jmeter.testelement.property.PropertyIterator;
45 import org.apache.jmeter.threads.JMeterContext;
46 import org.apache.jmeter.threads.JMeterContextService;
47 import org.apache.jorphan.io.TextFile;
48 import org.apache.jorphan.logging.LoggingManager;
49 import org.apache.log.Logger;
50 import org.w3c.dom.Document JavaDoc;
51 import org.w3c.dom.NamedNodeMap JavaDoc;
52 import org.w3c.dom.Node JavaDoc;
53 import org.w3c.dom.NodeList JavaDoc;
54 import org.xml.sax.SAXException JavaDoc;
55
56 /**
57  * @author Michael Stover
58  * @version $Revision: 1.14.2.3 $
59  */

60 public class AnchorModifier
61     extends AbstractTestElement
62     implements PreProcessor, Serializable JavaDoc
63 {
64     transient private static Logger log = LoggingManager.getLoggerForClass();
65     private static Random JavaDoc rand = new Random JavaDoc();
66
67     public AnchorModifier()
68     {}
69
70     /**
71      * Modifies an Entry object based on HTML response text.
72      */

73     public void process()
74     {
75         JMeterContext context = getThreadContext();
76         Sampler sam = context.getCurrentSampler();
77         SampleResult res = context.getPreviousResult();
78         HTTPSamplerBase sampler = null;
79         HTTPSampleResult result = null;
80         if (res == null
81             || !(sam instanceof HTTPSamplerBase)
82             || !(res instanceof HTTPSampleResult))
83         {
84             log.info("Can't apply HTML Link Parser when the previous"
85                      +" sampler run is not an HTTP Request.");
86             return;
87         }
88         else
89         {
90             sampler = (HTTPSamplerBase) sam;
91             result = (HTTPSampleResult) res;
92         }
93         List JavaDoc potentialLinks = new ArrayList JavaDoc();
94         String JavaDoc responseText = "";
95         try
96         {
97             responseText = new String JavaDoc(result.getResponseData(), "8859_1");
98         }
99         catch (UnsupportedEncodingException JavaDoc e)
100         {}
101         Document JavaDoc html;
102         try
103         {
104             int index = responseText.indexOf("<");
105             if (index == -1)
106             {
107                 index = 0;
108             }
109             html = (Document JavaDoc) HtmlParsingUtils.getDOM(responseText.substring(index));
110         }
111         catch (SAXException JavaDoc e)
112         {
113             return;
114         }
115         addAnchorUrls(html, result, sampler, potentialLinks);
116         addFormUrls(html, result, sampler, potentialLinks);
117         if (potentialLinks.size() > 0)
118         {
119             HTTPSamplerBase url =
120                 (HTTPSamplerBase) potentialLinks.get(
121                     rand.nextInt(potentialLinks.size()));
122             sampler.setDomain(url.getDomain());
123             sampler.setPath(url.getPath());
124             if (url.getMethod().equals(HTTPSamplerBase.POST))
125             {
126                 PropertyIterator iter = sampler.getArguments().iterator();
127                 while (iter.hasNext())
128                 {
129                     Argument arg = (Argument) iter.next().getObjectValue();
130                     modifyArgument(arg, url.getArguments());
131                 }
132             }
133             else
134             {
135                 sampler.setArguments(url.getArguments());
136                 //config.parseArguments(url.getQueryString());
137
}
138             sampler.setProtocol(url.getProtocol());
139             return;
140         }
141         return;
142     }
143
144     private void modifyArgument(Argument arg, Arguments args)
145     {
146         log.debug("Modifying argument: " + arg);
147         List JavaDoc possibleReplacements = new ArrayList JavaDoc();
148         PropertyIterator iter = args.iterator();
149         Argument replacementArg;
150         while (iter.hasNext())
151         {
152             replacementArg = (Argument) iter.next().getObjectValue();
153             try
154             {
155                 if (HtmlParsingUtils.isArgumentMatched(replacementArg, arg))
156                 {
157                     possibleReplacements.add(replacementArg);
158                 }
159             }
160             catch (Exception JavaDoc ex)
161             {
162                 log.error("", ex);
163             }
164         }
165
166         if (possibleReplacements.size() > 0)
167         {
168             replacementArg =
169                 (Argument) possibleReplacements.get(
170                     rand.nextInt(possibleReplacements.size()));
171             arg.setName(replacementArg.getName());
172             arg.setValue(replacementArg.getValue());
173             log.debug(
174                 "Just set argument to values: "
175                     + arg.getName()
176                     + " = "
177                     + arg.getValue());
178             args.removeArgument(replacementArg);
179         }
180     }
181
182     public void addConfigElement(ConfigElement config)
183     {}
184
185     private void addFormUrls(
186         Document JavaDoc html,
187         HTTPSampleResult result,
188         HTTPSamplerBase config,
189         List JavaDoc potentialLinks)
190     {
191         NodeList JavaDoc rootList = html.getChildNodes();
192         List JavaDoc urls = new LinkedList JavaDoc();
193         for (int x = 0; x < rootList.getLength(); x++)
194         {
195             urls.addAll(
196                 HtmlParsingUtils.createURLFromForm(
197                     rootList.item(x),
198                     result.getURL()));
199         }
200         Iterator JavaDoc iter = urls.iterator();
201         while (iter.hasNext())
202         {
203             HTTPSamplerBase newUrl = (HTTPSamplerBase) iter.next();
204             try
205             {
206                 newUrl.setMethod(HTTPSamplerBase.POST);
207                 if (HtmlParsingUtils.isAnchorMatched(newUrl, config))
208                 {
209                     potentialLinks.add(newUrl);
210                 }
211             }
212             catch (org.apache.oro.text.regex.MalformedPatternException e)
213             {
214                 log.error("Bad pattern", e);
215             }
216         }
217     }
218
219     private void addAnchorUrls(
220         Document JavaDoc html,
221         HTTPSampleResult result,
222         HTTPSamplerBase config,
223         List JavaDoc potentialLinks)
224     {
225         String JavaDoc base="";
226         NodeList JavaDoc baseList = html.getElementsByTagName("base");
227         if (baseList.getLength()>0){
228             base=baseList.item(0).getAttributes().getNamedItem("href").getNodeValue();
229         }
230         NodeList JavaDoc nodeList = html.getElementsByTagName("a");
231         for (int i = 0; i < nodeList.getLength(); i++)
232         {
233             Node JavaDoc tempNode = nodeList.item(i);
234             NamedNodeMap JavaDoc nnm = tempNode.getAttributes();
235             Node JavaDoc namedItem = nnm.getNamedItem("href");
236             if (namedItem == null)
237             {
238                 continue;
239             }
240             String JavaDoc hrefStr = namedItem.getNodeValue();
241             try
242             {
243                 HTTPSamplerBase newUrl =
244                     HtmlParsingUtils.createUrlFromAnchor(
245                         hrefStr, new URL JavaDoc(result.getURL(),base));
246                 newUrl.setMethod(HTTPSamplerBase.GET);
247                 log.debug("possible match: " + newUrl);
248                 if (HtmlParsingUtils.isAnchorMatched(newUrl, config))
249                 {
250                     log.debug("Is a match! " + newUrl);
251                     potentialLinks.add(newUrl);
252                 }
253             }
254             catch (MalformedURLException JavaDoc e)
255             {}
256             catch (org.apache.oro.text.regex.MalformedPatternException e)
257             {
258                 log.error("Bad pattern", e);
259             }
260         }
261     }
262
263     public static class Test extends JMeterTestCase
264     {
265         public Test(String JavaDoc name)
266         {
267             super(name);
268         }
269         private JMeterContext jmctx = null;
270         
271         public void setUp()
272         {
273             jmctx = JMeterContextService.getContext();
274         }
275
276         public void testProcessingHTMLFile(String JavaDoc HTMLFileName) throws Exception JavaDoc
277         {
278             HTTPSamplerBase config =
279                 (HTTPSamplerBase) SaveService
280                     .loadSubTree(
281                         new FileInputStream JavaDoc(
282                             System.getProperty("user.dir")
283                                 + "/testfiles/load_bug_list.jmx"))
284                     .getArray()[0];
285             config.setRunningVersion(true);
286             HTTPSampleResult result = new HTTPSampleResult();
287             HTTPSamplerBase context =
288                 (HTTPSamplerBase) SaveService
289                     .loadSubTree(
290                         new FileInputStream JavaDoc(
291                             System.getProperty("user.dir")
292                                 + "/testfiles/Load_JMeter_Page.jmx"))
293                     .getArray()[0];
294             jmctx.setCurrentSampler(context);
295             jmctx.setCurrentSampler(config);
296             result.setResponseData(
297                 new TextFile(
298                     System.getProperty("user.dir")
299                         + HTMLFileName)
300                     .getText()
301                     .getBytes());
302             result.setSampleLabel(context.toString());
303             result.setSamplerData(context.toString());
304             result.setURL(new URL JavaDoc("http://issues.apache.org/fakepage.html"));
305             jmctx.setPreviousResult(result);
306             AnchorModifier modifier = new AnchorModifier();
307             modifier.setThreadContext(jmctx);
308             modifier.process();
309             assertEquals(
310                 "http://issues.apache.org/bugzilla/buglist.cgi?"
311                     + "bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED"
312                     + "&email1=&emailtype1=substring&emailassigned_to1=1"
313                     + "&email2=&emailtype2=substring&emailreporter2=1"
314                     + "&bugidtype=include&bug_id=&changedin=&votes="
315                     + "&chfieldfrom=&chfieldto=Now&chfieldvalue="
316                     + "&product=JMeter&short_desc=&short_desc_type=substring"
317                     + "&long_desc=&long_desc_type=substring&bug_file_loc="
318                     + "&bug_file_loc_type=substring&keywords="
319                     + "&keywords_type=anywords"
320                     + "&field0-0-0=noop&type0-0-0=noop&value0-0-0="
321                     + "&cmdtype=doit&order=Reuse+same+sort+as+last+time",
322                 config.toString());
323             config.recoverRunningVersion();
324             assertEquals(
325                 "http://issues.apache.org/bugzilla/buglist.cgi?"
326                     + "bug_status=.*&bug_status=.*&bug_status=.*&email1="
327                     + "&emailtype1=substring&emailassigned_to1=1&email2="
328                     + "&emailtype2=substring&emailreporter2=1"
329                     + "&bugidtype=include&bug_id=&changedin=&votes="
330                     + "&chfieldfrom=&chfieldto=Now&chfieldvalue="
331                     + "&product=JMeter&short_desc=&short_desc_type=substring"
332                     + "&long_desc=&long_desc_type=substring&bug_file_loc="
333                     + "&bug_file_loc_type=substring&keywords="
334                     + "&keywords_type=anywords&field0-0-0=noop"
335                     + "&type0-0-0=noop&value0-0-0=&cmdtype=doit"
336                     + "&order=Reuse+same+sort+as+last+time",
337                 config.toString());
338         }
339
340         public void testModifySampler() throws Exception JavaDoc
341         {
342             testProcessingHTMLFile(
343                 "/testfiles/jmeter_home_page.html");
344         }
345         
346         public void testModifySamplerWithRelativeLink() throws Exception JavaDoc
347         {
348             testProcessingHTMLFile(
349                 "/testfiles/jmeter_home_page_with_relative_links.html");
350         }
351 //* Feature not yet implemented. TODO: implement it.
352
public void testModifySamplerWithBaseHRef() throws Exception JavaDoc
353         {
354             testProcessingHTMLFile(
355                 "/testfiles/jmeter_home_page_with_base_href.html");
356         }
357 //*/
358
}
359 }
360
Popular Tags