KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > speedo > j2eedo > bo > DatabaseImpl


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 1 mars 2004 @author fmillevi@yahoo.com
22  *
23  */

24 package org.objectweb.speedo.j2eedo.bo;
25
26 import java.util.Collection JavaDoc;
27 import java.util.Hashtable JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.Vector JavaDoc;
30
31 import javax.jdo.JDOException;
32 import javax.jdo.JDOFatalException;
33 import javax.jdo.PersistenceManager;
34 import javax.jdo.Query;
35
36 import org.objectweb.speedo.Alea;
37 import org.objectweb.speedo.j2eedo.common.PMHolder;
38 import org.objectweb.speedo.j2eedo.database.Address;
39 import org.objectweb.speedo.j2eedo.database.DatabaseObjectInterface;
40 import org.objectweb.speedo.j2eedo.database.Department;
41 import org.objectweb.speedo.j2eedo.database.Employee;
42 import org.objectweb.speedo.j2eedo.database.Project;
43 import org.objectweb.util.monolog.Monolog;
44 import org.objectweb.util.monolog.api.BasicLevel;
45 import org.objectweb.util.monolog.api.Logger;
46 import org.objectweb.util.monolog.api.LoggerFactory;
47
48 /**
49  * This class handle each request on the <b>J2EEDO</b> application.
50  * The doAction() method performs the current requested action.
51  * <p>
52  * It starts and commits a transaction if needed
53  * </p>
54  * <p>
55  * Call the asked action. When the action in the
56  * {@link DatabaseImpl#actionArray action list}, the 3 local static lists of
57  * id (department, employee and project) are redefined.
58  * </p>
59  *
60  * @author fmillevi@yahoo.com
61  */

62 public class DatabaseImpl {
63     /**
64      * Defines the action <code>PARAMETER_PING</code><b> its value is ("ping")</b>
65      * <p>
66      * This action is use just to check if the application can be reached
67      * </p>
68      */

69     final public static String JavaDoc PARAMETER_PING = "ping";
70     /**
71      * Defines the action <code>PARAMETER_NEW_DEPARTMENT</code><b> its value is
72      * ("newDept")</b>
73      * <p>
74      * This action Creates a new department and some new employees (random
75      * number defined between 10 and 70).
76      * </p>
77      *
78      * @see DepartmentFactory#MIN_EMPLOYEE_PER_DEPARTMENT
79      * @see DepartmentFactory#MAX_EMPLOYEE_PER_DEPARTMENT
80      * @see DepartmentFactory#newDepartmentWithEmployees
81      */

82     final public static String JavaDoc PARAMETER_NEW_DEPARTMENT = "newDept";
83     /**
84      * Defines the action <code>PARAMETER_NEW_PROJECT</code><b> its value is
85      * ("newProj")</b>
86      * <p>
87      * This action Creates a new project and affect few employees (random
88      * number defined between 5 and 20).
89      * </p>
90      *
91      * @see ProjectFactory#MIN_MEMBER_PER_PROJECT
92      * @see ProjectFactory#MAX_MEMBER_PER_PROJECT
93      * @see ProjectFactory#newProjectWithEmployees
94      */

95     final public static String JavaDoc PARAMETER_NEW_PROJECT = "newProj";
96     /**
97      * Defines the action <code>PARAMETER_NEW_EMPLOYEE</code><b> its value is
98      * ("newEmp")</b>
99      * <p>
100      * Selects one of the known departments and creates a new employee.
101      * </p>
102      * @see EmployeeFactory#newEmployee
103      */

104     final public static String JavaDoc PARAMETER_NEW_EMPLOYEE = "newEmp";
105     /**
106      * Defines the action <code>PARAMETER_SET_BOSS</code><b> its value is
107      * ("setDeptBoss")</b>
108      * @see DepartmentFactory#setManagerForADepartment()
109      */

110     final public static String JavaDoc PARAMETER_SET_BOSS = "setDeptBoss";
111     /**
112      * Defines the action <code>PARAMETER_REM_EMPLOYEE</code><b> its value is
113      * ("delEmployee")</b>
114      * @see EmployeeFactory#deleteEmployee
115      */

116     final public static String JavaDoc PARAMETER_REM_EMPLOYEE = "delEmployee";
117     /**
118      * Defines the action <code>PARAMETER_REM_PROJECT</code><b> its value is
119      * ("delProject")</b>
120      * @see ProjectFactory#deleteProject
121      */

122     final public static String JavaDoc PARAMETER_REM_PROJECT = "delProject";
123     /**
124      * Defines the action <code>PARAMETER_SPLIT_PROJECT</code><b> its value is
125      * ("splitProject")</b>
126      * @see ProjectFactory#splitProject
127      */

128     final public static String JavaDoc PARAMETER_SPLIT_PROJECT = "splitProject";
129     /**
130      * Defines the action <code>PARAMETER_SPLIT_DEPARTMENT</code><b> its value is
131      * ("splitDepartment")</b>
132      * @see DepartmentFactory#splitDepartment
133      */

134     final public static String JavaDoc PARAMETER_SPLIT_DEPARTMENT = "splitDepartment";
135     /**
136      * Defines the action <code>PARAMETER_MERGE_DEPARTMENT</code><b> its value is
137      * ("mergeDept")</b>
138      * @see DepartmentFactory#mergeDepartment
139      */

140     final public static String JavaDoc PARAMETER_MERGE_DEPARTMENT = "mergeDept";
141     /**
142      * Defines the action <code>PARAMETER_INCREASE_SALARY</code><b> its value is
143      * ("incSalary")</b> for good folsk only...
144      * @see EmployeeFactory#increaseSalary()
145      */

146     final public static String JavaDoc PARAMETER_INCREASE_SALARY = "incSalary";
147     /**
148      * Defines the action <code>PARAMETER_GET_DEPARTMENT</code><b> its value is
149      * ("getDepartment")</b>
150      * @see DepartmentFactory#getDepartment()
151      */

152     final public static String JavaDoc PARAMETER_GET_DEPARTMENT = "getDepartment";
153     /**
154      * Defines the action <code>PARAMETER_GET_PROJECT</code><b> its value is
155      * ("getProject")</b>
156      * @see ProjectFactory#getProject()
157      */

158     final public static String JavaDoc PARAMETER_GET_PROJECT = "getProject";
159     /**
160      * Defines the action <code>PARAMETER_GET_EMPLOYEE</code><b> its value is
161      * ("getEmployee")</b>
162      * @see EmployeeFactory#getEmployees()
163      */

164     final public static String JavaDoc PARAMETER_GET_EMPLOYEE = "getEmployee";
165     /**
166      * Defines the action <code>PARAMETER_QUERY_PROJECTS</code><b> its value is
167      * ("queryProjects")</b>
168      * <p>
169      * Performs one of the four queries:
170      * <ul>
171      * <li>Get employee by its id,</li>
172      * <li>Get employees between min and max,</li>
173      * <li>Get employees having the same manager,</li>
174      * <li>Get employees member of a project.</li>
175      * </ul>
176      * </p>
177      * @see EmployeeFactory#getEmployees()
178      */

179     final public static String JavaDoc PARAMETER_QUERY_PROJECTS = "queryProjects";
180     /**
181      * Defines the action <code>PARAMETER_QUERY_EMPLOYEES</code><b> its value is
182      * ("queryEmployees")</b>
183      * <p>
184      * Performs one of the two queries:
185      * <ul>
186      * <li>Get project by its id,</li>
187      * <li>Get projects by member.</li>
188      * </ul>
189      * </p>
190      * @see ProjectFactory#getProjects()
191      */

192     final public static String JavaDoc PARAMETER_QUERY_EMPLOYEES = "queryEmployees";
193
194     final public static String JavaDoc PARAMETER_EVICTALL = "evictall";
195     /**
196      * The String array <code>actionArray</code> gives the liste of actions
197      * avalaibles
198      */

199     final public static String JavaDoc actionArray[] =
200         {
201             DatabaseImpl.PARAMETER_NEW_DEPARTMENT,
202             DatabaseImpl.PARAMETER_NEW_PROJECT,
203             DatabaseImpl.PARAMETER_NEW_EMPLOYEE,
204             DatabaseImpl.PARAMETER_SET_BOSS,
205             DatabaseImpl.PARAMETER_REM_EMPLOYEE,
206             DatabaseImpl.PARAMETER_REM_PROJECT,
207             DatabaseImpl.PARAMETER_SPLIT_PROJECT,
208             DatabaseImpl.PARAMETER_SPLIT_DEPARTMENT,
209             DatabaseImpl.PARAMETER_MERGE_DEPARTMENT,
210             DatabaseImpl.PARAMETER_INCREASE_SALARY,
211             DatabaseImpl.PARAMETER_GET_DEPARTMENT,
212             DatabaseImpl.PARAMETER_GET_PROJECT,
213             DatabaseImpl.PARAMETER_GET_EMPLOYEE,
214             DatabaseImpl.PARAMETER_QUERY_PROJECTS,
215             DatabaseImpl.PARAMETER_QUERY_EMPLOYEES,
216             DatabaseImpl.PARAMETER_PING };
217
218     final public static int READ = 1;
219     final public static int WRITE = 0;
220
221     /**
222      * The double dimension array <code>actionWeightArray</code> gives for
223      * each action the relative read and write weight
224      *
225      * @see #actionArray
226      */

227     final public static int actionWeightArray[][] = { //{write,read}
228
{ 4, 0 }, //DatabaseImpl.PARAMETER_NEW_DEPARTMENT,
229
{
230             5, 3 }, //DatabaseImpl.PARAMETER_NEW_PROJECT,
231
{
232             1, 1 }, //DatabaseImpl.PARAMETER_NEW_EMPLOYEE,
233
{
234             4, 2 }, //DatabaseImpl.PARAMETER_SET_BOSS,
235
{
236             1, 1 }, //DatabaseImpl.PARAMETER_REM_EMPLOYEE,
237
{
238             4, 2 }, //DatabaseImpl.PARAMETER_REM_PROJECT,
239
{
240             4, 3 }, //DatabaseImpl.PARAMETER_SPLIT_PROJECT,
241
{
242             4, 4 }, //DatabaseImpl.PARAMETER_SPLIT_DEPARTMENT
243
{
244             5, 2 }, //DatabaseImpl.PARAMETER_MERGE_DEPARTMENT,
245
{
246             3, 2 }, //DatabaseImpl.PARAMETER_INCREASE_SALARY,
247
{
248             0, 5 }, //DatabaseImpl.PARAMETER_GET_DEPARTMENT,
249
{
250             0, 3 }, //DatabaseImpl.PARAMETER_GET_PROJECT,
251
{
252             0, 1 }, //DatabaseImpl.PARAMETER_GET_EMPLOYEE,
253
{
254             0, 3 }, //DatabaseImpl.PARAMETER_QUERY_PROJECT,
255
{
256             0, 2 }, //DatabaseImpl.PARAMETER_QUERY_EMPLOYEE
257
{
258             0, 0 } //DatabaseImpl.PARAMETER_PING
259
};
260
261     private String JavaDoc action;
262     private boolean performCommit;
263     private Hashtable JavaDoc needTransactionArray;
264     protected StringBuffer JavaDoc outStr;
265     private PMHolder persistenceManagerHolder;
266
267     /**
268      * Current Persistence Manager <code>pm</code>
269      */

270     public PersistenceManager pm;
271     private PollsSynchronizations pollsSync;
272
273     private DepartmentFactory departmentFactory = null;
274     private EmployeeFactory employeeFactory = null;
275     private ProjectFactory projectFactory = null;
276
277     /**
278      * The Vector <code>poolOfDepartmentId</code> is a static list of known
279      * departmentId used to keep in mind the list of department without doing
280      * any JDO request.
281      * <p>
282      * This is a local cache
283      * </p>
284      */

285     public final static Vector JavaDoc poolOfDepartmentId = new Vector JavaDoc();
286     /**
287      * The Vector <code>poolOfProjectId</code> is a static list of known
288      * projectId used to keep in mind the list of project without doing any JDO
289      * request.
290      * <p>
291      * This is a local cache
292      * </p>
293      */

294     public final static Vector JavaDoc poolOfProjectId = new Vector JavaDoc();
295     /**
296      * The Vector <code>poolOfEmployeeId</code> is a static list of known
297      * employeeId used to keep in mind the list of employee without doing any
298      * JDO request.
299      * <p>
300      * This is a local cache
301      * </p>
302      */

303     public final static Vector JavaDoc poolOfEmployeeId = new Vector JavaDoc();
304
305     private static boolean resetPools = true;
306
307     static Logger logger = null;
308     static {
309         LoggerFactory lf = Monolog.initialize();
310         logger = lf.getLogger(DatabaseImpl.class.getName());
311     }
312
313     private final static int PROJECT_INIT_SIZE = 100;
314     private final static int DEPARTMENT_INIT_SIZE = 30;
315
316     /**
317      * Empty Constructor initialize the current data model implementation
318      * object :
319      *
320      * @param pmHolder
321      * is the Persistence Manager Holder used to get the PM.
322      */

323     public DatabaseImpl(PMHolder pmHolder) {
324         super();
325         this.persistenceManagerHolder = pmHolder;
326         this.action = "";
327         this.performCommit = false;
328         this.outStr = new StringBuffer JavaDoc();
329         this.departmentFactory = new DepartmentFactory();
330         this.employeeFactory = new EmployeeFactory();
331         this.projectFactory = new ProjectFactory();
332         this.needTransactionArray = new Hashtable JavaDoc();
333         // define the action needing transaction.
334
int writeWeight;
335         for (int i = 0; i < DatabaseImpl.actionWeightArray.length; i++) {
336             String JavaDoc _action = DatabaseImpl.actionArray[i];
337             writeWeight = DatabaseImpl.actionWeightArray[i][DatabaseImpl.WRITE];
338             if (0 == writeWeight)
339                 needTransactionArray.put(_action, new Boolean JavaDoc(false));
340             else
341                 needTransactionArray.put(_action, new Boolean JavaDoc(true));
342         }
343     }
344
345     /**
346      * This method initialize the action to be performed, disables transaction
347      * management and calls the private doAction() method.
348      *
349      * @param parameter
350      * is the action to be performed
351      * @return threatment result as String
352      * @throws JDOException
353      * @throws Exception
354      */

355     public String JavaDoc doAction(String JavaDoc parameter) throws JDOException, Exception JavaDoc {
356         this.action = parameter;
357         this.performCommit = false;
358         return doAction();
359     }
360
361     /**
362      * This method initialize the action to be performed, enables or disables
363      * transaction management according the parameter withTransaction and calls
364      * the private doAction() method.
365      *
366      * @param parameter
367      * is the action to be performed
368      * @param withTransaction
369      * is a boolean use to enable or disable the use of transaction
370      * @return threatment result as String
371      * @throws JDOException
372      * @throws Exception
373      */

374     public String JavaDoc doAction(String JavaDoc parameter, boolean withTransaction)
375         throws JDOException, Exception JavaDoc {
376         this.action = parameter;
377         this.performCommit = withTransaction;
378         return doAction();
379     }
380
381     /**
382      * This method performs the current requested action.
383      * <p>
384      * It starts and commits a transaction if needed
385      * </p>
386      * <p>
387      * Call the asked action. When the action in the
388      * {@see #actionArray actuion list}defined above, the 3 local static list
389      * of id (department, employee and project) are redefined.
390      * </p>
391      *
392      * @return threatment result as String
393      * @throws JDOException
394      * @throws Exception
395      */

396     private String JavaDoc doAction() throws JDOException, Exception JavaDoc {
397         this.outStr = new StringBuffer JavaDoc();
398         // check if a transaction is required
399
boolean needTrans =
400             (this.performCommit)
401                 ? ((Boolean JavaDoc) this.needTransactionArray.get(this.action))
402                     .booleanValue()
403                 : false;
404         try {
405             if (PARAMETER_PING.equalsIgnoreCase(action)) {
406                 return "Alive...";
407             }
408             this.pm = this.persistenceManagerHolder.getPersistenceManager();
409             if (PARAMETER_EVICTALL.equalsIgnoreCase(action)) {
410                 logger.log(BasicLevel.WARN, "Flushing cache ...");
411                 this.pm.evictAll();
412                 resetPolls(this.pm, this.outStr);
413                 return "Cache flushed !";
414             }
415             DatabaseImpl.initPolls(this.pm);
416
417             // start a transaction if required
418
if (!"".equalsIgnoreCase(this.action)
419                 && ((Boolean JavaDoc) this.needTransactionArray.get(this.action))
420                     .booleanValue()) {
421                 this.pollsSync = new PollsSynchronizations();
422                 this.pm.setUserObject(pollsSync);
423                 this.pm.currentTransaction().setSynchronization(pollsSync);
424             }
425
426             if (needTrans) {
427                 logger.log(
428                     BasicLevel.DEBUG,
429                     "Start a new transaction "
430                         + this.pm.currentTransaction().toString());
431                 this.pm.currentTransaction().begin();
432             }
433             logger.log(BasicLevel.DEBUG, "do action " + this.action);
434             if (PARAMETER_NEW_DEPARTMENT.equalsIgnoreCase(action)) {
435                 this.outStr.append("\nCreate new deparment with its employees");
436                 this.departmentFactory.setOutStr(this.outStr);
437                 this.departmentFactory.setPm(this.pm);
438                 this.departmentFactory.newDepartmentWithEmployees(
439                     this.pollsSync);
440             } else if (PARAMETER_NEW_PROJECT.equalsIgnoreCase(action)) {
441                 this.outStr.append("\nCreate new project with its members");
442                 this.projectFactory.setOutStr(this.outStr);
443                 this.projectFactory.setPm(this.pm);
444                 this.projectFactory.newProjectWithEmployees(this.pollsSync);
445             } else if (PARAMETER_SET_BOSS.equalsIgnoreCase(action)) {
446                 this.outStr.append(
447                     "\nUpdate the boss for a department's employees");
448                 this.departmentFactory.setOutStr(this.outStr);
449                 this.departmentFactory.setPm(this.pm);
450                 this.departmentFactory.setManagerForADepartment();
451             } else if (PARAMETER_NEW_EMPLOYEE.equalsIgnoreCase(action)) {
452                 this.outStr.append("\nCreate an employee");
453                 this.employeeFactory.setOutStr(this.outStr);
454                 this.employeeFactory.setPm(this.pm);
455                 this.employeeFactory.newEmployee(this.pollsSync);
456             } else if (PARAMETER_REM_EMPLOYEE.equalsIgnoreCase(action)) {
457                 this.outStr.append("\nDelete an employee");
458                 this.employeeFactory.setOutStr(this.outStr);
459                 this.employeeFactory.setPm(this.pm);
460                 this.employeeFactory.deleteEmployee(this.pollsSync);
461             } else if (PARAMETER_REM_PROJECT.equalsIgnoreCase(action)) {
462                 this.outStr.append("\nDelete a project");
463                 this.projectFactory.setOutStr(this.outStr);
464                 this.projectFactory.setPm(this.pm);
465                 this.projectFactory.deleteProject(this.pollsSync);
466             } else if (PARAMETER_SPLIT_PROJECT.equalsIgnoreCase(action)) {
467                 this.outStr.append("\nSplit a project");
468                 this.projectFactory.setOutStr(this.outStr);
469                 this.projectFactory.setPm(this.pm);
470                 this.projectFactory.splitProject(this.pollsSync);
471             } else if (PARAMETER_MERGE_DEPARTMENT.equalsIgnoreCase(action)) {
472                 this.outStr.append("\nMerge two departments");
473                 this.departmentFactory.setOutStr(this.outStr);
474                 this.departmentFactory.setPm(this.pm);
475                 this.departmentFactory.mergeDepartment(this.pollsSync);
476             } else if (PARAMETER_SPLIT_DEPARTMENT.equalsIgnoreCase(action)) {
477                 this.outStr.append("\nSplit a department");
478                 this.departmentFactory.setOutStr(this.outStr);
479                 this.departmentFactory.setPm(this.pm);
480                 this.departmentFactory.splitDepartment(this.pollsSync);
481             } else if (PARAMETER_INCREASE_SALARY.equalsIgnoreCase(action)) {
482                 this.outStr.append("\nIncrease salary");
483                 this.employeeFactory.setOutStr(this.outStr);
484                 this.employeeFactory.setPm(this.pm);
485                 this.employeeFactory.increaseSalary();
486             } else if (PARAMETER_GET_DEPARTMENT.equalsIgnoreCase(action)) {
487                 this.outStr.append("\nGet a department");
488                 this.departmentFactory.setOutStr(this.outStr);
489                 this.departmentFactory.setPm(this.pm);
490                 this.departmentFactory.getDepartment();
491             } else if (PARAMETER_GET_PROJECT.equalsIgnoreCase(action)) {
492                 this.outStr.append("\nGet a project");
493                 this.projectFactory.setOutStr(this.outStr);
494                 this.projectFactory.setPm(this.pm);
495                 this.projectFactory.getProject();
496             } else if (PARAMETER_GET_EMPLOYEE.equalsIgnoreCase(action)) {
497                 this.outStr.append("\nGet an employee");
498                 this.employeeFactory.setOutStr(this.outStr);
499                 this.employeeFactory.setPm(this.pm);
500                 this.employeeFactory.getEmployee();
501             } else if (PARAMETER_QUERY_PROJECTS.equalsIgnoreCase(action)) {
502                 this.outStr.append("\nGet some projects");
503                 this.projectFactory.setOutStr(this.outStr);
504                 this.projectFactory.setPm(this.pm);
505                 this.projectFactory.getProjects();
506             } else if (PARAMETER_QUERY_EMPLOYEES.equalsIgnoreCase(action)) {
507                 this.outStr.append("\nGet some persons");
508                 this.employeeFactory.setOutStr(this.outStr);
509                 this.employeeFactory.setPm(this.pm);
510                 this.employeeFactory.getEmployees();
511             } else {
512                 logger.log(BasicLevel.DEBUG, "Resets and shows pools");
513                 resetPolls(this.pm, new StringBuffer JavaDoc());
514             }
515             logger.log(BasicLevel.DEBUG, "End of action : " + action);
516             // commit the current transaction if required
517
if (needTrans) {
518                 logger.log(
519                     BasicLevel.DEBUG,
520                     "Valid the current transaction "
521                         + this.pm.currentTransaction().toString());
522                 this.pm.currentTransaction().setSynchronization(this.pollsSync);
523                 this.pm.currentTransaction().commit();
524             }
525         } catch (JDOFatalException e) {
526             if (logger.isLoggable(BasicLevel.DEBUG)) {
527                 logger.log(BasicLevel.DEBUG, "The action : '" + action
528                     + "' fails : Deadlock detected. Action canceled: ", e);
529             } else {
530                 logger.log(BasicLevel.WARN, "The action : '" + action
531                     + "' fails : Deadlock detected. Action canceled." + e.getMessage());
532             }
533             if (needTrans)
534                 this.pm.currentTransaction().rollback();
535
536             // if (!DatabaseImpl.resetPools) {
537
// DatabaseImpl.resetPools = true;
538
// this.doAction("", false);
539
// }
540
} catch (JDOException e) {
541             logger.log(
542                 BasicLevel.INFO,
543                 "The action : '"
544                     + action
545                     + "' fails : it throws a JDO exception.",
546                 e);
547             throw e;
548         } catch (Exception JavaDoc e) {
549             logger.log(
550                 BasicLevel.WARN,
551                 "The action : '" + action + "' fails : it throws an exception.",
552                 e);
553             throw e;
554         } finally {
555             this.persistenceManagerHolder.closePersistenceManager();
556         }
557         return this.outStr.toString();
558     }
559
560     //private static void removeFromPoll(Collection poll, long id) {
561
// poll.remove(new Long(id));
562
//}
563

564     private synchronized static void resetPolls(PersistenceManager pm, StringBuffer JavaDoc outStr)
565     throws JDOException, Exception JavaDoc {
566         DatabaseImpl.poolOfDepartmentId.clear();
567         DatabaseImpl.poolOfEmployeeId.clear();
568         DatabaseImpl.poolOfProjectId.clear();
569         DatabaseImpl.resetPools = true;
570         DatabaseImpl.initPolls(pm);
571         if (outStr != null) {
572             outStr.append("\nDo nothing and dump static poll contents");
573             outStr.append("\nDepartments:");
574             outStr.append(DatabaseImpl.poolOfDepartmentId.toString());
575             outStr.append("\nEmployees:");
576             outStr.append(DatabaseImpl.poolOfEmployeeId.toString());
577             outStr.append("\nProjects:");
578             outStr.append(DatabaseImpl.poolOfProjectId.toString());
579         }
580     }
581     
582     private static synchronized void initPolls(PersistenceManager pm)
583         throws JDOException, Exception JavaDoc {
584         if (!DatabaseImpl.resetPools)
585             return;
586         try {
587             if (DatabaseImpl.poolOfDepartmentId.size() == 0) {
588                 DatabaseImpl.initIdPoll(
589                     DatabaseImpl.poolOfDepartmentId,
590                     Department.class,
591                     pm);
592                 logger.log(
593                     BasicLevel.DEBUG,
594                     "Initialize the static pool of Departments Id : "
595                         + DatabaseImpl.poolOfDepartmentId.toString());
596             }
597             if (DatabaseImpl.poolOfProjectId.size() == 0) {
598                 DatabaseImpl.initIdPoll(
599                     DatabaseImpl.poolOfProjectId,
600                     Project.class,
601                     pm);
602                 logger.log(
603                     BasicLevel.DEBUG,
604                     "Initialize the static pool of Projects Id : "
605                         + DatabaseImpl.poolOfProjectId.toString());
606             }
607             if (DatabaseImpl.poolOfEmployeeId.size() == 0) {
608                 DatabaseImpl.initIdPoll(
609                     DatabaseImpl.poolOfEmployeeId,
610                     Employee.class,
611                     pm);
612                 logger.log(
613                     BasicLevel.DEBUG,
614                     "Initialize the static pool of Employees Id : "
615                         + DatabaseImpl.poolOfEmployeeId.toString());
616             }
617         } finally {
618             DatabaseImpl.resetPools = false;
619         }
620     }
621
622     private static void initIdPoll(
623         Collection JavaDoc poll,
624         Class JavaDoc c,
625         PersistenceManager pm)
626         throws JDOException, Exception JavaDoc {
627         Query query = pm.newQuery(c);
628         logger.log(
629             BasicLevel.DEBUG,
630             "(Re)Initialize static pool id for classe : " + c.getName());
631         Collection JavaDoc col = (Collection JavaDoc) query.execute();
632         Iterator JavaDoc it = col.iterator();
633         while (it.hasNext()) {
634             Object JavaDoc o = it.next();
635             try {
636                 poll.add(new Long JavaDoc(((DatabaseObjectInterface) o).getId()));
637             } catch (Exception JavaDoc e) {
638                 throw e;
639             }
640         }
641         query.close(col);
642     }
643
644     final private static long getIdFromPool(Vector JavaDoc poll) {
645         // Get an id from the pool.
646
while (DatabaseImpl.resetPools) {
647             try {
648                 logger.log(
649                     BasicLevel.DEBUG,
650                     "sleep until the end off static pool id reset...");
651                 Thread.sleep(10);
652             } catch (InterruptedException JavaDoc e) {
653             }
654         }
655         int alea = Alea.rand(1, poll.size());
656         Iterator JavaDoc it = poll.iterator();
657         long current = -1;
658         while (it.hasNext() && alea > 0) {
659             current = ((Long JavaDoc) it.next()).longValue();
660             alea--;
661             if (!it.hasNext())
662                 it = poll.iterator();
663         }
664         return current;
665     }
666
667     public static void initTestData(PMHolder pmHolder)
668         throws JDOException, Exception JavaDoc {
669         String JavaDoc str;
670         PersistenceManager pm = pmHolder.getPersistenceManager();
671         DatabaseImpl departmentImpl = null;
672         departmentImpl = new DatabaseImpl(pmHolder);
673         pm.evictAll();
674         Iterator JavaDoc objIter = null;
675         DatabaseImpl.poolOfDepartmentId.clear();
676         DatabaseImpl.poolOfEmployeeId.clear();
677         DatabaseImpl.poolOfProjectId.clear();
678         // remove all employee
679
Class JavaDoc[] classes = new Class JavaDoc[] {
680                 Employee.class,
681                 Address.class,
682                 Project.class,
683                 Department.class
684         };
685         pm.currentTransaction().begin();
686         for (int i = 0; i < classes.length; i++) {
687             logger.log(BasicLevel.DEBUG, "Removing " + classes[i].getName() + " ...");
688             pm.deletePersistentAll((Collection JavaDoc) pm.newQuery(classes[i]).execute());
689             logger.log(BasicLevel.INFO, "All " + classes[i].getName() + " have been removed.");
690         }
691         pm.currentTransaction().commit();
692
693         pm.evictAll();
694
695         pm.currentTransaction().begin();
696         logger.log(BasicLevel.INFO, "Init departments and employees data.");
697         for (int i = 0; i < DEPARTMENT_INIT_SIZE; i++) {
698             str = departmentImpl.doAction(DatabaseImpl.PARAMETER_NEW_DEPARTMENT);
699             logger.log(BasicLevel.DEBUG, str);
700         }
701         DatabaseImpl.resetPools = true;
702         logger.log(BasicLevel.INFO, "Init projects data.");
703         for (int i = 0; i < PROJECT_INIT_SIZE; i++) {
704             str = departmentImpl.doAction(DatabaseImpl.PARAMETER_NEW_PROJECT);
705             logger.log(BasicLevel.DEBUG, str);
706         }
707         DatabaseImpl.resetPools = true;
708         pm.currentTransaction().commit();
709         logger.log(BasicLevel.INFO, "Initial data set.");
710         resetPolls(pm, null);
711         pm.evictAll();
712         logger.log(BasicLevel.DEBUG, "Remove all cache entries.");
713         pmHolder.closePersistenceManager();
714         logger.log(BasicLevel.DEBUG, "Close the persistenceManager.");
715     }
716
717     /**
718      * Returns one of the existing department id
719      *
720      * @return a department id
721      */

722     public static long getDepartmentIdFromPool() {
723         //synchronized (DatabaseImpl.poolOfDepartmentId) {
724
return DatabaseImpl.getIdFromPool(DatabaseImpl.poolOfDepartmentId);
725         //}
726
}
727
728     /**
729      * Returns one of the existing employee id
730      *
731      * @return a employee id
732      */

733     public static long getEmployeeIdFromPool() {
734         //synchronized (DatabaseImpl.poolOfEmployeeId) {
735
return DatabaseImpl.getIdFromPool(DatabaseImpl.poolOfEmployeeId);
736         //}
737
}
738
739     /**
740      * Returns one of the existing project id
741      *
742      * @return a project id
743      */

744     public static long getProjectIdFromPool() {
745         //synchronized (DatabaseImpl.poolOfProjectId) {
746
return DatabaseImpl.getIdFromPool(DatabaseImpl.poolOfProjectId);
747         //}
748
}
749 }
Popular Tags