KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > ext > dbobj > PerfTests


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 /*
66  * PerfTests.java
67  *
68  * Copyright 1999, 2000, 2001 Jcorporate Ltd.
69  */

70 package com.jcorporate.expresso.ext.dbobj;
71
72 import com.jcorporate.expresso.core.controller.ControllerRequest;
73 import com.jcorporate.expresso.core.db.DBException;
74 import com.jcorporate.expresso.core.dbobj.SecuredDBObject;
75 import com.jcorporate.expresso.core.dbobj.ValidValue;
76 import com.jcorporate.expresso.core.misc.ConfigManager;
77 import com.jcorporate.expresso.core.misc.DateTime;
78 import com.jcorporate.expresso.core.misc.StringUtil;
79 import org.apache.log4j.Logger;
80
81 import java.io.IOException JavaDoc;
82 import java.io.InputStream JavaDoc;
83 import java.io.InputStreamReader JavaDoc;
84 import java.net.HttpURLConnection JavaDoc;
85 import java.net.MalformedURLException JavaDoc;
86 import java.net.URL JavaDoc;
87 import java.util.Hashtable JavaDoc;
88 import java.util.Iterator JavaDoc;
89 import java.util.List JavaDoc;
90 import java.util.Vector JavaDoc;
91
92
93 /**
94  * PerfTests
95  * List of URL's to execute and time, along with statistics on their
96  * execution time.
97  *
98  * @author Michael Nash
99  */

100 public class PerfTests
101         extends SecuredDBObject {
102     private static Vector JavaDoc httpValues = null;
103     private static Vector JavaDoc sessionValues = null;
104     private static Logger log = Logger.getLogger(PerfTests.class);
105
106     /**
107      * Constructor
108      */

109     public PerfTests()
110             throws DBException {
111         super();
112     } /* PerfTests() */
113
114     /**
115      * Use over (String) constructor. Initializes the object in the context
116      * of the user who's uid belongs to the parameter.
117      *
118      * @param uid the Uid of the user context
119      * @throws DBException if there's an initialization problem
120      */

121     public PerfTests(int uid)
122             throws DBException {
123         super(uid);
124     }
125
126     /**
127      * For using DBObjects within Controllers. Initializes based upon the current
128      * user and the requested db. [Of course this can be modified later]
129      *
130      * @param request - The controller request handed to you by the framework.
131      * @throws DBException if there's an initialization problem
132      */

133     public PerfTests(ControllerRequest request)
134             throws DBException {
135         super(request);
136     }
137
138     /**
139      * @param fieldName the name of the field
140      * @return java.lang.String
141      * @throws DBException upon error
142      */

143     public String JavaDoc getField(String JavaDoc fieldName)
144             throws DBException {
145         if (fieldName.equals("AverageTime")) {
146             long totCounts = 0;
147
148             try {
149                 totCounts = new Long JavaDoc(getField("TestCount")).longValue();
150             } catch (NumberFormatException JavaDoc ne) {
151                 totCounts = 0;
152             }
153
154             long totTime = 0;
155
156             try {
157                 totTime = new Long JavaDoc(getField("TotalTime")).longValue();
158             } catch (NumberFormatException JavaDoc ne) {
159                 totTime = 0;
160             }
161             if (totTime <= 0) {
162                 return ("0");
163             } else {
164                 return ("" + totTime / totCounts);
165             }
166         } else if (fieldName.equals("FailedTests")) {
167             long totCounts = 0;
168
169             try {
170                 totCounts = new Long JavaDoc(getField("TestCount")).longValue();
171             } catch (NumberFormatException JavaDoc ne) {
172                 totCounts = 0;
173             }
174
175             long successCount = 0;
176
177             try {
178                 successCount = new Long JavaDoc(getField("SuccessfulTests")).longValue();
179             } catch (NumberFormatException JavaDoc ne) {
180                 successCount = 0;
181             }
182
183             return ("" + (totCounts - successCount));
184         }
185
186         return super.getField(fieldName);
187     } /* getField(String) */
188
189
190     public Vector JavaDoc getValidValues(String JavaDoc fieldName)
191             throws DBException {
192         if (fieldName.equals("HttpMethod")) {
193             if (httpValues == null) {
194                 httpValues = new Vector JavaDoc();
195                 httpValues.addElement(new ValidValue("GET", "GET"));
196                 httpValues.addElement(new ValidValue("POST", "POST"));
197             }
198
199             return httpValues;
200         } else if (fieldName.equals("GetSession")) {
201             if (sessionValues == null) {
202                 sessionValues = new Vector JavaDoc();
203                 sessionValues.addElement(new ValidValue("Y", "Yes"));
204                 sessionValues.addElement(new ValidValue("N", "No"));
205             }
206
207             return sessionValues;
208         }
209
210         return super.getValidValues(fieldName);
211     } /* getValidValues(String) */
212
213
214     /**
215      * Define the table and fields for this object
216      */

217     public void setupFields()
218             throws DBException {
219         setTargetTable("PTESTS");
220         setDescription("DBptests");
221         setCharset("ISO-8859-1");
222         addField("TestNumber", "auto-inc", 0, false, "testNumber");
223         addField("URLToTest", "text", 0, false, "urlToTest");
224         addField("Descrip", "varchar", 80, false, "descriptionOfTest");
225         addField("NormTime", "int", 0, true, "normalTime");
226         addField("WarnTime", "int", 0, true, "warningTime");
227         addField("MaxTime", "int", 0, true, "maxTime");
228         addField("LastTime", "int", 0, true, "lastRunTime");
229         addField("TestCount", "int", 0, true, "nofRuns");
230         addField("TotalTime", "int", 0, true, "totalTimeAllRuns");
231         addVirtualField("AverageTime", "int", 0, "avgTimeAllRuns");
232         addField("ExpectString", "text", 0, true, "expectText");
233         addField("SuccessfulTests", "int", 0, true, "successfulTests");
234         addVirtualField("FailedTests", "int", 0, "failedTests");
235         addField("LastTestSucceeded", "char", 1, true, "lastTestSucceeded");
236         addField("LastRun", "datetime", 0, true, "testLastRunOn");
237         addField("LastFailureReason", "text", 0, true, "reasonForLastFailure");
238         addField("HttpMethod", "char", 10, false, "httpMethod");
239         addField("GetSession", "char", 1, false, "getSession");
240         this.getJDBCMetaData().setAttribute("GetSession", "checkbox", "Y");
241         setStringFilter("URLToTest", "rawFilter");
242         setStringFilter("ExpectString", "rawFilter");
243         addKey("TestNumber");
244
245         /* setReadOnly("TestNumber");
246
247 setReadOnly("LastTime");
248
249 setReadOnly("SuccessfulTests");
250
251 setReadOnly("LastRun");
252
253 setReadOnly("LastTestSucceeded");
254
255 setReadOnly("TotalTime");
256
257 setReadOnly("TestCount"); */

258         setMultiValued("HttpMethod");
259         setMultiValued("GetSession");
260     } /* setupFields() */
261
262
263     /**
264      * Run the current test
265      *
266      * @param currentSessionId ?
267      * @return PerfTestResult
268      */

269     public PerfTestResult run(String JavaDoc currentSessionId)
270             throws DBException {
271         PerfTestResult myResult = new PerfTestResult();
272         URL JavaDoc myUrl = null;
273         HttpURLConnection JavaDoc c;
274         String JavaDoc reason = "";
275         boolean failed = false;
276         String JavaDoc urlString = ConfigManager.expandValue(getField("URLToTest"));
277
278         if (currentSessionId != null) {
279             try {
280                 URL JavaDoc myURL = new URL JavaDoc(urlString);
281                 String JavaDoc queryPart = StringUtil.notNull(myURL.getQuery());
282                 String JavaDoc pathPart = myURL.getPath();
283                 int port = myURL.getPort();
284                 String JavaDoc protocol = myURL.getProtocol();
285                 String JavaDoc hostPart = myURL.getHost();
286
287                 /*System.out.println("PATH:" + pathPart);
288
289 System.out.println("Query:" + queryPart);
290
291 System.out.println("Protocol:" + protocol);
292
293 System.out.println("Host:" + hostPart); */

294
295                 //System.exit(1);
296
urlString = protocol + "://" + hostPart + ":" + port +
297                         pathPart + ";jsessionid=" + currentSessionId;
298
299                 if (!queryPart.equals("")) {
300                     urlString = urlString + "?" + queryPart;
301                 }
302
303                 //System.out.println("New URL:" + urlString);
304
log.info("Session was established: new URL '" + urlString +
305                         "'");
306             } catch (MalformedURLException JavaDoc me) {
307                 throw new DBException(me);
308             }
309         }
310
311         long runTime = 0;
312         String JavaDoc encodedURL = null;
313
314         try {
315             encodedURL = urlString; //URLEncoder.encode(urlString);
316

317             if (encodedURL == null) {
318                 throw new IllegalArgumentException JavaDoc("Unable to encode URL '" +
319                         urlString + "'");
320             }
321
322             myUrl = new URL JavaDoc(encodedURL);
323
324             if (myUrl == null) {
325                 throw new IllegalArgumentException JavaDoc("Unable to encode URL '" +
326                         urlString + "'");
327             }
328         } catch (MalformedURLException JavaDoc m) {
329             m.printStackTrace(System.out);
330             throw new IllegalArgumentException JavaDoc("URL '" + urlString +
331                     "' is not valid.");
332         }
333         try {
334             c = (HttpURLConnection JavaDoc) myUrl.openConnection();
335
336             if (c == null) {
337                 throw new IllegalArgumentException JavaDoc("No connection established to '" + urlString + "'");
338             }
339
340             c.setDoOutput(true);
341             HttpURLConnection.setFollowRedirects(true);
342             c.setAllowUserInteraction(true);
343             c.setRequestMethod(getField("HttpMethod"));
344
345             /* Now listen for the answer */
346             boolean printme = false;
347             InputStream JavaDoc is = null;
348
349             try {
350                 is = c.getInputStream();
351             } catch (IOException JavaDoc ie) {
352                 is = c.getErrorStream();
353                 printme = true;
354
355                 if (is == null) {
356                     System.out.println("No input or error stream from URL '" +
357                             encodedURL + "'");
358                 } else {
359                     System.out.println("Got error stream");
360                 }
361                 try {
362                     int responseCode = c.getResponseCode();
363                     System.out.println("Response code:" + responseCode);
364                 } catch (Exception JavaDoc ee) {
365                     System.out.println("No response code available:" +
366                             ee.getMessage());
367                     ee.printStackTrace(System.out);
368                 }
369
370                 //System.out.println("Response code:" + c.getResponseCode());
371
//System.out.println("Response message:" + StringUtil.notNull(c.getResponseMessage()));
372
}
373             if (is == null) {
374                 throw new IllegalArgumentException JavaDoc("No input or error stream returned");
375             }
376
377             InputStreamReader JavaDoc dis = new InputStreamReader JavaDoc(is);
378             long startTime = System.currentTimeMillis();
379             URLReader ur = new URLReader(dis, getField("ExpectString"),
380                     printme);
381
382             if (getField("GetSession").equals("Y")) {
383                 ur.setRequireSession(true);
384             }
385
386             ur.start();
387
388             long maxMillis = 0;
389
390             try {
391                 maxMillis = new Long JavaDoc(getField("MaxTime")).longValue();
392             } catch (NumberFormatException JavaDoc ne) {
393                 maxMillis = 0;
394             }
395             if (maxMillis == 0) {
396                 maxMillis = 99999;
397             }
398
399             ur.join(maxMillis);
400
401             boolean success = ur.completedSuccessfully();
402             long endTime = System.currentTimeMillis();
403             runTime = endTime - startTime;
404             myResult.setRunTime(runTime);
405
406             Hashtable JavaDoc allUsers = ConfigManager.getCurrentLogins();
407             myResult.setCurrentUsers(allUsers.size());
408
409             if (success) {
410
411                 /* PerfTestStat myStat = new PerfTestStat();
412
413 myStat.setDBName(getDBName());
414
415 myStat.setField("UserCount", "" + allUsers.size());
416
417 myStat.setField("TestNumber", getField("TestNumber"));
418
419 myStat.setField("RunWhen", DateTime.getDateTimeForDB());
420
421 myStat.setField("RunTime", new Long(runTime).toString());
422
423 try {
424
425 myStat.add();
426
427 } catch (DBException de) {
428
429 log.error("Unable to log test run statistic:", de);
430
431 } */

432             }
433             if (getField("GetSession").equals("Y")) {
434                 currentSessionId = ur.getSessionId();
435                 myResult.setSessionId(currentSessionId);
436                 currentSessionId = myResult.getSessionId();
437                 log.info("Logged in with session id '" + currentSessionId +
438                         "'");
439
440                 if (currentSessionId == null) {
441                     reason = "No jsessionid (Session ID) found in output";
442                     failed = true;
443                 }
444             }
445             if (!success) {
446                 failed = true;
447                 reason = ur.getFailureReason();
448             }
449         } /* try */ catch (Exception JavaDoc io) {
450             log.error("I/O Error:", io);
451             io.printStackTrace(System.out);
452             reason = "I/O Error communicating with server:" + io.getMessage();
453             failed = true;
454         }
455         if (failed) {
456             setField("LastTestSucceeded", "N");
457             setField("LastFailureReason", reason);
458         } else {
459             setField("LastTestSucceeded", "Y");
460             addToField("SuccessfulTests", 1);
461         }
462
463         addToField("TestCount", 1);
464         addToField("TotalTime", runTime);
465         setField("LastTime", "" + runTime);
466         setField("LastRun", DateTime.getDateTimeForDB(this.getDataContext()));
467         setCheckZeroUpdate(false);
468         update();
469
470         /* Prepare result */
471         long lastTime = 0;
472         StringBuffer JavaDoc detailMessage = new StringBuffer JavaDoc();
473
474         if (getField("LastTestSucceeded").equals("N")) {
475             myResult.setFailureCount(1);
476             detailMessage.append("\nERROR: Test " + getField("TestNumber") +
477                     " (" + getField("Descrip") + ") for URL '" +
478                     getField("URLToTest") +
479                     "' failed. Reason reported was '" +
480                     getField("LastFailureReason") + "'\n");
481         } else {
482             lastTime = getFieldLong("LastTime");
483
484             if (lastTime > getFieldLong("WarnTime")) {
485                 myResult.setWarningCount(1);
486                 detailMessage.append("\nWARNING: Test " +
487                         getField("TestNumber") + " (" +
488                         getField("Descrip") + ") for URL '" +
489                         getField("URLToTest") +
490                         "' responded slower than it's set warning time of " +
491                         getField("WarnTime") +
492                         " milliseconds. It ran in " +
493                         getField("LastTime") +
494                         " milliseconds.\n");
495             } else if (lastTime > getFieldLong("NormTime")) {
496                 myResult.setCautionCount(1);
497                 detailMessage.append("\nCAUTION: Test " +
498                         getField("TestNumber") + " (" +
499                         getField("Descrip") + ") for URL '" +
500                         getField("URLToTest") +
501                         "' responded slower than it's set normal time of " +
502                         getField("NormTime") +
503                         " milliseconds. It ran in " +
504                         getField("LastTime") +
505                         " milliseconds.\n");
506             }
507         }
508
509         myResult.setMessage(detailMessage.toString());
510
511         return myResult;
512     } /* run() */
513
514
515     /**
516      * @param fieldName name of the field
517      * @param valueToAdd value for the field
518      * @throws DBException upon error
519      */

520     private void addToField(String JavaDoc fieldName, long valueToAdd)
521             throws DBException {
522         long currentValue = 0;
523
524         try {
525             currentValue = new Long JavaDoc(getField(fieldName)).longValue();
526         } catch (NumberFormatException JavaDoc ne) {
527             throw new DBException("Unable to add to field '" + fieldName +
528                     "', current value of '" +
529                     getField(fieldName) + "' is not a number.");
530         }
531
532         currentValue = currentValue + valueToAdd;
533         setField(fieldName, "" + currentValue);
534     } /* addToField(String, long) */
535
536
537     /**
538      * Run all defined tests
539      *
540      * @param dbName database context
541      * @param currentSessionId where to store the results
542      * @return PerfTestResult
543      * @throws DBException upon error
544      */

545     public static PerfTestResult runAll(String JavaDoc dbName, String JavaDoc currentSessionId)
546             throws DBException {
547         PerfTests tl = new PerfTests();
548         tl.setDataContext(dbName);
549
550         PerfTestResult overallResult = new PerfTestResult();
551         PerfTestResult oneResult = null;
552         PerfTests oneTest = null;
553
554         List JavaDoc list = tl.searchAndRetrieveList();
555         for (Iterator JavaDoc iterator = list.iterator(); iterator.hasNext();) {
556             oneTest = (PerfTests) iterator.next();
557             oneResult = oneTest.run(currentSessionId);
558             overallResult.add(oneResult);
559         }
560
561         return overallResult;
562     } /* runAll(String) */
563
564
565     /**
566      * Run all defined tests
567      *
568      * @param dbName database context
569      * @param setNumber the 'id' of the test set
570      * @param currentSessionId ?
571      * @return PerfTestResult
572      */

573     public static PerfTestResult runSet(String JavaDoc dbName, String JavaDoc setNumber,
574                                         String JavaDoc currentSessionId)
575             throws DBException {
576         PerfTestResult overallResult = new PerfTestResult();
577         PerfTestResult oneResult = null;
578         PerfTestSet ps = new PerfTestSet();
579         ps.setDataContext(dbName);
580         ps.setField("SetNumber", setNumber);
581         ps.retrieve();
582
583         PerfTestSetDet psd = new PerfTestSetDet();
584         psd.setDataContext(dbName);
585         psd.setField("SetNumber", setNumber);
586
587         PerfTestSetDet oneDet = null;
588         PerfTests oneTest = new PerfTests();
589         oneTest.setDataContext(dbName);
590
591         List JavaDoc list = psd.searchAndRetrieveList("SequenceNumber");
592         for (Iterator JavaDoc iterator = list.iterator(); iterator.hasNext();) {
593             oneDet = (PerfTestSetDet) iterator.next();
594             oneTest.setField("TestNumber", oneDet.getField("TestNumber"));
595             oneTest.retrieve();
596             oneResult = oneTest.run(currentSessionId);
597
598             if (currentSessionId == null) {
599                 currentSessionId = oneResult.getSessionId();
600                 overallResult.setSessionId(currentSessionId);
601                 log.info("Test " + oneDet.getField("TestNumber") +
602                         " logged in - session id now '" + currentSessionId +
603                         "'");
604             }
605
606             overallResult.add(oneResult);
607         }
608
609         return overallResult;
610     } /* runSet(String, String) */
611
612
613     /**
614      * Read from the specified URL, looking for the "ExpectString". If you find it,
615      * return true, if not - return false
616      *
617      * @param dis
618      * @throws DBException
619      * @throws IOException
620      * @return
621      */

622 // private boolean readFromStream(DataInputStream dis)
623
// throws DBException, IOException {
624
// boolean returnVal = false;
625
//
626
// if (dis == null) {
627
// throw new DBException("No connection to server:DataInputStream dis is null");
628
// }
629
//
630
// //System.out.println(myName + ":Bytes available from stream:"
631
// // + dis.available());
632
// int linesRead = 0;
633
//
634
// //System.out.println(myName + ":Reading line");
635
// String OneLine = dis.readLine();
636
//
637
// if (OneLine.indexOf(getField("ExpectString")) > 0) {
638
// returnVal = true;
639
// }
640
// //System.out.println("Read (initial) from server:" + OneLine);
641
// if (OneLine == null) {
642
// throw new DBException("Server never sent EOF");
643
// }
644
//
645
// String oneValue = ("");
646
// String oneKey = ("");
647
//
648
// while (OneLine != null) {
649
// if (OneLine.indexOf(getField("ExpectString")) > 0) {
650
// returnVal = true;
651
// }
652
// if (!OneLine.equals("")) {
653
// linesRead++;
654
// } /* if */
655
//
656
//
657
// OneLine = dis.readLine();
658
// } /* while */
659
//
660
//
661
// dis.close();
662
//
663
// //Log.log(myName, "Read " + linesRead + " lines from server", "");
664
// return returnVal;
665
// } /* readFromStream(DataInputStream) */
666

667
668 } /* PerfTests */
669
Popular Tags