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