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