bookings were made to be taken from server per time they are searched
[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.List;
9 import java.util.ListIterator;
10 import java.util.Vector;
11
12 import com.db4o.Db4oEmbedded;
13 import com.db4o.ObjectContainer;
14 import com.db4o.ObjectSet;
15 import com.db4o.config.EmbeddedConfiguration;
16 import com.db4o.cs.Db4oClientServer;
17 import com.db4o.cs.config.ClientConfiguration;
18 import com.db4o.query.Predicate;
19
20 import configuration.ConfigXML;
21 import domain.Account;
22 import domain.Administrator;
23 import domain.Booking;
24 import domain.Client;
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
73                                         .queryByExample(DB4oManagerAux.class);
74                         ListIterator<DB4oManagerAux> listIter = res.listIterator();
75                         if (listIter.hasNext())
76                                 theDB4oManagerAux = (DB4oManagerAux) res.next();
77                 }
78         }
79
80         private static void openDB() {
81                 configuration = Db4oEmbedded.newConfiguration();
82                 configuration.common().activationDepth(c.getActivationDepth());
83                 configuration.common().updateDepth(c.getUpdateDepth());
84                 configuration.common().objectClass(Owner.class).cascadeOnDelete(true);
85                 configuration.common().objectClass(Booking.class).cascadeOnDelete(true);
86                 configuration.common().objectClass(RuralHouse.class)
87                                 .cascadeOnDelete(true);
88                 configuration.common().objectClass(Account.class).cascadeOnDelete(true);
89                 configuration.common().objectClass(Offer.class).cascadeOnDelete(true);
90                 configuration.common().objectClass(Owner.class).cascadeOnUpdate(true);
91                 configuration.common().objectClass(Booking.class).cascadeOnUpdate(true);
92                 configuration.common().objectClass(RuralHouse.class)
93                                 .cascadeOnUpdate(true);
94                 configuration.common().objectClass(Account.class).cascadeOnUpdate(true);
95                 configuration.common().objectClass(Offer.class).cascadeOnUpdate(true);
96                 configuration.common().objectClass(Account.class).cascadeOnUpdate(true);
97                 db = Db4oEmbedded.openFile(configuration, c.getDb4oFilename());
98         }
99
100         private void openSDB() {
101
102                 configurationCS = Db4oClientServer.newClientConfiguration();
103                 configurationCS.common().activationDepth(c.getActivationDepth());
104                 configurationCS.common().updateDepth(c.getUpdateDepth());
105                 configurationCS.common().objectClass(Owner.class).cascadeOnDelete(true);
106                 db = Db4oClientServer.openClient(configurationCS, c.getDatabaseNode(),
107                                 c.getDatabasePort(), c.getUser(), c.getPassword());
108
109         }
110
111         class DB4oManagerAux {
112                 int bookingNumber;
113                 int offerNumber;
114
115                 DB4oManagerAux(int bookingNumber, int offerNumber) {
116                         this.bookingNumber = bookingNumber;
117                         this.offerNumber = offerNumber;
118                 }
119         }
120
121         public static DB4oManager getInstance() throws Exception {
122                 if (theDB4oManager == null)
123                         theDB4oManager = new DB4oManager();
124                 return theDB4oManager;
125         }
126
127         public void initializeDB() {
128
129                 try {
130                         Owner jon = new Owner("Jon", "1349 5677 21 2133567777",
131                                         "Jon@gmail.com");
132                         Owner alfredo = new Owner("Alfredo", "4144 0087 23 9700002133",
133                                         "alfredo@gmail.com");
134                         jon.addRuralHouse("Ezkioko", "Ezkioko etxea", "Beatriz", 3, 3, 3,
135                                         3, 3);
136                         jon.addRuralHouse("Eskiatze", "Eskiatzeko etxea", "Guazate", 4, 4,
137                                         4, 4, 4);
138                         alfredo.addRuralHouse("Aitonako", "Casa del abuelo", "Vegas", 5, 5,
139                                         5, 5, 5);
140
141                         alfredo.addRuralHouse("Murgoitz", "", "Cedro", 6, 6, 6, 6, 6);
142                         Account jonAcc = new Account("1", "1", jon);
143                         Account alfredoAcc = new Account("userAlfredo", "passAlfredo",
144                                         alfredo);
145
146                         Account admin = new Account("admin", "admin", true);
147                         db.store(Administrator.getInstance());
148                         db.store(jonAcc);
149                         db.store(alfredoAcc);
150                         db.store(admin);
151                         db.commit();
152                 } finally {
153                         db.close();
154                 }
155         }
156
157         public void deleteDB() {
158
159                 if (c.isDatabaseLocal() == false)
160                         openSDB();
161                 else
162                         openDB();
163
164                 try {
165                         Owner proto = new Owner(null, null, null);
166                         ObjectSet<Owner> result = db.queryByExample(proto);
167                         while (result.hasNext()) {
168                                 Owner o = (Owner) result.next();
169                                 System.out.println("Deleted owner: " + o.toString());
170                                 db.delete(o);
171                         }
172                         db.commit();
173                 } finally {
174                         db.close();
175                 }
176         }
177
178         public Offer createOffer(RuralHouse ruralHouse, Date firstDay,
179                         Date lastDay, float price) throws RemoteException, Exception {
180                 Offer o = null;
181
182                 if (c.isDatabaseLocal() == false)
183                         openSDB();
184                 else
185                         openDB();
186
187                 try {
188
189                         RuralHouse proto = new RuralHouse(ruralHouse.getHouseName(), null,
190                                         null, null, null);
191                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
192                         RuralHouse rh = (RuralHouse) result.next();
193                         o = rh.createOffer(theDB4oManagerAux.offerNumber++, firstDay,
194                                         lastDay, price);
195                         db.store(theDB4oManagerAux); // To store the new value for
196                                                                                         // offerNumber
197                         db.store(o);
198                         db.commit();
199
200                 } catch (com.db4o.ext.ObjectNotStorableException e) {
201                         System.out
202                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createOffer");
203                 } finally {
204                         db.close();
205                 }
206                 return o;
207         }
208
209         public void deleteOffer(Offer offer) throws RemoteException, Exception {
210                 if (c.isDatabaseLocal() == false)
211                         openSDB();
212                 else
213                         openDB();
214
215                 try {
216                         ObjectSet<Offer> of = db.queryByExample(offer);
217                         RuralHouse rh = of.get(0).getRuralHouse();
218                         System.out.println(rh.getAllOffers().remove(of.get(0)));
219                         db.store(rh);
220                         db.commit();
221
222                 } catch (com.db4o.ext.ObjectNotStorableException e) {
223                         System.out
224                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createOffer");
225                 } finally {
226                         db.close();
227                 }
228         }
229
230         public Vector<Offer> getRHsOffer(String name) {
231                 if (c.isDatabaseLocal() == false)
232                         openSDB();
233                 else
234                         openDB();
235
236                 try {
237                         RuralHouse rh = (RuralHouse) db.queryByExample(
238                                         new RuralHouse(name, null, null, null, null)).get(0);
239                         Offer proto = new Offer(0, rh, null, null, 0);
240                         ObjectSet<Offer> result = db.queryByExample(proto);
241                         return new Vector<Offer>(result);
242                 } finally {
243                         db.close();
244                 }
245         }
246
247         public Administrator getAdminData() {
248
249                 if (c.isDatabaseLocal() == false)
250                         openSDB();
251                 else
252                         openDB();
253
254                 try {
255
256                         List<Administrator> admL = db.query(new Predicate<Administrator>() {
257                                 private static final long serialVersionUID = 1L;
258
259                                 public boolean match(Administrator admin) {
260                                         return true;
261                                 }
262                         });
263
264                         return admL.get(0);
265                 } finally {
266                         db.close();
267
268                 }
269
270         }
271
272         public void storeAdmin() {
273
274                 if (c.isDatabaseLocal() == false)
275                         openSDB();
276                 else
277                         openDB();
278                 try {
279
280                         List<Administrator> admL = db.query(new Predicate<Administrator>() {
281                                 /**
282                                  * 
283                                  */
284                                 private static final long serialVersionUID = 1L;
285
286                                 public boolean match(Administrator admin) {
287                                         return true;
288                                 }
289                         });
290
291                         admL.get(0).setAddRequest(
292                                         Administrator.getInstance().getAddRequest());
293                         admL.get(0).setRemoveRequest(
294                                         Administrator.getInstance().getRemoveRequest());
295                         admL.get(0).setNewOwnerRequest(
296                                         Administrator.getInstance().getNewOwnerRequest());
297
298                         db.commit();
299
300                 } catch (Exception e) {
301
302                 } finally {
303                         db.close();
304                 }
305
306         }
307
308         /**
309          * This method creates a book with a corresponding parameters
310          * 
311          * @param First
312          *            day, last day, house number and telephone
313          * @return a book
314          */
315         public Vector<Booking> createBooking(RuralHouse ruralHouse, Date firstDate,
316                         Date lastDate, Client cl) throws OfferCanNotBeBooked {
317
318                 if (c.isDatabaseLocal() == false)
319                         openSDB();
320                 else
321                         openDB();
322
323                 Vector<Booking> book = new Vector<Booking>();
324
325                 try {
326
327                         if (c.isDatabaseLocal() == false)
328                                 openSDB();
329
330                         RuralHouse proto = new RuralHouse(ruralHouse.getHouseName(), null,
331                                         null, null, null);
332                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
333                         RuralHouse rh = (RuralHouse) result.next();
334
335                         Offer offer;
336                         offer = (Offer)db.queryByExample(new Offer(0, rh, firstDate, lastDate, 0)).get(0);
337
338                         if (offer != null) {
339                                 offer.createBooking(theDB4oManagerAux.bookingNumber++, cl);
340                                 db.store(theDB4oManagerAux); // To store the new value for
341                                                                                                 // bookingNumber
342
343                                 db.store(offer);
344                                 db.commit();
345                                 book = offer.getBookings();
346
347                         }
348
349                 } catch (com.db4o.ext.ObjectNotStorableException e) {
350                         System.out
351                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createBooking");
352                 } catch (Exception exc) {
353                         exc.printStackTrace();
354                 } finally {
355                         db.close();
356                 }
357                 return book;
358         }
359
360         /**
361          * This method existing owners
362          * 
363          */
364         public Vector<Owner> getOwners() throws RemoteException, Exception {
365
366                 if (c.isDatabaseLocal() == false)
367                         openSDB();
368                 else
369                         openDB();
370
371                 try {
372                         Owner proto = new Owner(null, null, null);
373                         ObjectSet<Owner> result = db.queryByExample(proto);
374                         Vector<Owner> owners = new Vector<Owner>();
375                         while (result.hasNext())
376                                 owners.add((Owner) result.next());
377                         return owners;
378                 } finally {
379                         db.close();
380                 }
381         }
382
383
384
385         public boolean existsOverlappingOffer(RuralHouse rh, Date firstDay,
386                         Date lastDay) throws RemoteException, OverlappingOfferExists {
387
388                 if (c.isDatabaseLocal() == false)
389                         openSDB();
390                 else
391                         openDB();
392
393                 try {
394
395                         RuralHouse rhn = (RuralHouse) db.queryByExample(
396                                         new RuralHouse(rh.getHouseName(), null, null, null, null))
397                                         .next();
398                         if (rhn.overlapsWith(firstDay, lastDay) != null)
399                                 throw new OverlappingOfferExists();
400                         else
401                                 return false;
402                 } finally {
403                         db.close();
404                 }
405         }
406
407         public void close() {
408                 db.close();
409                 System.out.println("DataBase closed");
410         }
411
412         public String toString() {
413                 return "bookingNumber=" + bookingNumber + " offerNumber=" + offerNumber;
414         }
415
416         /**
417          * @param usr
418          * @param ps
419          * @return
420          * @throws RemoteException
421          * @throws Exception
422          */
423         public Vector<Account> getAccount(Account proto) throws RemoteException,
424                         Exception {
425
426                 if (c.isDatabaseLocal() == false)
427                         openSDB();
428                 else
429                         openDB();
430
431                 try {
432                         ObjectSet<Account> result = db.queryByExample(proto);
433                         Vector<Account> accounts = new Vector<Account>();
434                         while (result.hasNext())
435                                 accounts.add((Account) result.next());
436                         return accounts;
437                 } finally {
438                         db.close();
439                 }
440         }
441
442         /**
443          * @param rh
444          */
445         public boolean storeRuralHouses(RuralHouse rh) {
446
447                 if (c.isDatabaseLocal() == false)
448                         openSDB();
449                 else
450                         openDB();
451
452                 boolean stored = false;
453                 RuralHouse house = new RuralHouse(rh.getHouseName(), null, null, null,
454                                 null);
455                 try {
456                         ObjectSet<RuralHouse> result = db.queryByExample(house);
457                         if (result.isEmpty()) {
458                                 Owner ow = (Owner) db.queryByExample(rh.getOwner()).get(0);
459                                 rh.setOwner(ow);
460                                 ow.addRuralHouse(rh);
461                                 db.store(rh);
462                                 db.commit();
463                                 stored = true;
464                         } else {
465                                 db.delete(result.get(0));
466                                 db.store(rh);
467                                 db.commit();
468                                 stored = true;
469                         }
470                 } finally {
471                         db.close();
472                 }
473                 return stored;
474         }
475
476         public void removeHouse(RuralHouse rh, Owner owner) {
477
478                 if (c.isDatabaseLocal() == false)
479                         openSDB();
480                 else
481                         openDB();
482                 try {
483                         ObjectSet<Owner> result = db.queryByExample(owner);
484                         ObjectSet<RuralHouse> rhs = db.queryByExample(rh);
485                         if (!rhs.isEmpty()) {
486                                 Owner found = result.get(0);
487                                 found.getRuralHouses().remove(rhs.get(0));
488                                 db.delete(rhs.get(0));
489                                 db.store(found);
490                                 db.commit();
491                         }
492                 } catch (Exception exc) {
493                         exc.printStackTrace();
494                 } finally {
495                         db.close();
496                 }
497
498         }
499
500         public Vector<RuralHouse> getRuralHouses(Owner ow, String name,
501                         String town, int nBed, int nKit, int nBath, int nPark, int nLiv) {
502                 HouseFeatures fea = new HouseFeatures(nBed, nKit, nBath, nLiv, nPark);
503                 RuralHouse rh = new RuralHouse(name, ow, null, town, fea);
504                 if (c.isDatabaseLocal() == false)
505                         openSDB();
506                 else
507                         openDB();
508
509                 try {
510                         ObjectSet<RuralHouse> result = db.queryByExample(rh);
511                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
512                         while (result.hasNext())
513                                 ruralHouses.add(result.next());
514                         db.close();
515                         return ruralHouses;
516                 } catch (NullPointerException e) {
517                         return null;
518                 }
519
520         }
521
522         public boolean addAccount(Account acc) {
523                 if (c.isDatabaseLocal() == false)
524                         openSDB();
525                 else
526                         openDB();
527
528                 try {
529                         ObjectSet<Account> result = db.queryByExample(new Account(acc
530                                         .getUsername()));
531                         if (result.isEmpty()) {
532                                 db.store(acc);
533                                 db.commit();
534                                 return true;
535                         }
536                 } catch (Exception exc) {
537                         exc.printStackTrace();
538                 } finally {
539                         db.close();
540                 }
541                 return false;
542         }
543
544         public boolean removeAccount(Owner own) {
545                 if (c.isDatabaseLocal() == false)
546                         openSDB();
547                 else
548                         openDB();
549
550                 try {
551                         ObjectSet<Account> result = db.queryByExample(new Account(null,null,own));
552                         if (!result.isEmpty()) {
553                                 db.delete(result.get(0));
554                                 db.commit();
555                                 return true;
556                         }
557                 } catch (Exception exc) {
558                         exc.printStackTrace();
559                 } finally {
560                         db.close();
561                 }
562                 return false;
563         }
564
565         public void acceptBooking(Offer of) {
566                 Offer off = new Offer(of.getOfferNumber(), new RuralHouse(of
567                                 .getRuralHouse().getHouseName(), null, null, null, null), null,
568                                 null, 0);
569                 if (c.isDatabaseLocal() == false)
570                         openSDB();
571                 else
572                         openDB();
573
574                 try {
575                         ObjectSet<Offer> result = db.queryByExample(off);
576                         db.delete(result.get(0));
577                         RuralHouse rh = result.get(0).getRuralHouse();
578                         of.setRuralHouse(rh);
579                         rh.getAllOffers().remove(result.get(0));
580                         rh.getAllOffers().add(of);
581                         db.store(rh);
582                         db.close();
583
584                 } catch (Exception e) {
585                         e.printStackTrace();
586                         ;
587                 }
588         }
589
590         public void removeBooking(Booking b) {
591                 if (c.isDatabaseLocal() == false)
592                         openSDB();
593                 else
594                         openDB();
595                 try {
596                         Booking book = new Booking(b.getBookNumber(), new Offer(b
597                                         .getOffer().getOfferNumber(), new RuralHouse(b.getOffer()
598                                         .getRuralHouse().getHouseName(), null, null, null, null),
599                                         null, null, 0), b.getClient(), b.getBookDate());
600                         book.setOffer(null);
601                         db.delete(book);
602                         db.commit();
603                 } catch (Exception e) {
604                         e.printStackTrace();
605                 } finally {
606                         db.close();
607                 }
608
609         }
610
611         public Vector<Booking> getOfBok(Offer o) {
612                 if (c.isDatabaseLocal() == false)
613                         openSDB();
614                 else
615                         openDB();
616         
617                 try {
618                         Offer of = (Offer) db.queryByExample(
619                                         new Offer(0, o.getRuralHouse(), null, null, 0)).get(0);
620                         Booking proto = new Booking(0, of, null, null);
621                         ObjectSet<Booking> result = db.queryByExample(proto);
622                         return new Vector<Booking>(result);
623                 } finally {
624                         db.close();
625                 }
626         }
627 }