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