KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > speedo > j2eedo > TestJ2eedoApplication


1 /*
2  * Speedo: an implementation of JDO compliant personality on top of JORM
3  * generic I/O sub-system. Copyright (C) 2001-2004 France Telecom R&D
4  *
5  * This library is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU Lesser General Public License as published by the
7  * Free Software Foundation; either version 2 of the License, or (at your
8  * option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
13  * for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public License
16  * along with this library; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  *
19  * Release: 1.0
20  *
21  * Created on 2004-03-04 @author fmillevi@yahoo.com
22  *
23  */

24 package org.objectweb.speedo.j2eedo;
25
26 import java.io.BufferedReader JavaDoc;
27 import java.io.PrintWriter JavaDoc;
28 import java.io.StringReader JavaDoc;
29 import java.io.StringWriter JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.Collections JavaDoc;
32 import java.util.HashMap JavaDoc;
33 import java.util.Hashtable JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.List JavaDoc;
36
37 import javax.jdo.JDOException;
38 import javax.jdo.JDOFatalException;
39 import javax.jdo.PersistenceManager;
40
41 import org.objectweb.speedo.SpeedoTestHelper;
42 import org.objectweb.speedo.j2eedo.bo.DatabaseImpl;
43 import org.objectweb.speedo.j2eedo.common.PMHolder;
44 import org.objectweb.speedo.j2eedo.common.TraceTime;
45 import org.objectweb.util.monolog.Monolog;
46 import org.objectweb.util.monolog.api.BasicLevel;
47
48 /**
49  * This class implements Junit test case. All the defined tests are launched in
50  * a standalone mode (it means test performing without an J2EE deployement)
51  *
52  * @author fmillevi@yahoo.com
53  */

54 public class TestJ2eedoApplication extends SpeedoTestHelper {
55
56     /**
57      * define the application prefix parameters <code>JEEDO_LOG_NAME</code>
58      */

59     public final static String JavaDoc JEEDO_LOG_NAME =
60         org.objectweb.speedo.SpeedoTestHelper.LOG_NAME + ".j2eedo";
61
62     protected final String JavaDoc SIMPLETEST = getLoggerName() + ".simpleTest";
63     protected final String JavaDoc THREAD = getLoggerName() + ".thread";
64     protected final String JavaDoc LOOP = getLoggerName() + ".loop";
65     protected final String JavaDoc TIMEOUT = getLoggerName() + ".timeout";
66     protected final String JavaDoc NBOFREAD = getLoggerName() + ".read";
67     protected final String JavaDoc NBOFWRITE = getLoggerName() + ".write";
68
69     protected boolean simpleTestOnly = false;
70     protected int nbThread = -1;
71     protected int nbTx = -1;
72     protected long timeout = -1;
73     protected int nbOfRead = -1;
74     protected int nbOfWrite = -1;
75
76     protected List JavaDoc methodsList = null;
77
78     private static boolean dataReset = false;
79
80     /**
81      * Sets up the test fixture. (Called before every test case method.) This
82      * method
83      * <ul>
84      * <li>registers each action,</li>
85      * <li>Set the default action list method</li>
86      * <li>Initializes the database content.</li>
87      * </ul>
88      *
89      * @see org.objectweb.speedo.j2eedo.bo.DatabaseImpl
90      */

91     protected void setUp() {
92         GenerateListOfActionToBeDone generateMethod =
93             new GenerateListOfActionToBeDone();
94
95         try {
96             for (int i = 0; i < DatabaseImpl.actionArray.length; i++) {
97                 // register method doing something
98
generateMethod.registerMethod(
99                     DatabaseImpl.actionArray[i],
100                     DatabaseImpl.actionWeightArray[i][DatabaseImpl.READ],
101                     DatabaseImpl.actionWeightArray[i][DatabaseImpl.WRITE]);
102             }
103             // set the action list
104
this.methodsList =
105                 generateMethod.mergeWriteReadMethodList(
106                     Integer.getInteger(NBOFWRITE, 1).intValue(),
107                     Integer.getInteger(NBOFREAD, 3).intValue());
108         } catch (Exception JavaDoc e) {
109             e.printStackTrace();
110         }
111
112         PMHolder pmHolder = new PMHolder(getPMF());
113         try {
114             synchronized (JEEDO_LOG_NAME) {
115                 if (!TestJ2eedoApplication.dataReset) {
116                     TestJ2eedoApplication.dataReset = true;
117                     logger.log(
118                         BasicLevel.INFO,
119                         "Resetting initial data for the new test...");
120                     DatabaseImpl.initTestData(pmHolder);
121                     logger.log(
122                         BasicLevel.INFO,
123                         "Initial test data have been created.");
124                 }
125             }
126         } catch (JDOException e) {
127             e.printStackTrace(System.out);
128             fail("Setup of initial test data throws an JDO Exception" + e);
129         } catch (Exception JavaDoc e) {
130             e.printStackTrace(System.out);
131             fail("Setup of initial test data throws an Exception" + e);
132         }
133     }
134     /**
135      * Tears down the test fixture. (Called after every test case method.)
136      */

137     protected void tearDown() {
138         //Nothing to do yet
139
}
140
141     /**
142      * This constructor gets the parameters and resets the default list of
143      * methods to be called
144      *
145      * @see org.objectweb.speedo.j2eedo.bo.DatabaseImpl
146      * @param s
147      * is the class name
148      */

149     public TestJ2eedoApplication(String JavaDoc s) {
150         super(s);
151         this.simpleTestOnly = Boolean.getBoolean(SIMPLETEST);
152         this.nbThread = Integer.getInteger(THREAD, 1).intValue();
153         this.nbTx = Integer.getInteger(LOOP, 1).intValue();
154         this.timeout = Long.getLong(TIMEOUT, 3600000).longValue();
155         this.nbOfRead = Integer.getInteger(NBOFREAD, 3).intValue();
156         this.nbOfWrite = Integer.getInteger(NBOFWRITE, 1).intValue();
157
158         System.out.println(SIMPLETEST + "=" + simpleTestOnly);
159         System.out.println(THREAD + "=" + nbThread);
160         System.out.println(LOOP + "=" + nbTx);
161         System.out.println(TIMEOUT + "=" + timeout);
162         System.out.println(NBOFREAD + "=" + nbOfRead);
163         System.out.println(NBOFWRITE + "=" + nbOfWrite);
164
165         loggerFactory = Monolog.monologFactory;
166         logger = loggerFactory.getLogger(getLoggerName());
167
168         this.methodsList = null;
169     }
170     /**
171      * This sub class provides the list of the methods having to be called
172      * while taking regarding the rate between the reading and writing defined
173      * by the two parameters <br>- rankOfRead : number of read methods to be
174      * called <br>- rankOfWrite : number of write methods to be called <br>
175      *
176      * @author fmillevi@yahoo.com
177      */

178     public class GenerateListOfActionToBeDone {
179         /**
180          * The constant <code>MAX_WEIGHT</code> defines relative maximum
181          * weight used by the methods registerMethodXXX . Its values is 5
182          */

183         public final static int MAX_WEIGHT = 5;
184         /**
185          * The constant <code>MIN_WEIGHT</code> defines relative minimum
186          * weight used by the methods registerMethodXXX . Its values is -1
187          */

188         public final static int MIN_WEIGHT = 1;
189
190         private int totalWriteWeight = 0;
191         private int totalReadWeight = 0;
192
193         private List JavaDoc readAndWriteActionList = null;
194         private List JavaDoc writeOnlyActionList = null;
195         private List JavaDoc readOnlyActionList = null;
196         HashMap JavaDoc readAndWriteAction4ReadMap = null;
197         HashMap JavaDoc readAndWriteAction4WriteMap = null;
198         HashMap JavaDoc readOnlyActionMap = null;
199         HashMap JavaDoc writeOnlyActionMap = null;
200
201         /**
202          * This method populates the list of action according the weight of
203          * each method : The less a method is weighted, the more frequent this
204          * method is in the list
205          *
206          * @param map
207          * is the current map storing the method names with the
208          * read/write weight
209          * @param list
210          * is the current list of method populated according the
211          * weight of each method
212          */

213         private int computeList(HashMap JavaDoc map, List JavaDoc list) {
214             if (null == map || 0 == map.size())
215                 return 0;
216
217             Iterator JavaDoc listOfMethod = map.keySet().iterator();
218             int totalWeight = 0;
219             int nbEntries = 0;
220             while (listOfMethod.hasNext()) {
221                 String JavaDoc method = (String JavaDoc) listOfMethod.next();
222                 int weight = ((Integer JavaDoc) map.get(method)).intValue();
223                 int nbOfEntry = Math.round(MAX_WEIGHT * MAX_WEIGHT / weight);
224                 for (int i = 0; i < nbOfEntry; i++) {
225                     list.add(method);
226                     nbEntries++;
227                     totalWeight += weight;
228                 }
229             }
230             logger.log(BasicLevel.DEBUG, nbEntries + " entries added");
231             return totalWeight;
232         }
233
234         /**
235          * generate the list of write taking care of the write weight
236          *
237          * @throws Exception
238          * when no method are register in the map
239          */

240         private void computeReadMethodList() throws Exception JavaDoc {
241             try {
242                 this.readOnlyActionList = new ArrayList JavaDoc();
243                 this.totalReadWeight =
244                     computeList(
245                         this.readOnlyActionMap,
246                         this.readOnlyActionList);
247             } catch (Exception JavaDoc e) {
248                 throw new Exception JavaDoc("Can not compute Write Method List", e);
249             }
250         }
251
252         /**
253          * generate the list of write taking care of the write weight
254          *
255          * @throws Exception
256          * when no method are register in the map
257          */

258         private void computeReadWriteMethodList() throws Exception JavaDoc {
259             try {
260                 this.readAndWriteActionList = new ArrayList JavaDoc();
261
262                 int nbRead =
263                     computeList(
264                         this.readAndWriteAction4ReadMap,
265                         this.readAndWriteActionList);
266
267                 int nbWrite =
268                     computeList(
269                         this.readAndWriteAction4WriteMap,
270                         this.readAndWriteActionList);
271
272                 this.totalWriteWeight = nbWrite;
273                 this.totalReadWeight = nbRead;
274
275             } catch (Exception JavaDoc e) {
276                 throw new Exception JavaDoc("Can not compute Write Method List", e);
277             }
278         }
279
280         /**
281          * generate the list of write taking care of the write weight
282          *
283          * @throws Exception
284          * when no method are register in the map
285          */

286         private void computeWriteMethodList() throws Exception JavaDoc {
287             try {
288                 this.writeOnlyActionList = new ArrayList JavaDoc();
289                 this.totalWriteWeight =
290                     computeList(
291                         this.writeOnlyActionMap,
292                         this.writeOnlyActionList);
293             } catch (Exception JavaDoc e) {
294                 throw new Exception JavaDoc("Can not compute Write Method List", e);
295             }
296         }
297
298         /**
299          * This method populates the list Read/Write Methods according the Read
300          * methoded registered
301          *
302          * @param nbOfWrite
303          * @param nbOfRead
304          * @return the list of methods to be called
305          * @throws Exception
306          * when no method are register in the map and when
307          * parameters are null or <0
308          */

309         public List JavaDoc mergeWriteReadMethodList(int nbOfWrite, int nbOfRead)
310             throws Exception JavaDoc {
311             if (0 >= (nbOfWrite + nbOfRead) || 0 > (nbOfWrite * nbOfRead))
312                 throw new Exception JavaDoc(
313                     "Parameters nbOfRead ("
314                         + nbOfRead
315                         + ") and nbOfWrite ("
316                         + nbOfWrite
317                         + ") are not correct.");
318
319             logger.log(
320                 BasicLevel.DEBUG,
321                 "Generate the actions list according registered actions read/write weight");
322             List JavaDoc list1 = new ArrayList JavaDoc();
323
324             this.computeReadWriteMethodList();
325             list1.addAll(this.readAndWriteActionList);
326
327             this.computeReadMethodList();
328             this.computeWriteMethodList();
329
330             list1.addAll(this.writeOnlyActionList);
331
332             if (logger.isLoggable(BasicLevel.DEBUG)) {
333                 Iterator JavaDoc iter = null;
334                 int nbActions = 0;
335                 iter = this.readOnlyActionList.iterator();
336                 for (nbActions = 0; iter.hasNext(); nbActions++)
337                     iter.next();
338                 logger.log(
339                     BasicLevel.DEBUG,
340                     nbActions
341                         + " read only actions (total weight:"
342                         + this.totalReadWeight
343                         + ")");
344                 iter = this.writeOnlyActionList.iterator();
345                 for (nbActions = 0; iter.hasNext(); nbActions++)
346                     iter.next();
347                 logger.log(
348                     BasicLevel.DEBUG,
349                     nbActions
350                         + " write only actions (total weight:"
351                         + this.totalWriteWeight
352                         + ")");
353                 iter = this.readAndWriteActionList.iterator();
354                 for (nbActions = 0; iter.hasNext(); nbActions++)
355                     iter.next();
356                 logger.log(
357                     BasicLevel.DEBUG,
358                     nbActions + " read & write only actions");
359             }
360
361             Iterator JavaDoc iter = list1.iterator();
362             int weightRead = 0;
363             int weightWrite = 0;
364             String JavaDoc method;
365             while (iter.hasNext()) {
366                 method = (String JavaDoc) iter.next();
367                 if (this.readOnlyActionMap.containsKey(method))
368                     weightRead
369                         += ((Integer JavaDoc) this.readOnlyActionMap.get(method))
370                             .intValue();
371                 else if (this.writeOnlyActionMap.containsKey(method))
372                     weightWrite
373                         += ((Integer JavaDoc) this.writeOnlyActionMap.get(method))
374                             .intValue();
375                 else {
376                     weightRead
377                         += ((Integer JavaDoc) this.readAndWriteAction4ReadMap.get(method))
378                             .intValue();
379                     weightWrite
380                         += ((Integer JavaDoc) this
381                             .readAndWriteAction4WriteMap
382                             .get(method))
383                             .intValue();
384                 }
385             }
386
387             List JavaDoc list = new ArrayList JavaDoc();
388             if (0 == nbOfWrite) {
389                 list.addAll(this.readOnlyActionList);
390             } else if (0 == nbOfRead) {
391                 list.addAll(this.writeOnlyActionList);
392             } else {
393                 int nbRead2BeAdd =
394                     nbOfRead * weightWrite / nbOfWrite - weightRead;
395                 if (0 >= nbRead2BeAdd)
396                     nbRead2BeAdd = 1;
397                 logger.log(
398                     BasicLevel.DEBUG,
399                     "Before merge Read only methods : \nnbRead "
400                         + weightRead
401                         + "\nnbWrite "
402                         + weightWrite
403                         + "\nnbRead2BeAdd "
404                         + nbRead2BeAdd
405                         + "\nAddList:"
406                         + (float) nbRead2BeAdd / (float) this.totalReadWeight
407                         + "\t#:"
408                         + Math.round(
409                             (float) nbRead2BeAdd / (float) totalReadWeight)
410                         + " *("
411                         + this.totalReadWeight
412                         + ")");
413
414                 if (nbRead2BeAdd < this.totalReadWeight) {
415                     for (int j = 0;
416                         j
417                             < Math.round(
418                                 (float) totalReadWeight / (float) nbRead2BeAdd);
419                         j++)
420                         list.addAll(list1);
421                     list.addAll(this.readOnlyActionList);
422                 } else {
423                     list.addAll(list1);
424                     for (int j = 0;
425                         j
426                             < Math.round(
427                                 (float) nbRead2BeAdd / (float) totalReadWeight);
428                         j++)
429                         list.addAll(this.readOnlyActionList);
430                 }
431             }
432             if (logger.isLoggable(BasicLevel.DEBUG)) {
433                 weightRead = 0;
434                 weightWrite = 0;
435                 int nbCalls = 0;
436                 iter = list.iterator();
437                 while (iter.hasNext()) {
438                     method = (String JavaDoc) iter.next();
439                     nbCalls++;
440                     if (this.readOnlyActionMap.containsKey(method))
441                         weightRead
442                             += ((Integer JavaDoc) this.readOnlyActionMap.get(method))
443                                 .intValue();
444                     else if (this.writeOnlyActionMap.containsKey(method))
445                         weightWrite
446                             += ((Integer JavaDoc) this.writeOnlyActionMap.get(method))
447                                 .intValue();
448                     else {
449                         weightRead
450                             += ((Integer JavaDoc) this
451                                 .readAndWriteAction4ReadMap
452                                 .get(method))
453                                 .intValue();
454                         weightWrite
455                             += ((Integer JavaDoc) this
456                                 .readAndWriteAction4WriteMap
457                                 .get(method))
458                                 .intValue();
459                     }
460                 }
461                 logger.log(
462                     BasicLevel.DEBUG,
463                     "The action list is set : \nnbRead "
464                         + weightRead
465                         + "\nnbWrite "
466                         + weightWrite
467                         + "\n\tGoal rate : "
468                         + nbOfRead
469                         + "/"
470                         + nbOfWrite
471                         + "="
472                         + ((nbOfWrite != 0)
473                             ? Float.toString(
474                                 (float) nbOfRead / (float) nbOfWrite)
475                             : "NaN")
476                         + "\n\tRate:"
477                         + ((weightWrite != 0)
478                             ? Float.toString(
479                                 (float) weightRead / (float) weightWrite)
480                             : "NaN")
481                         + " in "
482                         + nbCalls
483                         + " calls");
484             }
485
486             return list;
487         }
488
489         /**
490          * Register a method having write an read job
491          *
492          * @param name
493          * is the action's name
494          * @param readWeight
495          * is the relative read weight defined between MIN_WEIGHT
496          * and MAX_WEIGHT or setted to 0 (zero)
497          * @param writeWeight
498          * is the relative write weight defined between MIN_WEIGHT
499          * and MAX_WEIGHT or setted to 0 (zero)
500          * @throws Exception
501          * when the weights are not defined between the max and the
502          * min value or setted to 0 (zero). Both weight parameters
503          * can not be setted to 0
504          * @see #MAX_WEIGHT
505          * @see #MIN_WEIGHT
506          */

507         public void registerMethod(
508             String JavaDoc name,
509             int readWeight,
510             int writeWeight)
511             throws Exception JavaDoc {
512             if (name.equals(DatabaseImpl.PARAMETER_PING))
513                 return;
514             if (0 == readWeight)
515                 this.registerMethodWrite(name, writeWeight);
516             else if (0 == writeWeight)
517                 this.registerMethodRead(name, readWeight);
518             else
519                 registerMethodReadWrite(name, readWeight, writeWeight);
520         }
521
522         /**
523          * Register a method having write an read job
524          *
525          * @param name
526          * is the action's name
527          * @param readWeight
528          * is the relatif weight for read
529          * @param writeWeight
530          * is the relatif weight for write
531          * @throws Exception
532          * when the weights are not in the max and the min value
533          */

534         private void registerMethodReadWrite(
535             String JavaDoc name,
536             int readWeight,
537             int writeWeight)
538             throws Exception JavaDoc {
539             if (null == this.readAndWriteAction4ReadMap)
540                 this.readAndWriteAction4ReadMap = new HashMap JavaDoc();
541             if (null == this.readAndWriteAction4WriteMap)
542                 this.readAndWriteAction4WriteMap = new HashMap JavaDoc();
543
544             if (readWeight > GenerateListOfActionToBeDone.MAX_WEIGHT
545                 || readWeight < GenerateListOfActionToBeDone.MIN_WEIGHT
546                 || writeWeight > GenerateListOfActionToBeDone.MAX_WEIGHT
547                 || writeWeight < GenerateListOfActionToBeDone.MIN_WEIGHT)
548                 throw new Exception JavaDoc(
549                     "Can not register this method : the weight must be defined between "
550                         + GenerateListOfActionToBeDone.MIN_WEIGHT
551                         + " and "
552                         + GenerateListOfActionToBeDone.MAX_WEIGHT);
553             this.readAndWriteAction4ReadMap.put(name, new Integer JavaDoc(readWeight));
554             this.readAndWriteAction4WriteMap.put(
555                 name,
556                 new Integer JavaDoc(writeWeight));
557         }
558
559         /**
560          * Register a method having read job
561          *
562          * @param name is the Method's name
563          * @param weight is relatif weight for read
564          * @throws Exception
565          * when the weights are not in the max and the min value
566          */

567         private void registerMethodRead(String JavaDoc name, int weight)
568             throws Exception JavaDoc {
569             if (null == this.readOnlyActionMap)
570                 this.readOnlyActionMap = new HashMap JavaDoc();
571
572             if (weight > GenerateListOfActionToBeDone.MAX_WEIGHT
573                 || weight < GenerateListOfActionToBeDone.MIN_WEIGHT)
574                 throw new Exception JavaDoc(
575                     "Can not register this method : the weight must be defined between "
576                         + GenerateListOfActionToBeDone.MIN_WEIGHT
577                         + " and "
578                         + GenerateListOfActionToBeDone.MAX_WEIGHT);
579             this.readOnlyActionMap.put(name, new Integer JavaDoc(weight));
580         }
581
582         /**
583          * Register a method having write job
584          *
585          * @param name is the Method's name
586          * @param weight is relatif weight for write
587          * @throws Exception
588          * when the weights are not in the max and the min value
589          */

590         private void registerMethodWrite(String JavaDoc name, int weight)
591             throws Exception JavaDoc {
592             if (null == this.writeOnlyActionMap)
593                 this.writeOnlyActionMap = new HashMap JavaDoc();
594
595             this.totalWriteWeight += weight;
596
597             if (weight > GenerateListOfActionToBeDone.MAX_WEIGHT
598                 || weight < GenerateListOfActionToBeDone.MIN_WEIGHT)
599                 throw new Exception JavaDoc(
600                     "Can not register this method : the weight must be defined between "
601                         + GenerateListOfActionToBeDone.MIN_WEIGHT
602                         + " and "
603                         + GenerateListOfActionToBeDone.MAX_WEIGHT);
604             this.writeOnlyActionMap.put(name, new Integer JavaDoc(weight));
605         }
606
607         /**
608          * Empty Constructor - reset all values
609          */

610         public GenerateListOfActionToBeDone() {
611             this.readOnlyActionList = null;
612             this.writeOnlyActionList = null;
613             this.readAndWriteAction4ReadMap = null;
614             this.readAndWriteAction4WriteMap = null;
615             this.readOnlyActionMap = null;
616             this.writeOnlyActionMap = null;
617             this.totalWriteWeight = 0;
618             this.totalReadWeight = 0;
619         }
620
621     }
622
623     /**
624      * Returns the current log name
625      *
626      * @see org.objectweb.speedo.SpeedoTestHelper#getLoggerName()
627      */

628     protected String JavaDoc getLoggerName() {
629         return JEEDO_LOG_NAME;
630     }
631
632     private final static Hashtable JavaDoc needTransactionArray = new Hashtable JavaDoc();
633
634     protected String JavaDoc performMethod(String JavaDoc action)
635         throws Exception JavaDoc, JDOException, JDOFatalException {
636         PMHolder pmHolder = new PMHolder(getPMF());
637         DatabaseImpl databaseImpl = new DatabaseImpl(pmHolder);
638
639         String JavaDoc returnStr = null;
640         boolean needTrans;
641         PersistenceManager pm = null;
642
643         if (!needTransactionArray.containsKey(action)) {
644             int k = 0;
645             for (;
646                 !DatabaseImpl.actionArray[k].equals(action)
647                     && k < DatabaseImpl.actionWeightArray.length;
648                 k++);
649
650             if (0 == DatabaseImpl.actionWeightArray[k][DatabaseImpl.WRITE])
651                 needTransactionArray.put(action, new Boolean JavaDoc(false));
652             else
653                 needTransactionArray.put(action, new Boolean JavaDoc(true));
654         }
655         needTrans = ((Boolean JavaDoc) needTransactionArray.get(action)).booleanValue();
656         needTrans = true;
657         if (needTrans) {
658             pm = pmHolder.getPersistenceManager();
659             pm.currentTransaction().begin();
660         }
661         try {
662             returnStr = databaseImpl.doAction(action);
663         } catch (JDOFatalException e) {
664             if (pm != null && !pm.isClosed() && pm.currentTransaction().isActive()) {
665                 pm.currentTransaction().rollback();
666             }
667             throw e;
668         } finally {
669             if (pm != null && !pm.isClosed() && pm.currentTransaction().isActive()) {
670                 pm.currentTransaction().commit();
671             }
672             if (needTrans) {
673                 pmHolder.closePersistenceManager();
674             }
675         }
676         return returnStr;
677     }
678
679     protected void perform() {
680         final int _nbTx = this.nbTx;
681         final List JavaDoc _methodsList = this.methodsList;
682         this.displayTestParameters();
683
684         //------------ Create thread for each tasks ------------//
685
Thread JavaDoc[] ts = new Thread JavaDoc[nbThread];
686
687         for (int thread = 0; thread < nbThread; thread++) {
688             ts[thread] = new Thread JavaDoc(new Runnable JavaDoc() {
689                 public void run() {
690                     TraceTime traceTime = new TraceTime();
691                     String JavaDoc action = null;
692                     Iterator JavaDoc iter = null;
693
694                     for (int j = 0, i = 0; i < _nbTx; i++) {
695                         traceTime.startTask(Thread.currentThread().getName() + ".loop." + i);
696                         logger.log(BasicLevel.INFO, "Start loop " + i);
697                         Collections.shuffle(_methodsList);
698                         iter = _methodsList.iterator();
699                         boolean deadLock = false;
700                         String JavaDoc returnStr;
701                         while (iter.hasNext()) {
702                             if (0 == (j++ % 100.0)) {
703                                 logger.log(BasicLevel.INFO, j + " actions called...");
704                             }
705                             action = (String JavaDoc) iter.next();
706                             // check if the action need to start a transaction
707
logger.log(BasicLevel.DEBUG, "Calls method:" + action);
708                             deadLock = true;
709                             while (deadLock) {
710                                 deadLock = false;
711                                 try {
712                                     returnStr = performMethod(action);
713                                     logger.log(BasicLevel.DEBUG,
714                                         "The method " + action + " returns:\n"
715                                             + returnStr);
716                                 } catch (JDOFatalException e) {
717                                     logger.log( BasicLevel.INFO, "The method "
718                                             + action
719                                             + " throws a JDO Fatal Exception");
720                                     deadLock = true;
721                                 } catch (Exception JavaDoc e) {
722                                     logger.log(BasicLevel.ERROR,
723                                         "The method " + action
724                                             + " throws an exception ", e);
725                                     fail("The method " + action
726                                             + " throws JDO an exception "
727                                             + e.getMessage());
728                                 }
729                             }
730                         }
731                     }
732                     traceTime.endTask();
733                     logger.log(BasicLevel.INFO, "End of thread loops : " + traceTime.report());
734                 }
735             });
736         }
737
738         //-------------- Launch all threads ------------//
739
for (int thread = 0; thread < nbThread; thread++) {
740             ts[thread].start();
741         }
742
743         try {
744             //------------ wait threads ------------//
745
for (int thread = 0; thread < nbThread; thread++) {
746                 ts[thread].join(timeout);
747                 if (ts[thread].isAlive()) {
748                     logger.log(
749                         BasicLevel.WARN,
750                         "Thread "
751                             + ts[thread].getName()
752                             + " is not finished after the delay, it could be blocked");
753                     ts[thread].interrupt();
754                     fail("Thread " + ts[thread] + " is blocked!");
755                 }
756             }
757         } catch (InterruptedException JavaDoc e) {
758             fail(e.getMessage());
759         }
760         // display the current status of data
761
try {
762             PMHolder pmHolder = new PMHolder(getPMF());
763             DatabaseImpl databaseImpl = new DatabaseImpl(pmHolder);
764             String JavaDoc str = databaseImpl.doAction("");
765             logger.log(BasicLevel.DEBUG, str);
766         } catch (Exception JavaDoc e) {
767             logger.log(BasicLevel.ERROR, "Error occurs : ", e);
768         }
769
770     }
771
772     /**
773      * this method logs the current test method called and the differents
774      * parameters values.
775      */

776     protected void displayTestParameters() {
777         if (!logger.isLoggable(BasicLevel.INFO))
778             return;
779         // display the calling method
780
Throwable JavaDoc t = new Throwable JavaDoc();
781         StringWriter JavaDoc sw = new StringWriter JavaDoc();
782         PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw);
783         t.printStackTrace(pw);
784         String JavaDoc input = sw.getBuffer().toString();
785         StringReader JavaDoc sr = new StringReader JavaDoc(input);
786         BufferedReader JavaDoc br = new BufferedReader JavaDoc(sr);
787         try {
788             String JavaDoc line;
789             br.readLine(); // Exception name
790
while (true) {
791                 line = br.readLine();
792                 int paren = line.indexOf('(');
793                 line = line.substring(0, paren);
794                 int period = line.lastIndexOf('.');
795                 line = line.substring(period + 1);
796                 if (line.indexOf("test") != 0)
797                     continue;
798                 break;
799             }
800             logger.log(BasicLevel.INFO, "The test is : " + line);
801         } catch (Exception JavaDoc e) {
802         }
803
804         logger.log(
805             BasicLevel.INFO,
806             "The test is launch with the parameters : \nNumber of threads: "
807                 + this.nbThread
808                 + "\nNumber of actions list loop: "
809                 + this.nbTx
810                 + "\ntime out (ms): "
811                 + this.timeout
812                 + "\nnb of read proportion: "
813                 + this.nbOfRead
814                 + "\nnb of write proportion: "
815                 + this.nbOfWrite);
816
817         int nbCalls = 0;
818         String JavaDoc method;
819         HashMap JavaDoc actionsWeight = new HashMap JavaDoc();
820         Iterator JavaDoc iter = this.methodsList.iterator();
821         int count = -1;
822         while (iter.hasNext()) {
823             method = (String JavaDoc) iter.next();
824             nbCalls++;
825             if (actionsWeight.containsKey(method)) {
826                 count = ((Integer JavaDoc) actionsWeight.get(method)).intValue() + 1;
827                 actionsWeight.remove(method);
828                 actionsWeight.put(method, new Integer JavaDoc(count));
829             } else {
830                 actionsWeight.put(method, new Integer JavaDoc(1));
831             }
832         }
833         logger.log(
834             BasicLevel.INFO,
835             "Action list {action1=count, action2=count ...}: "
836                 + actionsWeight
837                 + "\nTotal number of calls: "
838                 + nbCalls);
839     }
840
841     /**
842      * This method calls action of the DatabaseImpl class according the default
843      * parameters :
844      * <ul>
845      * <li>Default action list set by the setup method</li>
846      * <li>Test through J2EE calls</li>
847      * </ul>
848      */

849     public void testSimple() {
850         this.perform();
851     }
852
853     /**
854      * This method calls none writing action of the DatabaseImpl class.
855      */

856     public void _testReadOnly() {
857         if (this.simpleTestOnly)
858             return;
859         // Create a new list of methods
860
GenerateListOfActionToBeDone generateMethod =
861             new GenerateListOfActionToBeDone();
862
863         try {
864             for (int i = 0; i < DatabaseImpl.actionArray.length; i++) {
865                 if (0 == DatabaseImpl.actionWeightArray[i][DatabaseImpl.WRITE])
866                     generateMethod.registerMethod(
867                         DatabaseImpl.actionArray[i],
868                         DatabaseImpl.actionWeightArray[i][DatabaseImpl.READ],
869                         DatabaseImpl.actionWeightArray[i][DatabaseImpl.WRITE]);
870             }
871             this.nbOfRead = 1;
872             this.nbOfWrite = 0;
873             this.methodsList =
874                 generateMethod.mergeWriteReadMethodList(
875                     this.nbOfWrite,
876                     this.nbOfRead);
877         } catch (Exception JavaDoc e) {
878             e.printStackTrace();
879         }
880         this.perform();
881     }
882
883     /**
884      * This method calls none deleting action of the DatabaseImpl class.
885      */

886     public void _testIncreaseDatabaseSize() {
887         if (this.simpleTestOnly)
888             return;
889         // Create a new list of methods
890
GenerateListOfActionToBeDone generateMethod =
891             new GenerateListOfActionToBeDone();
892
893         try {
894             for (int i = 0; i < DatabaseImpl.actionArray.length; i++) {
895                 if (!(DatabaseImpl
896                     .actionArray[i]
897                     .equalsIgnoreCase(DatabaseImpl.PARAMETER_MERGE_DEPARTMENT))
898                     && !(DatabaseImpl
899                         .actionArray[i]
900                         .equalsIgnoreCase(DatabaseImpl.PARAMETER_REM_PROJECT))
901                     && !(DatabaseImpl
902                         .actionArray[i]
903                         .equalsIgnoreCase(DatabaseImpl.PARAMETER_REM_EMPLOYEE)))
904                     generateMethod.registerMethod(
905                         DatabaseImpl.actionArray[i],
906                         DatabaseImpl.actionWeightArray[i][DatabaseImpl.READ],
907                         DatabaseImpl.actionWeightArray[i][DatabaseImpl.WRITE]);
908             }
909             this.methodsList =
910                 generateMethod.mergeWriteReadMethodList(
911                     this.nbOfWrite,
912                     this.nbOfRead);
913         } catch (Exception JavaDoc e) {
914             e.printStackTrace();
915         }
916         this.perform();
917     }
918 }
919
Popular Tags