KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > barracuda > testbed > workbench > stress > URLStressTester


1 package org.enhydra.barracuda.testbed.workbench.stress;
2
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.io.*;
6 import java.net.*;
7 import java.util.*;
8 import javax.swing.*;
9 import javax.swing.event.*;
10
11 import org.enhydra.barracuda.plankton.data.*;
12 import org.enhydra.barracuda.plankton.http.*;
13
14 import org.enhydra.barracuda.testbed.workbench.util.gui.Containers;
15 import org.enhydra.barracuda.testbed.workbench.util.gui.Cursors;
16 import org.enhydra.barracuda.testbed.workbench.util.gui.DefaultComponentListener;
17
18 /**
19  * URL Stress Tester
20  */

21 public class URLStressTester extends JPanel {
22
23     //public vars
24
public static String JavaDoc DEFAULT_URL = "http://localhost:8080/Barracuda/Level5Event.event";
25     public static String JavaDoc DEFAULT_NUMBER_OF_THREADS = "5";
26
27     //debug vars
28
public static int showDebug = 0;
29
30     //test variables
31
private int activeThreads = 0;
32     private int threadCntr = 0;
33     private long startTime = 0;
34     private long endTime = 0;
35     private long totalTime = 0;
36     private boolean readySetGo = false;
37     private boolean logToConsole = true;
38     private int wrapOutput = 60;
39     private boolean showDetails = true;
40     private boolean doGet = true;
41
42     //objects
43
private boolean isInitialized = false;
44
45     //buttons & controls
46
//...URL panel
47
private JTextField jtfURL = null;
48     private JButton jbRunTest = null;
49     private JButton jbAvgTest = null;
50     private JButton jbAddToReq = null;
51     //...Main panel
52
private JSplitPane jspMaster = null;
53     //...Requests panel
54
private JPanel jpRequests = null;
55     //...Output panel
56
private JPanel jpOutput = null;
57     //...Footer panel
58
private JTextField jtfNoOfThreads = null;
59     private JRadioButton jrbGet = null;
60     private JRadioButton jrbPost = null;
61     private JTextField jtfLatency = null;
62     private JTextField jtfWrapOutput = null;
63     private JCheckBox jcbShowDetails = null;
64
65     
66     /**
67      * Public constructor
68      */

69     public URLStressTester() {
70         //set up a listener so when this guy is exposed we hear about it
71
this.addComponentListener(new LocalComponentListener());
72     }
73     
74     //============================================================
75
// Model / Controller info for the Master View
76
//============================================================
77
/**
78      * This method is responsible for laying out the
79      * UI components.
80      *
81      * @throws Exception
82      */

83     private void initViews() throws Exception JavaDoc {
84
85         //general
86
this.setLayout(new GridBagLayout());
87         LocalActionAdapter actionAdapter = new LocalActionAdapter();
88         Insets buttonInsets = new Insets(0, 5, 0, 5);
89
90         //URL Panel
91
JPanel jpURL = new JPanel();
92         jpURL.setLayout(new GridBagLayout());
93         this.add(jpURL, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0,
94             GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
95         //...URL Label
96
JLabel jlbURL = new JLabel("URL:");
97         jpURL.add(jlbURL, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
98             GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
99         //...URL Textfield
100
jtfURL = new JTextField(DEFAULT_URL);
101         jpURL.add(jtfURL, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 1.0, 0.0,
102             GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 0, 0));
103         //...Run Test
104
jbRunTest = new JButton("Run Test");
105         jbRunTest.setToolTipText("Run the test");
106         jbRunTest.setMargin(buttonInsets);
107         jbRunTest.addActionListener(actionAdapter);
108         jpURL.add(jbRunTest, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
109             GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
110         //...Avg Test
111
jbAvgTest = new JButton("Avg Test");
112         jbAvgTest.setToolTipText("Run the test 10x and average the results");
113         jbAvgTest.setMargin(buttonInsets);
114         jbAvgTest.addActionListener(actionAdapter);
115         jpURL.add(jbAvgTest, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
116             GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
117         //...Add to List
118
jbAddToReq = new JButton("+List");
119         jbAddToReq.setMargin(buttonInsets);
120         jbAddToReq.addActionListener(actionAdapter);
121         jpURL.add(jbAddToReq, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
122             GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
123
124
125         
126         //Main Panel (Splitter)
127
jspMaster = new JSplitPane();
128         jspMaster.setOneTouchExpandable(true);
129         this.add(jspMaster, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0,
130             GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 5, 5, 5), 0, 0));
131         
132         //...Requests Panel
133
jpRequests = new JPanel();
134         jpRequests.setLayout(new GridBagLayout());
135         jspMaster.add(jpRequests, JSplitPane.LEFT);
136         //......Todo
137
jpRequests.add(new JLabel("todo"), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0,
138             GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
139         
140         //...Output Panel
141
jpOutput = new JPanel();
142         jpOutput.setLayout(new GridBagLayout());
143         JScrollPane jspOutput = new JScrollPane(jpOutput);
144         jspMaster.add(jspOutput, JSplitPane.RIGHT);
145         //......Todo
146
// jpOutput.add(new JLabel("todo"), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0,
147
// GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
148

149         jspMaster.setDividerLocation(0);
150         
151         
152         //Footer Panel
153
JPanel jpFooter = new JPanel();
154         jpFooter.setLayout(new GridBagLayout());
155         this.add(jpFooter, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0,
156             GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 5, 2, 5), 0, 0));
157         //...filler
158
jpFooter.add(new JLabel(" "), new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 1.0, 0.0,
159             GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
160         //...Get/Post
161
jpFooter.add(new JLabel("Http Method:"), new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
162             GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 15, 0, 0), 0, 0));
163         ButtonGroup bg = new ButtonGroup();
164         jrbGet = new JRadioButton("Get");
165         bg.add(jrbGet);
166         jrbGet.setSelected(true);
167         jpFooter.add(jrbGet, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
168             GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0));
169         jrbPost = new JRadioButton("Post");
170         bg.add(jrbPost);
171         jpFooter.add(jrbPost, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
172             GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
173         //...No of Threads
174
jpFooter.add(new JLabel("No. Threads:"), new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
175             GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 15, 0, 0), 0, 0));
176         jtfNoOfThreads = new JTextField(DEFAULT_NUMBER_OF_THREADS, 3);
177         jpFooter.add(jtfNoOfThreads, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
178             GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0));
179         //...Latency
180
jpFooter.add(new JLabel("Latency:"), new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
181             GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 15, 0, 0), 0, 0));
182         jtfLatency = new JTextField("0", 3);
183         jpFooter.add(jtfLatency, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
184             GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0));
185         //...Wrap Output
186
jpFooter.add(new JLabel("Wrap:"), new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
187             GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 15, 0, 0), 0, 0));
188         jtfWrapOutput = new JTextField("60", 2);
189         jpFooter.add(jtfWrapOutput, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
190             GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0));
191         //...Show Details
192
jcbShowDetails = new JCheckBox("Show Details", true);
193         jpFooter.add(jcbShowDetails, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
194             GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 15, 0, 0), 0, 0));
195     }
196     
197     
198     public void runTest(int numberOfTimesToRun) {
199         try {
200             //set the cursors
201
Cursors.setWorking(Containers.getRootContainer(URLStressTester.this), true);
202
203             //disable key fields
204
jbRunTest.setEnabled(false);
205             jbAddToReq.setEnabled(false);
206
207             //get all the settings for this run
208
String JavaDoc surl = jtfURL.getText();
209             int threadCount = 1;
210             try {threadCount = Integer.parseInt(jtfNoOfThreads.getText());}
211             catch (NumberFormatException JavaDoc e) {}
212             int latency = 0;
213             try {latency = Integer.parseInt(jtfLatency.getText());}
214             catch (NumberFormatException JavaDoc e) {}
215             wrapOutput = 60;
216             try {wrapOutput = Integer.parseInt(jtfWrapOutput.getText());}
217             catch (NumberFormatException JavaDoc e) {}
218             doGet = jrbGet.isSelected();
219             showDetails = jcbShowDetails.isSelected();
220             int outputCount = (showDetails ? threadCount : 1);
221
222             //create the necessary output consoles
223
jpOutput.removeAll();
224             jpOutput.setLayout(new GridLayout(1,outputCount,0,0));
225             JTextArea jtxa[] = new JTextArea[outputCount];
226             for (int i=0; i<outputCount; i++) {
227                 jtxa[i] = new JTextArea("");
228                 jtxa[i].setCursor(new Cursor(Cursor.WAIT_CURSOR));
229                 jtxa[i].setMinimumSize(new Dimension(20,100));
230 // jtxa[i].setMaximumSize(new Dimension(100,100));
231
jtxa[i].invalidate();
232                 JScrollPane jsp = new JScrollPane(jtxa[i]);
233                 jpOutput.add(jsp);
234             }
235             Cursors.setWorking(jpOutput, true);
236 // jpOutput.invalidate();
237
jspMaster.validate();
238             jspMaster.paintAll(jspMaster.getGraphics());
239             Thread.yield();
240         
241             //now we're ready to run the tests
242
long totalMillis = 0;
243             for (int loopCntr=0; loopCntr<numberOfTimesToRun; loopCntr++) {
244                 //create the necessary threads
245
activeThreads=0;
246                  threadCntr=0;
247                  readySetGo = false;
248                 URLRequestor threads[] = new URLRequestor[threadCount];
249                 for (int i=0; i<threadCount; i++) {
250                     int ta = 0;
251                     if (i<outputCount) ta = i;
252                     threads[i] = new URLRequestor(surl, i, jtxa[ta], latency*i);
253                     threads[i].start();
254                 }
255
256                 //sit and wait for all the threads to get up and running (but only do this if the latency is not set)
257
for (int i=0; i<threadCount; i++) {
258                     if (!threads[i].isRunning) {
259                         --i;
260                         try {
261                             Thread.sleep(50);
262                             Thread.yield();
263                         } catch (InterruptedException JavaDoc ie) {}
264                     }
265                 }
266
267                 //let er rip!
268
startTime = System.currentTimeMillis();
269                 totalTime = 0;
270                 readySetGo = true;
271             
272                 //sit and wait for all the threads to finish
273
for (int i=0; i<threadCount; i++) {
274                     try {threads[i].join();}
275                     catch (InterruptedException JavaDoc ie) {}
276                 }
277                 endTime = System.currentTimeMillis();
278                 println (jtxa[0], " ");
279                 println (jtxa[0], "Start:"+startTime);
280                 println (jtxa[0], "End:"+endTime, true);
281                 println (jtxa[0], "Elapsed:"+(endTime-startTime)+" millisecs", true);
282                 println (jtxa[0], "Average:"+((totalTime)/threadCount)+" millisecs", true);
283                 totalMillis += (endTime-startTime);
284             }
285             println (jtxa[0], " ");
286             long avg = (totalMillis/numberOfTimesToRun);
287             if (numberOfTimesToRun>1) println (jtxa[0], "Average time/run over "+numberOfTimesToRun+" iterations:"+avg+" millisecs", true);
288             println (jtxa[0], "Throughput:"+(threadCount*numberOfTimesToRun*1000/totalMillis)+" reqs/1000 millisecs", true);
289         } finally {
290             //re-enable key fields
291
jbRunTest.setEnabled(true);
292             jbAddToReq.setEnabled(true);
293             
294             //reset the cursors
295
Cursors.setWorking(Containers.getRootContainer(URLStressTester.this), false);
296         }
297     }
298     
299     //-------------------- URLRequestor --------------------------
300
/**
301      * Request a URL
302      */

303     class URLRequestor extends Thread JavaDoc {
304
305         String JavaDoc surl = null;
306         int threadNo = -1;
307         JTextArea jtxa = null;
308         int latency;
309         boolean isRunning = false;
310             
311         public URLRequestor (String JavaDoc iurl, int ithreadNo, JTextArea ijtxa, int ilatency) {
312             surl = iurl;
313             threadNo = ithreadNo;
314             jtxa = ijtxa;
315             jtxa.setText("");
316             latency = ilatency;
317             if (showDebug>0) println (jtxa, "Creating Thread...");
318         }
319             
320         public void run() {
321             //create the HTTPRequest object
322
HttpRequester hr = new HttpRequester();
323             String JavaDoc urlStr = surl;
324             String JavaDoc method = (doGet ? HttpRequester.GET : HttpRequester.POST);
325             Map props = null;
326             int spos = surl.indexOf("?");
327             if (spos>0) {
328                 String JavaDoc paramStr = surl.substring(spos+1);
329                 urlStr = surl.substring(0,spos);
330                 if (showDebug>0) println (jtxa, "URL Str:"+urlStr);
331                 if (showDebug>0) println (jtxa, "Param Str:"+paramStr);
332                 props = HttpConverter.cvtURLStringToMap (paramStr, "&");
333             }
334             try {hr.setRequest (urlStr, method, props);}
335             catch (MalformedURLException e) {
336                 println (jtxa, "Bad URL:"+e);
337                 return;
338             }
339             
340             //...now we're officially running
341
isRunning = true;
342
343             
344             //wait for the starting gun
345
while (!readySetGo) {
346                 try {
347                     Thread.sleep(10);
348                     Thread.yield();
349                 } catch (InterruptedException JavaDoc ie) {}
350             }
351             
352             //now sleep for the required amount of latency
353
if (latency>0) try {
354                 Thread.sleep(latency);
355                 Thread.yield();
356             } catch (InterruptedException JavaDoc ie) {}
357             
358             //Bang! Off to the races...
359
long startTime = System.currentTimeMillis();
360 // int threadNo = ++threadCntr;
361
activeThreads++;
362             if (showDetails) println (jtxa, "Starting Thread "+threadNo+(latency>0 ? " (lat="+latency+")" : ""));
363
364             //retrieve the URL
365
boolean success = false;
366             try {
367 /*
368                 //do some busy work...
369                 double d = 0D;
370                 for (int i=0; i<100000; i++) {
371                     d+=(System.currentTimeMillis()/3.141592654);
372                     if (i%1000==0) Thread.yield();
373                 }
374                 println (jtxa, "Accumulated time:"+d);
375 */

376                 //make the connection
377
hr.connect();
378                 
379                 //csc_010404_1 - added
380
//start by getting the headers
381
if (showDetails) println (jtxa, "Headers...");
382                 Map hdrs = hr.getURLConnection().getHeaderFields();
383                 Iterator it = hdrs.entrySet().iterator();
384                 while (it.hasNext()) {
385                     Map.Entry me = (Map.Entry) it.next();
386                     if (showDetails) println (jtxa, "key:"+me.getKey()+" val:"+me.getValue());
387                 }
388             
389                 //next get the data
390
if (showDetails) println (jtxa, "Data...");
391                 String JavaDoc inputLine = null;
392                 while ((inputLine = hr.readLine())!=null) {
393                     if (showDetails) println (jtxa, inputLine);
394                     Thread.yield();
395                 }
396                 hr.disconnect();
397                 success = true;
398             } catch (Exception JavaDoc e) {
399                 println (jtxa, "Aborted Thread "+threadNo+" "+e);
400                 e.printStackTrace();
401             }
402             long endTime = System.currentTimeMillis();
403             incrTotalTime(endTime-startTime);
404             if (success && showDetails) println (jtxa, "Finished Thread "+threadNo+" ("+(endTime-startTime)+" millis)");
405         }
406     }
407
408     public void println(JTextArea jta, String JavaDoc s) {
409         println (jta, s, logToConsole);
410     }
411     
412     public void println(JTextArea jta, String JavaDoc s, boolean logToConsole) {
413         for (int i=0, max=s.length(); i<max; i+=wrapOutput) {
414             int epos = i+wrapOutput;
415             if (epos>max) epos = max;
416             if (i==0) jta.append(s.substring(i,epos)+System.getProperty("line.separator"));
417             else jta.append(" "+s.substring(i,epos)+System.getProperty("line.separator"));
418         }
419         jta.invalidate();
420         jta.paintAll(jta.getGraphics());
421         if (logToConsole) System.out.println (s);
422     }
423     
424     public synchronized void incrTotalTime(long incr) {
425         totalTime += incr;
426     }
427     
428     
429
430     //-------------------- ComponentListener ---------------------
431
/**
432      * Handle component events
433      */

434     class LocalComponentListener extends DefaultComponentListener {
435     
436         /**
437          * Invoked when the component has been made visible.
438          */

439         public void componentShown(ComponentEvent e) {
440             if (showDebug>1) System.out.println ("Shown:"+e);
441             
442             //init the screen and catch any unexpected errors
443
if (!isInitialized) try {
444                 initViews();
445                 isInitialized = true;
446             } catch (Exception JavaDoc be) {
447                 System.out.println ("Error initializing "+this);
448                 be.printStackTrace();
449             }
450         }
451     }
452
453     //-------------------- ActionListener ------------------------
454
/**
455      * Handle the actions for buttons
456      */

457     class LocalActionAdapter implements java.awt.event.ActionListener JavaDoc {
458
459         /**
460          * actionPerformed method
461          */

462         public void actionPerformed(ActionEvent e) {
463             //handle the action
464
Object JavaDoc o = e.getSource();
465             if (o==jbAddToReq) {
466                 java.awt.Toolkit.getDefaultToolkit().beep();
467                 JOptionPane.showMessageDialog(null, "Not implemented yet", "To Do", JOptionPane.INFORMATION_MESSAGE);
468             } else if (o==jbRunTest) {
469                 runTest(1);
470             } else if (o==jbAvgTest) {
471                 runTest(10);
472             }
473         }
474     }
475     
476 }
477
Popular Tags