KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ojb > performance > PerfMain


1 package org.apache.ojb.performance;
2
3 /* Copyright 2002-2005 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 import java.io.File JavaDoc;
19 import java.io.FileNotFoundException JavaDoc;
20 import java.io.FileOutputStream JavaDoc;
21 import java.io.PrintStream JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Collection JavaDoc;
24 import java.util.Collections JavaDoc;
25 import java.util.Comparator JavaDoc;
26 import java.util.Date JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.StringTokenizer JavaDoc;
32 import java.lang.reflect.Constructor JavaDoc;
33
34 import org.apache.commons.lang.SystemUtils;
35 import org.apache.commons.lang.exception.ExceptionUtils;
36 import org.apache.commons.lang.math.NumberUtils;
37
38 /**
39  * The OJB stress/performance test - a simple performance test application to
40  * run O/R mapper in a simulated single/multi-threaded environment.
41  *
42  * <p>
43  * <b>You have two possibilities to run this test:</b>
44  * </p>
45  * <p>
46  * - use the OJB build script and call
47  * <br/>
48  * <code>ant perf-test</code>
49  * </p>
50  * <p>
51  * - or for standalone use perform the test class by yourself
52  * <br/>
53  * <code>
54  * java -classpath CLASSPATH org.apache.ojb.performance.PerfMain
55  * </code>
56  * <br/>
57  * <code>
58  * [comma separated list of PerfTest implementation classes, no blanks!]
59  * </code>
60  * <br/>
61  * <code>
62  * [number of test loops, default '5']
63  * </code>
64  * <br/>
65  * <code>
66  * [number of threads, default '10']
67  * </code>
68  * <br/>
69  * <code>
70  * [number of insert/fetch/delete loops per thread, default '100']
71  * </code>
72  * <br/>
73  * <code>
74  * [boolean - run in stress mode if set true, run in performance mode if set false, default 'false']
75  * </code>
76  * <br/>
77  * <code>
78  * [boolean - if 'true' all log messages will be print, else only a test summary, default 'true']
79  * </code>
80  * </p>
81  * <p>
82  * For example:
83  * </p>
84  * <code>java -classpath CLASSPATH my.MyPerfTest,myMyPerfTest2 3 10 200 false true</code>
85  *
86  * @version $Id: PerfMain.java,v 1.9.2.7 2005/12/30 00:01:42 arminw Exp $
87  */

88 public class PerfMain
89 {
90     static final int TEST_INSERT = 0;
91     static final int TEST_FETCH = 1;
92     static final int TEST_FETCH_2 = 2;
93     static final int TEST_BY_IDENTITY = 3;
94     static final int TEST_UPDATE = 4;
95     static final int TEST_DELETE = 5;
96
97     static final short TIME_TOTAL = 0;
98     static final short TIME_INSERT = 1;
99     static final short TIME_FETCH = 2;
100     static final short TIME_FETCH_2 = 3;
101     static final short TIME_BY_IDENTITY = 4;
102     static final short TIME_UPDATE = 5;
103     static final short TIME_DELETE = 6;
104
105     /**
106      * The factor for get by Identity calls, e.g. 4 means handling 100 objects
107      * result in 100/4 getByIdentity calls.
108      */

109     protected static final int BY_IDENTITY_FACTOR = 4;
110     protected static final String JavaDoc EOL = SystemUtils.LINE_SEPARATOR;
111
112     /** iterations per thread */
113     private static int iterationsPerThread = 100;
114     /** number of concurrent threads */
115     private static int concurrentThreads = 10;
116     /** if false we use performance optimized delete/insert method */
117     private static boolean useStressMode = false;
118     /** number of test loops */
119     private static int testLoops = 5;
120     /** if false only a test summary will be print*/
121     private static boolean logAll = true;
122
123     private HashMap JavaDoc resultMap;
124     private HashMap JavaDoc exceptionMap;
125     private static Printer printer;
126
127
128     public static void main(String JavaDoc[] args)
129     {
130         PerfMain main = new PerfMain();
131         try
132         {
133             long peroid = System.currentTimeMillis();
134             // start the test
135
main.startPerfTest(args);
136             // print the test results
137
main.printResult();
138             peroid = System.currentTimeMillis() - peroid;
139             if(logAll) printer().println();
140             if(logAll) printer().println("PerfTest takes " + peroid / 1000 + " [sec]");
141         }
142         catch (Exception JavaDoc e)
143         {
144             e.printStackTrace();
145         }
146         System.exit(0);
147     }
148
149     public PerfMain()
150     {
151         this.resultMap = new HashMap JavaDoc();
152         this.exceptionMap = new HashMap JavaDoc();
153     }
154
155     public static Printer printer()
156     {
157         if(printer == null)
158         {
159             printer = new Printer();
160         }
161         return printer;
162     }
163
164     /** Call this to begin the performance test. */
165     public void startPerfTest(String JavaDoc[] args) throws Exception JavaDoc
166     {
167         ArrayList JavaDoc testList = null;
168         try
169         {
170             // comma separated list of the PerfTest implementation classes
171
if (args.length > 0)
172             {
173                 StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(args[0], ",");
174                 testList = new ArrayList JavaDoc();
175                 while (tok.hasMoreTokens())
176                 {
177                     testList.add(tok.nextToken().trim());
178                 }
179             }
180             else
181             {
182                 throw new IllegalArgumentException JavaDoc("No test handles found!");
183             }
184             // number of test loops
185
if (args.length > 1)
186             {
187                 testLoops = args.length > 1 ? Integer.parseInt(args[1]) : 1;
188             }
189             // number of threads
190
if (args.length > 2)
191             {
192                 concurrentThreads = Integer.parseInt(args[2]);
193             }
194             // number of insert/fetch/delete loops per thread
195
if (args.length > 3)
196             {
197                 iterationsPerThread = Integer.parseInt(args[3]);
198             }
199             // run in stress mode
200
if (args.length > 4)
201             {
202                 useStressMode = Boolean.valueOf(args[4]).booleanValue();
203             }
204             // log mode
205
if (args.length > 5)
206             {
207                 logAll = Boolean.valueOf(args[5]).booleanValue();
208             }
209         }
210         catch (Exception JavaDoc e)
211         {
212             e.printStackTrace();
213             System.err.println();
214             System.err.println("Usage of PerfMain:" +
215                     "java -classpath CLASSPATH org.apache.ojb.performance.PerfMain" +
216                     " [comma separated list of PerfTest implementation classes]" +
217                     " [number of test loops]" +
218                     " [number of threads]" +
219                     " [number of insert/fetch/delete loops per thread]" +
220                     " [boolean - run in stress mode]" +
221                     " [boolean - if 'true' detailed log messages will be print]");
222             System.err.println();
223             System.err.println("Example: java -classpath" +
224                     " CLASSPATH org.apache.ojb.performance.PerfMain org.MyPerfTest 3 10 500 false");
225         }
226
227         if(logAll) printer().println(" " +
228                 EOL + "Start OJB performance-test framework - running " + testLoops + " loops" +
229                 EOL + "-------------------------------------------------------");
230
231         PerfRunner test;
232         for (int i = 0; i < testLoops; i++)
233         {
234             Runtime JavaDoc rt = Runtime.getRuntime();
235             long freeMem;
236             if(logAll) printer().println(" Loop " + (i + 1));
237
238             if(i%2 == 0)
239             {
240                 for(int j = 0; j < testList.size(); j++)
241                 {
242                     String JavaDoc perfTest = (String JavaDoc) testList.get(j);
243                     Class JavaDoc testHandle = Class.forName(perfTest);
244                     test = new PerfRunner(testHandle);
245                     test.registerPerfMain(this);
246
247                     rt.gc();
248                     Thread.sleep(300);
249                     rt.freeMemory();
250                     rt.gc();
251                     Thread.sleep(100);
252                     freeMem = rt.freeMemory();
253                     test.performTest();
254                     freeMem = (freeMem - rt.freeMemory()) / 1024;
255                     if(logAll) printer().println(" allocated memory=" + freeMem + "kb");
256                     // rt.gc();
257
}
258             }
259             else
260             {
261                 for(int j = (testList.size() - 1); j >= 0; j--)
262                 {
263                     String JavaDoc perfTest = (String JavaDoc) testList.get(j);
264                     Class JavaDoc testHandle = Class.forName(perfTest);
265                     test = new PerfRunner(testHandle);
266                     test.registerPerfMain(this);
267
268                     rt.gc();
269                     Thread.sleep(300);
270                     rt.freeMemory();
271                     rt.gc();
272                     Thread.sleep(100);
273                     freeMem = rt.freeMemory();
274                     test.performTest();
275                     freeMem = (freeMem - rt.freeMemory()) / 1024;
276                     if(logAll) printer().println(" allocated memory: " + freeMem + " kb");
277                     // rt.gc();
278
}
279             }
280         }
281     }
282
283     public void printResult()
284     {
285         printer().println();
286         if (!getExceptionMap().isEmpty())
287         {
288             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
289             buf.append(EOL).append("Failures occured, test not valid:").append(EOL);
290             Iterator JavaDoc it = getExceptionMap().entrySet().iterator();
291             while (it.hasNext())
292             {
293                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
294                 buf.append("Failure cause by ").append(entry.getKey());
295                 if(entry.getValue() != null)
296                 {
297                     Throwable JavaDoc ex = ExceptionUtils.getRootCause((Exception JavaDoc) entry.getValue());
298                     if(ex == null) ex = (Exception JavaDoc) entry.getValue();
299                     buf.append(EOL).append("Exception was: ").append(EOL).append(ExceptionUtils.getStackTrace(ex));
300                 }
301                 buf.append(EOL);
302             }
303             printer().println(buf.toString());
304         }
305         printer().println(buildTestSummary(prepareTestResults()));
306     }
307
308     private PerfResult[] prepareTestResults()
309     {
310         List JavaDoc tmp = new ArrayList JavaDoc(resultMap.values());
311         Collections.sort(tmp, new Comparator JavaDoc()
312         {
313             public int compare(Object JavaDoc o1, Object JavaDoc o2)
314             {
315                 PerfResult r1 = (PerfResult) o1;
316                 PerfResult r2 = (PerfResult) o2;
317                 return new Long JavaDoc(r1.getTotalTime()).compareTo(new Long JavaDoc(r2.getTotalTime()));
318             }
319         });
320
321         PerfResult[] results = (PerfResult[]) tmp.toArray(new PerfResult[tmp.size()]);
322         long[][] calibration = new long[6][results.length];
323         for(int k = 0; k < 6; k++)
324         {
325             for(int i = 0; i < results.length; i++)
326             {
327                 PerfResult result = results[i];
328                 if(k==TEST_INSERT) calibration[TEST_INSERT][i] = result.getInsertPeriod();
329                 if(k==TEST_FETCH) calibration[TEST_FETCH][i] = result.getFetchPeriod();
330                 if(k==TEST_FETCH_2) calibration[TEST_FETCH_2][i] = result.getFetchSecondPeriod();
331                 if(k==TEST_BY_IDENTITY) calibration[TEST_BY_IDENTITY][i] = result.getByIdentityPeriod();
332                 if(k==TEST_UPDATE) calibration[TEST_UPDATE][i] = result.getUpdatePeriod();
333                 if(k==TEST_DELETE) calibration[TEST_DELETE][i] = result.getDeletePeriod();
334             }
335         }
336
337         for(int k = 0; k < 6; k++)
338         {
339             if(k==TEST_INSERT)
340             {
341                 long[] resultArray = calibration[TEST_INSERT];
342                 long minimum = NumberUtils.min(resultArray);
343                 for(int i = 0; i < results.length; i++)
344                 {
345                     results[i].setInsertMinimun(minimum);
346                 }
347             }
348             if(k==TEST_FETCH)
349             {
350                 long[] resultArray = calibration[TEST_FETCH];
351                 long minimum = NumberUtils.min(resultArray);
352                 for(int i = 0; i < results.length; i++)
353                 {
354                     results[i].setFetchMinimun(minimum);
355                 }
356             }
357             if(k==TEST_FETCH_2)
358             {
359                 long[] resultArray = calibration[TEST_FETCH_2];
360                 long minimum = NumberUtils.min(resultArray);
361                 for(int i = 0; i < results.length; i++)
362                 {
363                     results[i].setFetchSecondMinimun(minimum);
364                 }
365             }
366             if(k==TEST_BY_IDENTITY)
367             {
368                 long[] resultArray = calibration[TEST_BY_IDENTITY];
369                 long minimum = NumberUtils.min(resultArray);
370                 for(int i = 0; i < results.length; i++)
371                 {
372                     results[i].setByIdentityMinimun(minimum);
373                 }
374             }
375             if(k==TEST_UPDATE)
376             {
377                 long[] resultArray = calibration[TEST_UPDATE];
378                 long minimum = NumberUtils.min(resultArray);
379                 for(int i = 0; i < results.length; i++)
380                 {
381                     results[i].setUpdateMinimun(minimum);
382                 }
383             }
384             if(k==TEST_DELETE)
385             {
386                 long[] resultArray = calibration[TEST_DELETE];
387                 long minimum = NumberUtils.min(resultArray);
388                 for(int i = 0; i < results.length; i++)
389                 {
390                     results[i].setDeleteMinimun(minimum);
391                 }
392             }
393         }
394
395         return results;
396     }
397
398     private String JavaDoc buildTestSummary(PerfResult[] results)
399     {
400         int columnLength = 12;
401         int columnNumbers = 8;
402         final String JavaDoc indent = " ";
403
404         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
405         // table header
406
buf.append(EOL);
407         for (int i = 0; i < columnNumbers; i++)
408         {
409             buf.append(alignToLength(columnLength, "="));
410         }
411         buf.append(EOL);
412         buf.append(alignToLength(columnLength, " "));
413         String JavaDoc headline = "OJB PERFORMANCE TEST SUMMARY, " + new Date JavaDoc();
414         buf.append(alignLeft(headline, columnLength));
415         buf.append(EOL);
416         for (int i = 0; i < columnNumbers; i++)
417         {
418             buf.append(alignToLength(columnLength, "-"));
419         }
420         buf.append(EOL);
421         buf.append(indent).append(PerfMain.getConcurrentThreads());
422         buf.append(" concurrent threads, handle ");
423         buf.append(PerfMain.getIterationsPerThread());
424         buf.append(" objects per thread");
425         buf.append(EOL).append(indent).append(iterationsPerThread).append(" INSERT operations per test instance");
426         buf.append(EOL).append(indent + "FETCH collection of ").append(iterationsPerThread).append(" objects per test instance");
427         buf.append(EOL).append(indent + "Repeat FETCH collection of ").append(iterationsPerThread).append(" objects per test instance");
428         int byIdCalls = (iterationsPerThread / PerfMain.BY_IDENTITY_FACTOR);
429         buf.append(EOL).append(indent).append((byIdCalls == 0 ? 1: byIdCalls)).append(" get by Identity calls per test instance");
430         buf.append(EOL).append(indent).append(iterationsPerThread).append(" UPDATE operations per test instance");
431         buf.append(EOL).append(indent).append(iterationsPerThread).append(" DELETE operations per test instance");
432         buf.append(EOL).append(indent);
433         buf.append("- ").append(!(isUseStressMode()) ? "performance mode" : "stress mode");
434         buf.append(" - results per test instance (average)");
435         buf.append(EOL);
436         for (int i = 0; i < columnNumbers; i++)
437         {
438             buf.append(alignToLength(columnLength, "="));
439         }
440         buf.append(EOL);
441         buf.append(alignLeft("API", columnLength));
442         //buf.append(alignLeft("Period", columnLength, " "));
443
//buf.append(alignLeft("Total", columnLength, " "));
444
buf.append(alignLeft("Total", columnLength));
445
446         buf.append(alignLeft("Insert", columnLength));
447         //buf.append(alignToLength(columnLength, " "));
448
buf.append(alignLeft("Fetch", columnLength));
449         //buf.append(alignToLength(columnLength, " "));
450
buf.append(alignLeft("Fetch 2", columnLength));
451         //buf.append(alignToLength(columnLength, " "));
452
buf.append(alignLeft("by Id", columnLength));
453         //buf.append(alignToLength(columnLength, " "));
454
buf.append(alignLeft("Update", columnLength));
455         //buf.append(alignToLength(columnLength, " "));
456
buf.append(alignLeft("Delete", columnLength));
457         //buf.append(alignToLength(columnLength, " "));
458

459         buf.append(EOL);
460         buf.append(alignToLength(columnLength, " "));
461         //buf.append(alignLeft("[sec]", columnLength, " "));
462
//buf.append(alignLeft("[sec]", columnLength, " "));
463
buf.append(alignLeft("[%]", columnLength));
464
465         buf.append(alignLeft("[msec]", columnLength));
466         //buf.append(alignToLength(columnLength, " "));
467
buf.append(alignLeft("[msec]", columnLength));
468         //buf.append(alignToLength(columnLength, " "));
469
buf.append(alignLeft("[msec]", columnLength));
470         //buf.append(alignToLength(columnLength, " "));
471
buf.append(alignLeft("[msec]", columnLength));
472         //buf.append(alignToLength(columnLength, " "));
473
buf.append(alignLeft("[msec]", columnLength));
474         //buf.append(alignToLength(columnLength, " "));
475
buf.append(alignLeft("[msec]", columnLength));
476         //buf.append(alignToLength(columnLength, " "));
477
buf.append(EOL);
478         for (int i = 0; i < columnNumbers; i++)
479         {
480             buf.append(alignToLength(columnLength, "-"));
481         }
482
483         // fill table
484
int counter = 0;
485         double calibrationMark = 0;
486         for(int i = 0; i < results.length; i++)
487         {
488             PerfResult result = results[i];
489             buf.append(EOL);
490             if(counter == 0)
491             {
492                 // the first one is the fastest
493
calibrationMark = result.getTotalTime();
494             }
495             //double period = (double) result.getTestPeriod() / 1000;
496
//double total = (double) Math.round((double) result.getTotalTime()) / 1000;
497
long percent = Math.round((result.getTotalTime() / calibrationMark) * 100);
498
499             buf.append(alignLeft(result.getTestName(), columnLength));
500             //buf.append(alignLeft(""+period, columnLength, " "));
501
//buf.append(alignLeft(""+total, columnLength, " "));
502
buf.append(alignLeft(""+percent, columnLength));
503
504             buf.append(alignLeft(result.getInsertResult()+result.getInsertResultPercent(), columnLength));
505             //buf.append(alignLeft(result.getInsertResultPercent(), columnLength, " "));
506
buf.append(alignLeft(result.getFetchResult()+result.getFetchResultPercent(), columnLength));
507             //buf.append(alignLeft(result.getFetchResultPercent(), columnLength, " "));
508
buf.append(alignLeft(result.getFetchSecondResult()+result.getFetchSecondResultPercent(), columnLength));
509             //buf.append(alignLeft(result.getFetchSecondResultPercent(), columnLength, " "));
510
buf.append(alignLeft(result.getByIdentityResult()+result.getByIdentityResultPercent(), columnLength));
511             //buf.append(alignLeft(result.getByIdentityResultPercent(), columnLength, " "));
512
buf.append(alignLeft(result.getUpdateResult()+result.getUpdateResultPercent(), columnLength));
513             //buf.append(alignLeft(result.getUpdateResultPercent(), columnLength, " "));
514
buf.append(alignLeft(result.getDeleteResult()+result.getDeleteResultPercent(), columnLength));
515             //buf.append(alignLeft(result.getDeleteResultPercent(), columnLength, " "));
516
counter++;
517         }
518         buf.append(EOL);
519         for (int i = 0; i < columnNumbers; i++)
520         {
521             buf.append(alignToLength(columnLength, "="));
522         }
523 // if(failures.size() > 0)
524
// {
525
// buf.append(EOL + "Failures detected:" + EOL);
526
// for(int i = 0; i < failures.size(); i++)
527
// {
528
// PerfResult perfResult = (PerfResult) failures.get(i);
529
// buf.append("name=" + perfResult.getTestName() + ", isValid=" +perfResult.isValid() + EOL);
530
// }
531
// }
532
return buf.toString();
533     }
534
535 // private String alignRight(String target, int length)
536
// {
537
// return alignToLength(target, length, " ", true);
538
// }
539

540     private String JavaDoc alignLeft(String JavaDoc target, int length)
541     {
542         return alignToLength(target, length, " ", false);
543     }
544
545     private String JavaDoc alignToLength(int length, String JavaDoc fillCharacter)
546     {
547         return alignToLength("", length, fillCharacter, false);
548     }
549
550     private String JavaDoc alignToLength(String JavaDoc target, int length, String JavaDoc fillCharacter, boolean right)
551     {
552         if (target.length() > length) return target;
553
554         int count = length - target.length();
555         String JavaDoc blanks = "";
556         for (int i = 0; i < count; i++)
557         {
558             blanks += fillCharacter;
559         }
560         return right ? blanks + target : target + blanks;
561     }
562
563     /**
564      * testTimes[0] startTime/test length
565      * testTimes[1] inserting times
566      * testTimes[2] fetching times
567      * testTimes[3] fetching repeat times
568      * testTimes[4] get by Identity times
569      * testTimes[5] updating times
570      * testTimes[6] deleting times
571      */

572     public synchronized void addPeriodResult(String JavaDoc testName, long[] resultArr)
573     {
574         PerfResult result = (PerfResult) resultMap.get(testName);
575         if (result == null)
576         {
577             result = new PerfResult();
578             result.setTestName(testName);
579             result.setStressMode(isUseStressMode());
580             result.setIterationsPerThread(getIterationsPerThread());
581             result.setNumberOfThreads(getConcurrentThreads());
582             result.setTestLoops(getTestLoops());
583             resultMap.put(testName, result);
584
585         }
586         result.addTestPeriod(resultArr[TIME_TOTAL]);
587         result.addInsertPeriod(resultArr[TIME_INSERT]);
588         result.addFetchPeriod(resultArr[TIME_FETCH]);
589         result.addFetchSecondPeriod(resultArr[TIME_FETCH_2]);
590         result.addByIdentityPeriod(resultArr[TIME_BY_IDENTITY]);
591         result.addUpdatePeriod(resultArr[TIME_UPDATE]);
592         result.addDeletePeriod(resultArr[TIME_DELETE]);
593
594         if(logAll)
595         {
596             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
597             buf.append(" Test '").append(result.getTestName()).append("' [ms]")
598                 .append(": testPeriod=").append(resultArr[0]/getConcurrentThreads())
599                 .append(" insert=").append(resultArr[1]/getConcurrentThreads())
600                 .append(" read=").append(resultArr[2]/getConcurrentThreads())
601                 .append(" read2=").append(resultArr[3]/getConcurrentThreads())
602                 .append(" byIdentity=").append(resultArr[4]/getConcurrentThreads())
603                 .append(" update=").append(resultArr[5]/getConcurrentThreads())
604                 .append(" delete=").append(resultArr[6]/getConcurrentThreads());
605             printer().print(buf.toString());
606         }
607         else
608         {
609             printer().print(".");
610         }
611     }
612
613     public synchronized void addConsistentResult(String JavaDoc testName, int objectsBefore, int objectsAfter)
614     {
615         ConsistentEntry ce = new ConsistentEntry(objectsBefore, objectsAfter);
616         PerfResult result = (PerfResult) resultMap.get(testName);
617         if(objectsBefore != objectsAfter)
618         {
619             try
620             {
621                 throw new Exception JavaDoc("Wrong object count, before=" + objectsBefore + ", after=" + objectsAfter);
622             }
623             catch(Exception JavaDoc e)
624             {
625                 registerException(testName, e);
626             }
627         }
628         result.addConsistentEntry(ce);
629     }
630
631     public synchronized void registerException(String JavaDoc causer, Exception JavaDoc e)
632     {
633         exceptionMap.put(causer, e);
634     }
635
636     public Map JavaDoc getExceptionMap()
637     {
638         return exceptionMap;
639     }
640
641     public Collection JavaDoc getResultList()
642     {
643         return resultMap.values();
644     }
645
646     public static int getIterationsPerThread()
647     {
648         return iterationsPerThread;
649     }
650
651     public static int getConcurrentThreads()
652     {
653         return concurrentThreads;
654     }
655
656     public static boolean isUseStressMode()
657     {
658         return useStressMode;
659     }
660
661     public static int getTestLoops()
662     {
663         return testLoops;
664     }
665
666
667     Object JavaDoc newInstance(Class JavaDoc target, Class JavaDoc argType, Object JavaDoc argInstance)
668     {
669         try
670         {
671             Class JavaDoc[] types = new Class JavaDoc[]{argType};
672             Object JavaDoc[] args = new Object JavaDoc[]{argInstance};
673             Constructor JavaDoc con = target.getConstructor(types);
674             return con.newInstance(args);
675         }
676         catch(Exception JavaDoc e)
677         {
678             e.printStackTrace();
679             throw new RuntimeException JavaDoc("Can't create instance for class "
680                     + target + "using constructor argument " + argType + ", message is " + e.getMessage());
681         }
682     }
683
684
685     //================================================================
686
// inner class
687
//================================================================
688
static class PerfResult
689     {
690         private String JavaDoc testName;
691         private long testPeriod;
692         private boolean stressMode;
693
694         private int testLoops;
695         private int numberOfThreads;
696         private int iterationsPerThread;
697
698         private long insertPeriod;
699         private long insertMinimun;
700         private long fetchPeriod;
701         private long fetchMinimun;
702         private long fetchSecondPeriod;
703         private long fetchSecondMinimun;
704         private long byIdentityPeriod;
705         private long byIdentityMinimun;
706         private long updatePeriod;
707         private long updateMinimun;
708         private long deletePeriod;
709         private long deleteMinimun;
710
711         private boolean valid;
712
713         private List JavaDoc consistentList;
714
715         public PerfResult()
716         {
717             setValid(true);
718             this.consistentList = new ArrayList JavaDoc();
719         }
720
721         public String JavaDoc toString()
722         {
723             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
724             buf.append(EOL).append("[").append(this.getClass().getName());
725             buf.append(EOL).append("testName=").append(testName);
726             buf.append(EOL).append("testPeriod=").append(testPeriod);
727             buf.append(EOL).append("testLoops=").append(testLoops);
728             buf.append(EOL).append("numberOfThreads=").append(numberOfThreads);
729             buf.append(EOL).append("iterationsPerThread=").append(iterationsPerThread);
730             buf.append(EOL).append("isValid=").append(isValid());
731             buf.append(EOL).append("insertPeriod=").append(getInsertPeriod());
732             buf.append(EOL).append("fetchPeriod=").append(getFetchPeriod());
733             buf.append(EOL).append("fetchSecondPeriod=").append(getFetchSecondPeriod());
734             buf.append(EOL).append("byIdentity=").append(getByIdentityPeriod());
735             buf.append(EOL).append("deletePeriod=").append(getDeletePeriod());
736             buf.append(EOL).append("consistentList: ").append(consistentList);
737             buf.append("]");
738             return buf.toString();
739         }
740
741         public void addConsistentEntry(ConsistentEntry entry)
742         {
743             this.consistentList.add(entry);
744             valid = valid && entry.isPassed();
745         }
746
747         public boolean isStressMode()
748         {
749             return stressMode;
750         }
751
752         public void setStressMode(boolean stressMode)
753         {
754             this.stressMode = stressMode;
755         }
756
757         public boolean isValid()
758         {
759             return valid;
760         }
761
762         public void setValid(boolean valid)
763         {
764             this.valid = valid;
765         }
766
767         public String JavaDoc getTestName()
768         {
769             return testName;
770         }
771
772         public void setTestName(String JavaDoc testName)
773         {
774             this.testName = testName;
775         }
776
777         public long getTestPeriod()
778         {
779             return testPeriod;
780         }
781
782         public synchronized void addTestPeriod(long aTestPeriod)
783         {
784             this.testPeriod += aTestPeriod;
785         }
786
787         public int getTestLoops()
788         {
789             return testLoops;
790         }
791
792         public void setTestLoops(int testLoops)
793         {
794             this.testLoops = testLoops;
795         }
796
797         public int getNumberOfThreads()
798         {
799             return numberOfThreads;
800         }
801
802         public void setNumberOfThreads(int numberOfThreads)
803         {
804             this.numberOfThreads = numberOfThreads;
805         }
806
807         public int getIterationsPerThread()
808         {
809             return iterationsPerThread;
810         }
811
812         public void setIterationsPerThread(int numberOfObjects)
813         {
814             this.iterationsPerThread = numberOfObjects;
815         }
816
817         public long getTotalTime()
818         {
819             long result = ((insertPeriod + fetchPeriod + updatePeriod + deletePeriod) / getTestLoops()) / getNumberOfThreads();
820             return result > 0 ? result : 1;
821         }
822
823         public long getInsertPeriod()
824         {
825             return (insertPeriod / getTestLoops()) / getNumberOfThreads();
826         }
827
828         public synchronized void addInsertPeriod(long anInsertPeriod)
829         {
830             this.insertPeriod += anInsertPeriod;
831         }
832
833         public long getFetchPeriod()
834         {
835             return (fetchPeriod / getTestLoops()) / getNumberOfThreads();
836         }
837
838         public synchronized void addFetchPeriod(long aFetchPeriod)
839         {
840             this.fetchPeriod += aFetchPeriod;
841         }
842
843         public long getFetchSecondPeriod()
844         {
845             return (fetchSecondPeriod / getTestLoops()) / getNumberOfThreads();
846         }
847
848         public synchronized void addFetchSecondPeriod(long secondPeriod)
849         {
850             this.fetchSecondPeriod += secondPeriod;
851         }
852
853         public long getByIdentityPeriod()
854         {
855             return (byIdentityPeriod / getTestLoops()) / getNumberOfThreads();
856         }
857
858         public synchronized void addByIdentityPeriod(long byIdentityPeriod)
859         {
860             this.byIdentityPeriod += byIdentityPeriod;
861         }
862
863         public long getUpdatePeriod()
864         {
865             return (updatePeriod / getTestLoops()) / getNumberOfThreads();
866         }
867
868         public synchronized void addUpdatePeriod(long aUpdatePeriod)
869         {
870             this.updatePeriod += aUpdatePeriod;
871         }
872
873         public long getDeletePeriod()
874         {
875             return (deletePeriod / getTestLoops()) / getNumberOfThreads();
876         }
877
878         public synchronized void addDeletePeriod(long aDeletePeriod)
879         {
880             this.deletePeriod += aDeletePeriod;
881         }
882
883
884
885         public void setInsertMinimun(long insertMinimun)
886         {
887             this.insertMinimun = insertMinimun > 1 ? insertMinimun : 1;
888         }
889
890         public void setFetchMinimun(long fetchMinimun)
891         {
892             this.fetchMinimun = fetchMinimun > 1 ? fetchMinimun : 1;
893         }
894
895         public void setFetchSecondMinimun(long fetchSecondMinimun)
896         {
897             this.fetchSecondMinimun = fetchSecondMinimun > 1 ? fetchSecondMinimun : 1;
898         }
899
900         public void setByIdentityMinimun(long byIdentityMinimun)
901         {
902             this.byIdentityMinimun = byIdentityMinimun > 1 ? byIdentityMinimun : 1;
903         }
904
905         public void setUpdateMinimun(long updateMinimun)
906         {
907             this.updateMinimun = updateMinimun > 1 ? updateMinimun : 1;
908         }
909
910         public void setDeleteMinimun(long deleteMinimun)
911         {
912             this.deleteMinimun = deleteMinimun > 1 ? deleteMinimun : 1;
913         }
914
915
916
917         public String JavaDoc getInsertResult()
918         {
919             long result = getInsertPeriod();
920             return "" + result;
921         }
922
923         public String JavaDoc getFetchResult()
924         {
925             long result = getFetchPeriod();
926             return "" + result;
927         }
928
929         public String JavaDoc getFetchSecondResult()
930         {
931             long result = getFetchSecondPeriod();
932             return "" + result;
933         }
934
935         public String JavaDoc getByIdentityResult()
936         {
937             long result = getByIdentityPeriod();
938             return "" + result;
939         }
940
941         public String JavaDoc getUpdateResult()
942         {
943             long result = getUpdatePeriod();
944             return "" + result;
945         }
946
947         public String JavaDoc getDeleteResult()
948         {
949             long result = getDeletePeriod();
950             return "" + result;
951         }
952
953
954
955
956         public String JavaDoc getInsertResultPercent()
957         {
958             long result = getInsertPeriod();
959             return "(" + (int) ((result * 100)/insertMinimun) + "%)";
960         }
961
962         public String JavaDoc getFetchResultPercent()
963         {
964             long result = getFetchPeriod();
965             return "(" + (int) ((result * 100)/fetchMinimun) + "%)";
966         }
967
968         public String JavaDoc getFetchSecondResultPercent()
969         {
970             long result = getFetchSecondPeriod();
971             return "(" + (int) ((result * 100)/fetchSecondMinimun) + "%)";
972         }
973
974         public String JavaDoc getByIdentityResultPercent()
975         {
976             long result = getByIdentityPeriod();
977             return "(" + (int) ((result * 100)/byIdentityMinimun) + "%)";
978         }
979
980         public String JavaDoc getUpdateResultPercent()
981         {
982             long result = getUpdatePeriod();
983             return "(" + (int) ((result * 100)/updateMinimun) + "%)";
984         }
985
986         public String JavaDoc getDeleteResultPercent()
987         {
988             long result = getDeletePeriod();
989             return "(" + (int) ((result * 100)/deleteMinimun) + "%)";
990         }
991     }
992
993     //================================================================
994
// inner class
995
//================================================================
996
static class ConsistentEntry
997     {
998         private int objectsBefore;
999         private int objectsAfter;
1000
1001        public ConsistentEntry(int objectsBefore, int objectsAfter)
1002        {
1003            this.objectsBefore = objectsBefore;
1004            this.objectsAfter = objectsAfter;
1005        }
1006
1007        public int getObjectsBefore()
1008        {
1009            return objectsBefore;
1010        }
1011
1012        public int getObjectsAfter()
1013        {
1014            return objectsAfter;
1015        }
1016
1017        public boolean isPassed()
1018        {
1019            return objectsBefore == objectsAfter;
1020        }
1021
1022        public String JavaDoc toString()
1023        {
1024            StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
1025            buf.append("[").append(this.getClass().getName())
1026                    .append(": objectsBefore=")
1027                    .append(getObjectsBefore())
1028                    .append(" objectsAfter=")
1029                    .append(objectsAfter)
1030                    .append(" isPassed=")
1031                    .append(isPassed());
1032            return buf.toString();
1033        }
1034    }
1035
1036    static class Printer
1037    {
1038        PrintStream JavaDoc console;
1039        PrintStream JavaDoc file;
1040
1041        public Printer()
1042        {
1043            console = System.out;
1044            try
1045            {
1046                file = new PrintStream JavaDoc(new FileOutputStream JavaDoc(new File JavaDoc("OJB-Performance-Result.txt")));
1047            }
1048            catch(FileNotFoundException JavaDoc e)
1049            {
1050                e.printStackTrace();
1051            }
1052        }
1053
1054        void print(String JavaDoc str)
1055        {
1056            console.print(str);
1057            if(file != null) file.print(str);
1058        }
1059
1060        void print(String JavaDoc str, boolean consoleOnly)
1061        {
1062            console.print(str);
1063            if(file != null && !consoleOnly) file.print(str);
1064        }
1065
1066        void println(String JavaDoc str)
1067        {
1068            console.println(str);
1069            if(file != null) file.println(str);
1070        }
1071
1072        void println()
1073        {
1074            print("");
1075        }
1076    }
1077}
1078
Popular Tags