4a1a964d515c20e2efb41aaca46d746b16cf5ff9
[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(Offer.class)
89                 .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 Administrator getAdminData() {
225                 if (c.isDatabaseLocal() == false)
226                         openSDB();
227                 else
228                         openDB();
229
230                 try {
231
232                         List<Administrator> admL = db.query(new Predicate<Administrator>() {
233                                 private static final long serialVersionUID = 1L;
234
235                                 public boolean match(Administrator admin) {
236                                         return true;
237                                 }
238                         });
239
240                         return admL.get(0);
241                 } finally {
242                         db.close();
243
244                 }
245
246         }
247
248         public void storeAdmin() {
249
250                 if (c.isDatabaseLocal() == false)
251                         openSDB();
252                 else
253                         openDB();
254                 try {
255
256                         List<Administrator> admL = db.query(new Predicate<Administrator>() {
257                                 /**
258                                  * 
259                                  */
260                                 private static final long serialVersionUID = 1L;
261
262                                 public boolean match(Administrator admin) {
263                                         return true;
264                                 }
265                         });
266
267                         admL.get(0).setAddRequest(
268                                         Administrator.getInstance().getAddRequest());
269                         admL.get(0).setRemoveRequest(
270                                         Administrator.getInstance().getRemoveRequest());
271                         admL.get(0).setNewOwnerRequest(
272                                         Administrator.getInstance().getNewOwnerRequest());
273
274                         db.commit();
275
276                 } catch (Exception e) {
277
278                 } finally {
279                         db.close();
280                 }
281
282         }
283
284         /**
285          * This method creates a book with a corresponding parameters
286          * 
287          * @param First
288          *            day, last day, house number and telephone
289          * @return a book
290          */
291         public Vector<Booking> createBooking(RuralHouse ruralHouse, Date firstDate,
292                         Date lastDate, Client cl) throws OfferCanNotBeBooked {
293
294                 if (c.isDatabaseLocal() == false)
295                         openSDB();
296                 else
297                         openDB();
298
299                 Vector<Booking> book = new Vector<Booking>();
300
301                 try {
302
303                         if (c.isDatabaseLocal() == false)
304                                 openSDB();
305
306                         RuralHouse proto = new RuralHouse(ruralHouse.getHouseName(), null,
307                                         ruralHouse.getDescription(), ruralHouse.getDistrict(), null);
308                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
309                         RuralHouse rh = (RuralHouse) result.next();
310
311                         Offer offer;
312                         offer = rh.findOffer(firstDate, lastDate);
313
314                         if (offer != null) {
315                                 offer.createBooking(theDB4oManagerAux.bookingNumber++, cl);
316                                 db.store(theDB4oManagerAux); // To store the new value for
317                                                                                                 // bookingNumber
318
319                                 db.store(offer);
320                                 db.commit();
321                                 book = offer.getBookings();
322
323                         }
324
325                 } catch (com.db4o.ext.ObjectNotStorableException e) {
326                         System.out
327                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createBooking");
328                 } catch (Exception exc) {
329                         exc.printStackTrace();
330                 } finally {
331                         db.close();
332                 }
333                 return book;
334         }
335
336         /**
337          * This method existing owners
338          * 
339          */
340         public Vector<Owner> getOwners() throws RemoteException, Exception {
341
342                 if (c.isDatabaseLocal() == false)
343                         openSDB();
344                 else
345                         openDB();
346
347                 try {
348                         Owner proto = new Owner(null, null, null);
349                         ObjectSet<Owner> result = db.queryByExample(proto);
350                         Vector<Owner> owners = new Vector<Owner>();
351                         while (result.hasNext())
352                                 owners.add((Owner) result.next());
353                         return owners;
354                 } finally {
355                         db.close();
356                 }
357         }
358
359         public Vector<RuralHouse> getAllRuralHouses() throws RemoteException,
360                         Exception {
361
362                 if (c.isDatabaseLocal() == false)
363                         openSDB();
364                 else
365                         openDB();
366
367                 try {
368                         RuralHouse proto = new RuralHouse(null, null, null, null, null);
369                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
370                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
371                         while (result.hasNext())
372                                 ruralHouses.add((RuralHouse) result.next());
373                         return ruralHouses;
374                 } finally {
375                         db.close();
376                 }
377         }
378
379         public boolean existsOverlappingOffer(RuralHouse rh, Date firstDay,
380                         Date lastDay) throws RemoteException, OverlappingOfferExists {
381
382                 if (c.isDatabaseLocal() == false)
383                         openSDB();
384                 else
385                         openDB();
386
387                 try {
388
389                         RuralHouse rhn = (RuralHouse) db.queryByExample(
390                                         new RuralHouse(rh.getHouseName(), null, null, null, null))
391                                         .next();
392                         if (rhn.overlapsWith(firstDay, lastDay) != null)
393                                 throw new OverlappingOfferExists();
394                         else
395                                 return false;
396                 } finally {
397                         db.close();
398                 }
399         }
400
401         public static ObjectContainer getContainer() {
402                 return db;
403         }
404
405         public void close() {
406                 db.close();
407                 System.out.println("DataBase closed");
408         }
409
410         public String toString() {
411                 return "bookingNumber=" + bookingNumber + " offerNumber=" + offerNumber;
412         }
413
414         /**
415          * @param usr
416          * @param ps
417          * @return
418          * @throws RemoteException
419          * @throws Exception
420          */
421         public Vector<Account> getAccount(Account proto) throws RemoteException,
422                         Exception {
423
424                 if (c.isDatabaseLocal() == false)
425                         openSDB();
426                 else
427                         openDB();
428
429                 try {
430                         ObjectSet<Account> result = db.queryByExample(proto);
431                         Vector<Account> accounts = new Vector<Account>();
432                         while (result.hasNext())
433                                 accounts.add((Account) result.next());
434                         return accounts;
435                 } finally {
436                         db.close();
437                 }
438         }
439
440         /**
441          * @param rh
442          */
443         public boolean storeRuralHouses(RuralHouse rh) {
444
445                 if (c.isDatabaseLocal() == false)
446                         openSDB();
447                 else
448                         openDB();
449
450                 boolean stored = false;
451                 RuralHouse house = new RuralHouse(rh.getHouseName(), null, null, null,
452                                 null);
453                 try {
454                         ObjectSet<RuralHouse> result = db.queryByExample(house);
455                         if (result.isEmpty()) {
456                                 Owner ow = (Owner) db.queryByExample(rh.getOwner()).get(0);
457                                 rh.setOwner(ow);
458                                 ow.addRuralHouse(rh);
459                                 db.store(rh);
460                                 db.commit();
461                                 stored = true;
462                         } else {
463                                 db.delete(result.get(0));
464                                 db.store(rh);
465                                 db.commit();
466                                 stored = true;
467                         }
468                 } finally {
469                         db.close();
470                 }
471                 return stored;
472         }
473
474         public void removeHouse(RuralHouse rh, Owner owner) {
475
476                 if (c.isDatabaseLocal() == false)
477                         openSDB();
478                 else
479                         openDB();
480                 try {
481                         ObjectSet<Owner> result = db.queryByExample(owner);
482                         ObjectSet<RuralHouse> rhs = db.queryByExample(rh);
483                         if (!rhs.isEmpty()) {
484                                 Owner found = result.get(0);
485                                 found.getRuralHouses().remove(rhs.get(0));
486                                 db.delete(rhs.get(0));
487                                 db.store(found);
488                                 db.commit();
489                         }
490                 } catch (Exception exc) {
491                         exc.printStackTrace();
492                 } finally {
493                         db.close();
494                 }
495
496         }
497
498         public Vector<RuralHouse> getRuralHouses(String name, String town,
499                         int nBed, int nKit, int nBath, int nPark, int nLiv) {
500                 HouseFeatures fea = new HouseFeatures(nBed, nKit, nBath, nLiv, nPark);
501                 RuralHouse rh = new RuralHouse(name, null, null, town, fea);
502                 if (c.isDatabaseLocal() == false)
503                         openSDB();
504                 else
505                         openDB();
506
507                 try {
508                         ObjectSet<RuralHouse> result = db.queryByExample(rh);
509                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
510                         while (result.hasNext())
511                                 ruralHouses.add(result.next());
512                         db.close();
513                         return ruralHouses;
514                 } catch (NullPointerException e) {
515                         return null;
516                 }
517
518         }
519
520         public boolean addAccount(Account acc) {
521                 if (c.isDatabaseLocal() == false)
522                         openSDB();
523                 else
524                         openDB();
525
526                 try {
527                         ObjectSet<Account> result = db.queryByExample(new Account(acc
528                                         .getUsername()));
529                         if (result.isEmpty()) {
530                                 db.store(acc);
531                                 db.commit();
532                                 return true;
533                         }
534                 } catch (Exception exc) {
535                         exc.printStackTrace();
536                 } finally {
537                         db.close();
538                 }
539                 return false;
540         }
541
542         // TODO remove account
543
544         public boolean removeAccount(Account acc) {
545                 if (c.isDatabaseLocal() == false)
546                         openSDB();
547                 else
548                         openDB();
549
550                 try {
551                         ObjectSet<Account> result = db.queryByExample(new Account(acc
552                                         .getUsername()));
553                         if (!result.isEmpty()) {
554                                 db.delete(result.get(0));
555                                 ;
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 void acceptBooking(Offer of) {
568                 Offer off = new Offer(of.getOfferNumber(), new RuralHouse(of
569                                 .getRuralHouse().getHouseName(), null, null, null, null), null,
570                                 null, 0);
571                 if (c.isDatabaseLocal() == false)
572                         openSDB();
573                 else
574                         openDB();
575
576                 try {
577                         ObjectSet<Offer> result = db.queryByExample(off);
578                         db.delete(result.get(0));
579                         RuralHouse rh = result.get(0).getRuralHouse();
580                         of.setRuralHouse(rh);
581                         rh.getAllOffers().remove(result.get(0));
582                         rh.getAllOffers().add(of);
583                         db.store(rh);
584                         db.close();
585
586                 } catch (Exception e) {
587                         e.printStackTrace();
588                         ;
589                 }
590         }
591
592         public void removeBooking(Booking b) {
593                 if (c.isDatabaseLocal() == false)
594                         openSDB();
595                 else
596                         openDB();
597                 try {
598                         ObjectSet<Booking> result = db.queryByExample(b);
599                         result.get(0).getOffer().getBookings().remove(b);
600                         db.store(result.get(0).getOffer());
601                         db.commit();
602                 } catch (Exception e) {
603                         e.printStackTrace();
604                         ;
605                 } finally {
606                         db.close();
607                 }
608
609         }
610 }