KickJava   Java API By Example, From Geeks To Geeks.

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


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

22 package org.objectweb.speedo.j2eedo.bo;
23
24 import java.util.Calendar JavaDoc;
25 import java.util.Collection JavaDoc;
26 import java.util.Iterator JavaDoc;
27
28 import javax.jdo.JDOException;
29 import javax.jdo.PersistenceManager;
30 import javax.jdo.Query;
31
32 import org.objectweb.speedo.Alea;
33 import org.objectweb.speedo.j2eedo.database.Address;
34 import org.objectweb.speedo.j2eedo.database.Department;
35 import org.objectweb.speedo.j2eedo.database.Employee;
36 import org.objectweb.speedo.j2eedo.database.Project;
37 import org.objectweb.util.monolog.Monolog;
38 import org.objectweb.util.monolog.api.BasicLevel;
39 import org.objectweb.util.monolog.api.Logger;
40 import org.objectweb.util.monolog.api.LoggerFactory;
41
42 /**
43  * This class define the Java class to methods used to handle employee
44  * @author fmillevi@yahoo.com
45  *
46  */

47 public class EmployeeFactory {
48     static Logger logger = null;
49     private StringBuffer JavaDoc outStr;
50     private PersistenceManager pm;
51     static {
52         LoggerFactory lf = Monolog.initialize();
53         logger = lf.getLogger(DatabaseImpl.class.getName());
54     }
55
56
57     /**
58      * Initializes the StringBuffer used to store the treatment result
59      * @param outStr The outStr to set.
60      */

61     public void setOutStr(StringBuffer JavaDoc outStr) {
62         this.outStr = outStr;
63     }
64
65     /**
66      * Initializes the JDO persistence manager
67      * @param pm The pm to set.
68      */

69     public void setPm(PersistenceManager pm) {
70         this.pm = pm;
71     }
72
73     /**
74      * Creates a new employee in one of the existing department
75      * @throws JDOException
76      * @throws Exception
77      */

78     public void newEmployee(PollsSynchronizations pollsSync) throws JDOException, Exception JavaDoc {
79         long id = DatabaseImpl.getDepartmentIdFromPool();
80         Department d =
81             (Department) pm.getObjectById(
82                     pm.newObjectIdInstance(Department.class, Long.toString(id)),
83                     false);
84         this.outStr.append("\nCreate a new employee ");
85         Calendar JavaDoc cal = Calendar.getInstance();
86         cal.set(Alea.rand(1900, 2004), Alea.rand(1, 12), Alea.rand(1, 28));
87         Employee e =
88             new Employee(
89                     "First-" + Alea.randomstring(4, 5),
90                     "Last-" + Alea.randomstring(8, 10),
91                     cal.getTime(),
92                     d);
93         e.setSalary(Alea.rand(5000, 45000));
94         Address a = new Address();
95         a.setCity("City-" + Alea.randomstring(4, 5));
96         a.setStreet("Street-" + Alea.randomstring(4, 5));
97         a.setState("State-" + Alea.randomstring(4, 5));
98         a.setZipcode("ZIP-" + Alea.randomstring(2, 3));
99         e.setAddress(a);
100         pm.makePersistent(e);
101         logger.log(BasicLevel.DEBUG, "Create a new employee having id=" + e.getEmpid());
102
103         pollsSync.addInPool(DatabaseImpl.poolOfEmployeeId, e.getEmpid());
104         pm.setUserObject( pollsSync);
105
106     }
107
108     /**
109      * Deletes an existing employee
110      * @throws JDOException
111      * @throws Exception
112      */

113     public void deleteEmployee(PollsSynchronizations pollsSync) throws JDOException, Exception JavaDoc {
114         long id = DatabaseImpl.getEmployeeIdFromPool();
115         // remove id from static pool to avoid other threatment to use it
116
pollsSync.removeFromPool(DatabaseImpl.poolOfEmployeeId, id);
117         pm.setUserObject( pollsSync);
118         this.outStr.append("\nRemove the employee ");
119         this.outStr.append(id);
120         logger.log(BasicLevel.DEBUG, "Delete employee having id=" + id);
121         Employee e =
122             (Employee) pm.getObjectById(
123                     pm.newObjectIdInstance(Employee.class, Long.toString(id)),
124                     false);
125         Address a = e.getAddress();
126         pm.deletePersistent(a);
127         pm.deletePersistent(e);
128     }
129
130     /**
131      * Gets employee's data
132      * @throws JDOException
133      * @throws Exception
134      */

135     public void getEmployee() throws JDOException, Exception JavaDoc {
136         long id = DatabaseImpl.getEmployeeIdFromPool();
137         this.outStr.append("\nGet the employe id ");
138         this.outStr.append(id);
139         logger.log(BasicLevel.DEBUG, "Get employee having id=" + id);
140         Employee e =
141             (Employee) (Employee) pm.getObjectById(
142                     pm.newObjectIdInstance(Employee.class, Long.toString(id)),
143                     false);
144         this.outStr.append(e.getAsString());
145     }
146
147     /**
148      * Gets some employees. 4 queries are defines
149      * <ul><li>Get an employee by it's primary key</li>
150      * <li>Get employees having it's id between two values</li>
151      * <li>Get employees having the same manager</li>
152      * <li>Get employees member of one of 2 selected projects</li></ul>
153      * @throws JDOException
154      * @throws Exception
155      */

156     public void getEmployees() throws JDOException, Exception JavaDoc {
157         int testId = Alea.rand(0, 3);
158         switch (testId) {
159         case 0 :
160             this.queryEmployee();
161             break;
162         case 1 :
163             this.queryEmployeeArrayParameters();
164             break;
165         case 2 :
166             this.queryEmployeeByManager();
167             break;
168         case 3 :
169             this.queryEmployeeOrderHiredateByProject();
170             break;
171         }
172     }
173
174     /**
175      * Increases an employee' salary
176      * @throws JDOException
177      * @throws Exception
178      */

179     public void increaseSalary() throws JDOException, Exception JavaDoc {
180         long id = DatabaseImpl.getEmployeeIdFromPool();
181         this.outStr.append("\nIncrease salary for the employe ");
182         this.outStr.append(id);
183         logger.log(
184                 BasicLevel.DEBUG,
185                 "Increase the salary for the employee having id=" + id);
186         Employee e =
187             (Employee) pm.getObjectById(
188                     pm.newObjectIdInstance(Employee.class, Long.toString(id)),
189                     false);
190         e.setSalary(e.getSalary() + 1);
191     }
192
193     private void queryEmployee() throws JDOException, Exception JavaDoc {
194         long id = DatabaseImpl.getEmployeeIdFromPool();
195         logger.log(BasicLevel.DEBUG, "Query employee having id=" + id);
196         Query query = pm.newQuery(Employee.class);
197
198         String JavaDoc filter = "(empid==aId)";
199         String JavaDoc param = "long aId";
200
201         query.declareParameters(param);
202         query.setFilter(filter);
203
204         Collection JavaDoc col = (Collection JavaDoc) query.execute(new Long JavaDoc(id));
205         Iterator JavaDoc iter = col.iterator();
206         if (!iter.hasNext())
207             throw new Exception JavaDoc("TestInheritanceBasic query on employee does not return any row");
208         Employee e = (Employee) iter.next();
209         if (e.getEmpid() != id)
210             throw new Exception JavaDoc("TestInheritanceBasic query on employee returns an other row");
211         if (iter.hasNext())
212             throw new Exception JavaDoc("TestInheritanceBasic query on a employee returns to many rows");
213         this.outStr.append("\nEmployee full name ");
214         this.outStr.append(e.getFirstname());
215         this.outStr.append(" ");
216         this.outStr.append(e.getLastname());
217         query.close(col);
218     }
219
220     private void queryEmployeeOrderHiredateByProject()
221     throws JDOException, Exception JavaDoc {
222         Project p =
223             (Project) pm.getObjectById(
224                     pm.newObjectIdInstance(
225                             Project.class,
226                             Long.toString(
227                                     DatabaseImpl.getProjectIdFromPool())),
228                                             false);
229
230         this.outStr.append("\nLook for members of the project ");
231         this.outStr.append(p.getName());
232         logger.log(
233                 BasicLevel.DEBUG,
234                 "Query employee member of the project=" + p.getName());
235
236         Query query = pm.newQuery(Employee.class);
237
238         String JavaDoc filter = "(projects.contains(p))";
239         String JavaDoc params = "org.objectweb.speedo.j2eedo.database.Project p";
240         String JavaDoc sort = "hiredate ascending, salary descending";
241
242         query.declareParameters(params);
243         query.setFilter(filter);
244         query.setOrdering(sort);
245
246         Collection JavaDoc col = (Collection JavaDoc) query.execute(p);
247         Iterator JavaDoc iter = col.iterator();
248         if (!iter.hasNext())
249             throw new Exception JavaDoc("Query on employee does not return any row");
250         Employee e = null;
251         while (iter.hasNext()) {
252             e = (Employee) iter.next();
253             this.outStr.append("\n\tEmployee name:");
254             this.outStr.append(e.getFirstname());
255             this.outStr.append(" ");
256             this.outStr.append(e.getLastname());
257         }
258
259         query.close(col);
260     }
261
262     private void queryEmployeeArrayParameters()
263     throws JDOException, Exception JavaDoc {
264         long idMin =
265             DatabaseImpl.getEmployeeIdFromPool();
266         long idMax =
267             DatabaseImpl.getEmployeeIdFromPool();
268         while (idMin == idMax)
269             idMax =
270                 DatabaseImpl.getEmployeeIdFromPool();
271         //
272
if (idMin > idMax) {
273             // max < min ! inverse boundaries
274
long dummy = idMax;
275             idMax = idMin;
276             idMin = dummy;
277         }
278         this.outStr.append("\nLook for employees having id between ");
279         this.outStr.append(idMin);
280         this.outStr.append(" and ");
281         this.outStr.append(idMax);
282
283         logger.log(
284                 BasicLevel.DEBUG,
285                 "Query employee having id between " + idMin + " and " + idMax);
286
287         Long JavaDoc param[] = new Long JavaDoc[] { new Long JavaDoc(idMin), new Long JavaDoc(idMax)};
288         Query query = pm.newQuery(Employee.class);
289
290         String JavaDoc filter = "((empid>=idMin) && (empid<=idMax))";
291         String JavaDoc params = "long idMin, long idMax";
292         String JavaDoc ordering = "empid descending";
293
294         query.declareParameters(params);
295         query.setFilter(filter);
296         query.setOrdering(ordering);
297
298         Collection JavaDoc col = (Collection JavaDoc) query.executeWithArray(param);
299         Iterator JavaDoc iter = col.iterator();
300         if (!iter.hasNext())
301             throw new Exception JavaDoc("Query on employee does not return any row");
302         Employee e = (Employee) iter.next();
303         this.outStr.append("\n\tEmployee name (");
304         this.outStr.append(e.getEmpid());
305         this.outStr.append("): ");
306         this.outStr.append(e.getFirstname());
307         this.outStr.append(" ");
308         this.outStr.append(e.getLastname());
309         if (false && e.getEmpid() != idMax) {
310             throw new Exception JavaDoc("Query on employee returns an other first row than expecting");
311         }
312         while (iter.hasNext()) {
313             e = (Employee) iter.next();
314             this.outStr.append("\n\tEmployee name (");
315             this.outStr.append(e.getEmpid());
316             this.outStr.append("): ");
317             this.outStr.append(e.getFirstname());
318             this.outStr.append(" ");
319             this.outStr.append(e.getLastname());
320         }
321         if (false && e.getEmpid() != idMin)
322             throw new Exception JavaDoc("Query on employee returns an other last row than expecting");
323
324         query.close(col);
325     }
326
327     private void queryEmployeeByManager() throws JDOException, Exception JavaDoc {
328         Employee e =
329             (Employee) pm.getObjectById(
330                     pm.newObjectIdInstance(
331                             Employee.class,
332                             Long.toString(
333                                     DatabaseImpl.getEmployeeIdFromPool())),
334                                             false);
335
336         Employee boss = e.getManager();
337
338         this.outStr.append(
339         "\nLook for employees having the same manager : ");
340         if (null != boss)
341             this.outStr.append(boss.getLastname());
342         else
343             this.outStr.append("NULL");
344
345         logger.log(
346                 BasicLevel.DEBUG,
347                 "Query employee having the same manager :"
348                 +((null==boss)? "null" : boss.getLastname()));
349
350         Query query = pm.newQuery(Employee.class);
351
352         String JavaDoc filter = "(manager==e)";
353         String JavaDoc params = "org.objectweb.speedo.j2eedo.database.Employee e";
354
355         query.declareParameters(params);
356         query.setFilter(filter);
357
358         Collection JavaDoc col = (Collection JavaDoc) query.execute(boss);
359         Iterator JavaDoc iter = col.iterator();
360         e = null;
361         while (iter.hasNext()) {
362             e = (Employee) iter.next();
363             this.outStr.append("\n\tEmployee name:");
364             this.outStr.append(e.getFirstname());
365             this.outStr.append(" ");
366             this.outStr.append(e.getLastname());
367         }
368
369         query.close(col);
370     }
371 }
372
Popular Tags