debugging
[RRRRHHHH_Code] / ruralHouses / src / dataAccess / DB4oManager.java
1 package dataAccess;
2
3 import java.io.File;
4 //import java.util.Enumeration;
5 //import java.util.Vector;
6 import java.rmi.RemoteException;
7 import java.util.Date;
8 import java.util.LinkedList;
9 import java.util.List;
10 import java.util.ListIterator;
11 import java.util.Vector;
12
13 import com.db4o.Db4oEmbedded;
14 import com.db4o.ObjectContainer;
15 import com.db4o.ObjectSet;
16 import com.db4o.config.EmbeddedConfiguration;
17 import com.db4o.cs.Db4oClientServer;
18 import com.db4o.cs.config.ClientConfiguration;
19 import com.db4o.query.Predicate;
20
21 import configuration.ConfigXML;
22 import domain.Account;
23 import domain.Administrator;
24 import domain.Booking;
25 import domain.HouseFeatures;
26 import domain.Offer;
27 //import dataModel.Offer;
28 import domain.Owner;
29 import domain.RuralHouse;
30 import exceptions.OfferCanNotBeBooked;
31 import exceptions.OverlappingOfferExists;
32
33 public class DB4oManager {
34
35         private static ObjectContainer db;
36         private static EmbeddedConfiguration configuration;
37         private static ClientConfiguration configurationCS;
38         private int bookingNumber = 0; // if it is "static" then it is not
39                                                                         // serialized
40         private int offerNumber = 0; // if it is "static" then it is not serialized
41         private static DB4oManager theDB4oManager = null;
42
43         private static DB4oManagerAux theDB4oManagerAux;
44
45         static ConfigXML c;
46
47         private DB4oManager() throws Exception {
48                 theDB4oManagerAux = new DB4oManagerAux(0, 0);
49                 c = ConfigXML.getInstance();
50                 System.out.println("Creating DB4oManager instance => isDatabaseLocal: "
51                                 + c.isDatabaseLocal() + " getDatabBaseOpenMode: "
52                                 + c.getDataBaseOpenMode());
53
54                 if ((c.getDataBaseOpenMode().equals("initialize"))
55                                 && (c.isDatabaseLocal()))
56                         new File(c.getDb4oFilename()).delete();
57
58                 if (c.isDatabaseLocal()) {
59                         openDB();
60                         System.out.println("DataBase opened");
61                 } else // c.isDatabaseLocal==false
62                 {
63                         openSDB();
64                         System.out.println("Remote DataBase opened");
65                 }
66                 if (c.getDataBaseOpenMode().equals("initialize")) {
67                         initializeDB();
68                         System.out.println("DataBase initialized");
69                 } else // c.getDataBaseOpenMode().equals("open")
70
71                 {
72                         ObjectSet<DB4oManagerAux> res = db.queryByExample(DB4oManagerAux.class);
73                         ListIterator<DB4oManagerAux> listIter = res.listIterator();
74                         if (listIter.hasNext())
75                                 theDB4oManagerAux = (DB4oManagerAux) res.next();
76                 }
77         }
78
79         private static void openDB() {
80                 configuration = Db4oEmbedded.newConfiguration();
81                 configuration.common().activationDepth(c.getActivationDepth());
82                 configuration.common().updateDepth(c.getUpdateDepth());
83                 configuration.common().objectClass(Owner.class).cascadeOnUpdate(true);
84                 configuration.common().objectClass(RuralHouse.class).cascadeOnUpdate(true);
85                 configuration.common().objectClass(Account.class).cascadeOnUpdate(true);
86                 db = Db4oEmbedded.openFile(configuration, c.getDb4oFilename());
87         }
88
89         private void openSDB() {
90
91                 configurationCS = Db4oClientServer.newClientConfiguration();
92                 configurationCS.common().activationDepth(c.getActivationDepth());
93                 configurationCS.common().updateDepth(c.getUpdateDepth());
94                 configurationCS.common().objectClass(Owner.class).cascadeOnDelete(true);
95                 db = Db4oClientServer.openClient(configurationCS, c.getDatabaseNode(),
96                                 c.getDatabasePort(), c.getUser(), c.getPassword());
97
98         }
99
100         class DB4oManagerAux {
101                 int bookingNumber;
102                 int offerNumber;
103
104                 DB4oManagerAux(int bookingNumber, int offerNumber) {
105                         this.bookingNumber = bookingNumber;
106                         this.offerNumber = offerNumber;
107                 }
108         }
109
110         public static DB4oManager getInstance() throws Exception {
111                 if (theDB4oManager == null)
112                         theDB4oManager = new DB4oManager();
113                 return theDB4oManager;
114         }
115
116         public void initializeDB() {
117
118                 try {
119                         Owner jon = new Owner("Jon");
120                         Owner alfredo = new Owner("Alfredo");
121                         jon.addRuralHouse("Ezkioko", "Ezkioko etxea", "Beatriz", 3, 3, 3,
122                                         3, 3);
123                         jon.addRuralHouse("Eskiatze", "Eskiatzeko etxea", "Guazate", 4, 4,
124                                         4, 4, 4);
125                         jon.setBankAccount("1349 5677 21 2133567777");
126                         alfredo.addRuralHouse("Aitonako", "Casa del abuelo", "Vegas", 5, 5,
127                                         5, 5, 5);
128                         
129                         alfredo.addRuralHouse("Murgoitz", "", "Cedro", 6, 6, 6, 6, 6);
130                         alfredo.setBankAccount("4144 0087 23 9700002133");
131                         Account jonAcc = new Account("userJon", "passJon", jon);
132                         Account alfredoAcc = new Account("userAlfredo", "passAlfredo",
133                                         alfredo);
134
135                         Account admin = new Account("admin","admin", true);
136                         db.store(Administrator.giveAdmin());
137                         db.store(jon);
138                         db.store(alfredo);
139                         db.store(jonAcc);
140                         db.store(alfredoAcc);
141                         db.store(admin);
142                         db.commit();
143                 } finally {
144                         db.close();     
145                 }
146         }
147
148         public void deleteDB() {
149
150                 if (c.isDatabaseLocal() == false)
151                         openSDB();
152                 else
153                         openDB();
154
155                 try {
156                         Owner proto = new Owner(null, null);
157                         ObjectSet<Owner> result = db.queryByExample(proto);
158                         while (result.hasNext()) {
159                                 Owner o = (Owner) result.next();
160                                 System.out.println("Deleted owner: " + o.toString());
161                                 db.delete(o);
162                         }
163                         db.commit();
164                 } finally {
165                         db.close();
166                 }
167         }
168
169         public Offer createOffer(RuralHouse ruralHouse, Date firstDay,
170                         Date lastDay, float price) throws RemoteException, Exception {
171                 Offer o = null;
172
173                 if (c.isDatabaseLocal() == false)
174                         openSDB();
175                 else
176                         openDB();
177
178                 try {
179
180                         RuralHouse proto = new RuralHouse(ruralHouse.getHouseName(), null,
181                                         null, null, null);
182                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
183                         RuralHouse rh = (RuralHouse) result.next();
184                         o = rh.createOffer(theDB4oManagerAux.offerNumber++, firstDay,
185                                         lastDay, price);
186                         db.store(theDB4oManagerAux); // To store the new value for
187                                                                                         // offerNumber
188                         db.store(o);
189                         db.commit();
190
191                 } catch (com.db4o.ext.ObjectNotStorableException e) {
192                         System.out
193                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createOffer");
194                 } finally {
195                         db.close();
196                 }
197                 return o;
198         }
199
200         
201         public void deleteOffer(Offer offer) throws RemoteException,
202                         Exception {
203                 if (c.isDatabaseLocal() == false)
204                         openSDB();
205                 else
206                         openDB();
207
208                 try {
209                         ObjectSet<Offer> of = db.queryByExample(offer);
210                         RuralHouse rh =of.get(0).getRuralHouse();
211                         System.out.println(rh.offers.remove(of.get(0)));
212                         db.store(rh);
213                         db.commit();
214
215                 } catch (com.db4o.ext.ObjectNotStorableException e) {
216                         System.out
217                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createOffer");
218                 } finally {
219                         db.close();
220                 }
221         }
222
223         
224         @SuppressWarnings("static-access")
225         public LinkedList<RuralHouse>[] getAdminData(){
226                 if (c.isDatabaseLocal() == false)
227                         openSDB();
228                 else
229                         openDB();
230                 @SuppressWarnings("unchecked")
231                 LinkedList<RuralHouse>[] ret =  new LinkedList[2];
232                 
233                 try {
234                         
235                         List<Administrator> admL = db.query(new Predicate<Administrator>(){
236                                 /**
237                                  * 
238                                  */
239                                 private static final long serialVersionUID = 1L;
240
241                                 public boolean match(Administrator admin){
242                                         return true;
243                                 }
244                         });
245                         
246                         ret[0] = admL.get(0).getAddRequest();
247                         ret[1] = admL.get(0).getRemoveRequest();
248                         return ret;
249                 }
250                 finally {
251                         db.close();
252                         
253                 }
254                 
255         }
256         
257         @SuppressWarnings("static-access")
258         public void storeAdmin() {
259                 if (c.isDatabaseLocal() == false)
260                         openSDB();
261                 else
262                         openDB();               
263                 try {
264                         
265                         List<Administrator> admL = db.query(new Predicate<Administrator>(){
266                                 /**
267                                  * 
268                                  */
269                                 private static final long serialVersionUID = 1L;
270
271                                 public boolean match(Administrator admin){
272                                         return true;
273                                 }
274                         });
275                         
276                         admL.get(0).setAddRequest(Administrator.getAddRequest());
277                         admL.get(0).setRemoveRequest(Administrator.getRemoveRequest());
278                         db.commit();
279                         
280                 }
281                 catch(Exception e){
282                         
283                 }
284                 finally {
285                         db.close();
286                 }
287                 
288                 
289         }
290         
291         
292         /**
293          * This method creates a book with a corresponding parameters
294          * 
295          * @param First
296          *            day, last day, house number and telephone
297          * @return a book
298          */
299         public Booking createBooking(RuralHouse ruralHouse, Date firstDate,
300                         Date lastDate, String bookTelephoneNumber)
301                         throws OfferCanNotBeBooked {
302
303                 if (c.isDatabaseLocal() == false)
304                         openSDB();
305                 else
306                         openDB();
307
308                 Booking bok = null;
309                 
310
311                 try {
312
313                         if (c.isDatabaseLocal() == false)
314                                 openSDB();
315
316                         RuralHouse proto = new RuralHouse(ruralHouse.getHouseName(), null,
317                                         ruralHouse.getDescription(), ruralHouse.getDistrict(), null);
318                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
319                         RuralHouse rh = (RuralHouse) result.next();
320
321                         Offer offer;
322                         offer = rh.findOffer(firstDate, lastDate);
323
324                         if (offer != null) {
325                                 offer.createBooking(theDB4oManagerAux.bookingNumber++,
326                                                 bookTelephoneNumber);
327                                 db.store(theDB4oManagerAux); // To store the new value for
328                                                                                                 // bookingNumber
329                                 db.store(offer);
330                                 db.commit();
331                                 bok = offer.getBooking();
332                         }
333
334                 } catch (com.db4o.ext.ObjectNotStorableException e) {
335                         System.out
336                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createBooking");
337                 } catch (Exception exc) {
338                         exc.printStackTrace();
339                 } finally {
340                         db.close();
341                 }
342                 return bok;
343         }
344
345         /**
346          * This method existing owners
347          * 
348          */
349         public Vector<Owner> getOwners() throws RemoteException, Exception {
350
351                 if (c.isDatabaseLocal() == false)
352                         openSDB();
353                 else
354                         openDB();
355
356                 try {
357                         Owner proto = new Owner(null, null);
358                         ObjectSet<Owner> result = db.queryByExample(proto);
359                         Vector<Owner> owners = new Vector<Owner>();
360                         while (result.hasNext())
361                                 owners.add((Owner) result.next());
362                         return owners;
363                 } finally {
364                         db.close();
365                 }
366         }
367
368         public Vector<RuralHouse> getAllRuralHouses() throws RemoteException,
369                         Exception {
370
371                 if (c.isDatabaseLocal() == false)
372                         openSDB();
373                 else
374                         openDB();
375
376                 try {
377                         RuralHouse proto = new RuralHouse(null, null, null, null, null);
378                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
379                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
380                         while (result.hasNext())
381                                 ruralHouses.add((RuralHouse) result.next());
382                         return ruralHouses;
383                 } finally {
384                         db.close();
385                 }
386         }
387
388         public boolean existsOverlappingOffer(RuralHouse rh, Date firstDay,
389                         Date lastDay) throws RemoteException, OverlappingOfferExists {
390
391                 if (c.isDatabaseLocal() == false)
392                         openSDB();
393                 else
394                         openDB();
395
396                 try {
397
398                         RuralHouse rhn = (RuralHouse) db.queryByExample(
399                                         new RuralHouse(rh.getHouseName(), null, null, null, null))
400                                         .next();
401                         if (rhn.overlapsWith(firstDay, lastDay) != null)
402                                 throw new OverlappingOfferExists();
403                         else
404                                 return false;
405                 } finally {
406                         db.close();
407                 }
408         }
409
410         public static ObjectContainer getContainer() {
411                 return db;
412         }
413
414         public void close() {
415                 db.close();
416                 System.out.println("DataBase closed");
417         }
418
419         public String toString() {
420                 return "bookingNumber=" + bookingNumber + " offerNumber=" + offerNumber;
421         }
422
423         /**
424          * @param usr
425          * @param pwd
426          * @return
427          * @throws RemoteException
428          * @throws Exception
429          */
430         public Vector<Account> getAccount(String usr, String pwd)
431                         throws RemoteException, Exception {
432
433                 if (c.isDatabaseLocal() == false)
434                         openSDB();
435                 else
436                         openDB();
437
438                 try {
439                         Account proto = new Account(usr, pwd, null);
440                         ObjectSet<Account> result = db.queryByExample(proto);
441                         Vector<Account> accounts = new Vector<Account>();
442                         while (result.hasNext())
443                                 accounts.add((Account) result.next());
444                         return accounts;
445                 } finally {
446                         db.close();
447                 }
448         }
449
450         /**
451          * @param rh
452          */
453         public boolean storeRuralHouses(RuralHouse rh) {
454
455                 if (c.isDatabaseLocal() == false)
456                         openSDB();
457                 else
458                         openDB();
459
460                 boolean stored = false;
461                 RuralHouse house = new RuralHouse(rh.getHouseName(), null, null, null,
462                                 null);
463                 try {
464                         ObjectSet<RuralHouse> result = db.queryByExample(house);
465                         if (result.isEmpty()) {
466                                 Owner ow = (Owner) db.queryByExample(rh.getOwner()).get(0);
467                                 ObjectSet<RuralHouse> orh = db.queryByExample(new RuralHouse(null, ow, null, null, null));
468                                 ow.addRuralHouse(rh);
469                                 for (RuralHouse aa: orh){
470                                         aa.setOwner(ow);
471                                 }
472                                 db.store(ow);
473                                 db.commit();
474                                 stored = true;
475                         } else {
476                                 db.delete(result.get(0));
477                                 db.store(rh);
478                                 db.commit();
479                                 stored = true;
480                         }
481                 } finally {
482                         db.close();
483                 }
484                 return stored;
485         }
486
487         public void removeHouse(RuralHouse rh, Owner owner) {
488
489                 if (c.isDatabaseLocal() == false)
490                         openSDB();
491                 else
492                         openDB();
493                 try {
494                         ObjectSet<Owner> result = db.queryByExample(owner);
495                         ObjectSet<RuralHouse> rhs = db.queryByExample(rh);
496                         if (!rhs.isEmpty()) {
497                                 Owner found =  result.get(0);
498                                 found.getRuralHouses().remove(rhs.get(0));
499                                 db.delete(rhs.get(0));
500                                 db.store(found);
501                                 db.commit();
502                         }
503                 } catch (Exception exc) {
504                         exc.printStackTrace();
505                 } finally {
506                         db.close();
507                 }
508
509         }
510
511
512         public Vector<RuralHouse> getRuralHouses(String name, String town,
513                         int nBed, int nKit, int nBath, int nPark, int nLiv) {
514                 HouseFeatures fea = new HouseFeatures(nBed, nKit, nBath, nLiv, nPark);
515                 RuralHouse rh = new RuralHouse(name, null, null, town, fea);
516                 if (c.isDatabaseLocal() == false)
517                         openSDB();
518                 else
519                         openDB();
520
521                 try {
522                         ObjectSet<RuralHouse> result = db.queryByExample(rh);
523                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
524                         while (result.hasNext())
525                                 ruralHouses.add(result.next());
526                         db.close();
527                         return ruralHouses;
528                 } catch (NullPointerException e) {
529                         return null;
530                 }
531
532         }
533
534         
535 }