Merge branch 'master' of https://xp-dev.com/git/RRRRHHHH_Code
[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)
89                 .cascadeOnDelete(true);
90                 configuration.common().objectClass(Offer.class).cascadeOnDelete(true);
91                 configuration.common().objectClass(Account.class).cascadeOnUpdate(true);
92                 db = Db4oEmbedded.openFile(configuration, c.getDb4oFilename());
93         }
94
95         private void openSDB() {
96
97                 configurationCS = Db4oClientServer.newClientConfiguration();
98                 configurationCS.common().activationDepth(c.getActivationDepth());
99                 configurationCS.common().updateDepth(c.getUpdateDepth());
100                 configurationCS.common().objectClass(Owner.class).cascadeOnDelete(true);
101                 db = Db4oClientServer.openClient(configurationCS, c.getDatabaseNode(),
102                                 c.getDatabasePort(), c.getUser(), c.getPassword());
103
104         }
105
106         class DB4oManagerAux {
107                 int bookingNumber;
108                 int offerNumber;
109
110                 DB4oManagerAux(int bookingNumber, int offerNumber) {
111                         this.bookingNumber = bookingNumber;
112                         this.offerNumber = offerNumber;
113                 }
114         }
115
116         public static DB4oManager getInstance() throws Exception {
117                 if (theDB4oManager == null)
118                         theDB4oManager = new DB4oManager();
119                 return theDB4oManager;
120         }
121
122         public void initializeDB() {
123
124                 try {
125                         Owner jon = new Owner("Jon", "1349 5677 21 2133567777",
126                                         "Jon@gmail.com");
127                         Owner alfredo = new Owner("Alfredo", "4144 0087 23 9700002133",
128                                         "alfredo@gmail.com");
129                         jon.addRuralHouse("Ezkioko", "Ezkioko etxea", "Beatriz", 3, 3, 3,
130                                         3, 3);
131                         jon.addRuralHouse("Eskiatze", "Eskiatzeko etxea", "Guazate", 4, 4,
132                                         4, 4, 4);
133                         alfredo.addRuralHouse("Aitonako", "Casa del abuelo", "Vegas", 5, 5,
134                                         5, 5, 5);
135
136                         alfredo.addRuralHouse("Murgoitz", "", "Cedro", 6, 6, 6, 6, 6);
137                         Account jonAcc = new Account("1", "1", jon);
138                         Account alfredoAcc = new Account("userAlfredo", "passAlfredo",
139                                         alfredo);
140
141                         Account admin = new Account("admin", "admin", true);
142                         db.store(Administrator.getInstance());
143                         db.store(jonAcc);
144                         db.store(alfredoAcc);
145                         db.store(admin);
146                         db.commit();
147                 } finally {
148                         db.close();
149                 }
150         }
151
152         public void deleteDB() {
153
154                 if (c.isDatabaseLocal() == false)
155                         openSDB();
156                 else
157                         openDB();
158
159                 try {
160                         Owner proto = new Owner(null, null, null);
161                         ObjectSet<Owner> result = db.queryByExample(proto);
162                         while (result.hasNext()) {
163                                 Owner o = (Owner) result.next();
164                                 System.out.println("Deleted owner: " + o.toString());
165                                 db.delete(o);
166                         }
167                         db.commit();
168                 } finally {
169                         db.close();
170                 }
171         }
172
173         public Offer createOffer(RuralHouse ruralHouse, Date firstDay,
174                         Date lastDay, float price) throws RemoteException, Exception {
175                 Offer o = null;
176
177                 if (c.isDatabaseLocal() == false)
178                         openSDB();
179                 else
180                         openDB();
181
182                 try {
183
184                         RuralHouse proto = new RuralHouse(ruralHouse.getHouseName(), null,
185                                         null, null, null);
186                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
187                         RuralHouse rh = (RuralHouse) result.next();
188                         o = rh.createOffer(theDB4oManagerAux.offerNumber++, firstDay,
189                                         lastDay, price);
190                         db.store(theDB4oManagerAux); // To store the new value for
191                                                                                         // offerNumber
192                         db.store(o);
193                         db.commit();
194
195                 } catch (com.db4o.ext.ObjectNotStorableException e) {
196                         System.out
197                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createOffer");
198                 } finally {
199                         db.close();
200                 }
201                 return o;
202         }
203
204         public void deleteOffer(Offer offer) throws RemoteException, Exception {
205                 if (c.isDatabaseLocal() == false)
206                         openSDB();
207                 else
208                         openDB();
209
210                 try {
211                         ObjectSet<Offer> of = db.queryByExample(offer);
212                         RuralHouse rh = of.get(0).getRuralHouse();
213                         System.out.println(rh.getAllOffers().remove(of.get(0)));
214                         db.store(rh);
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         }
224
225         public Vector<Offer> getRHsOffer(String name){
226                 if (c.isDatabaseLocal() == false)
227                         openSDB();
228                 else
229                         openDB();
230
231                 try {
232                         RuralHouse rh = (RuralHouse)db.queryByExample(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         
378         public Vector<RuralHouse> getAllRuralHouses() throws RemoteException,
379                         Exception {
380
381                 if (c.isDatabaseLocal() == false)
382                         openSDB();
383                 else
384                         openDB();
385
386                 try {
387                         RuralHouse proto = new RuralHouse(null, null, null, null, null);
388                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
389                         return new Vector<RuralHouse>(result);
390                 } finally {
391                         db.close();
392                 }
393         }
394
395         public boolean existsOverlappingOffer(RuralHouse rh, Date firstDay,
396                         Date lastDay) throws RemoteException, OverlappingOfferExists {
397
398                 if (c.isDatabaseLocal() == false)
399                         openSDB();
400                 else
401                         openDB();
402
403                 try {
404
405                         RuralHouse rhn = (RuralHouse) db.queryByExample(
406                                         new RuralHouse(rh.getHouseName(), null, null, null, null))
407                                         .next();
408                         if (rhn.overlapsWith(firstDay, lastDay) != null)
409                                 throw new OverlappingOfferExists();
410                         else
411                                 return false;
412                 } finally {
413                         db.close();
414                 }
415         }
416
417         public static ObjectContainer getContainer() {
418                 return db;
419         }
420
421         public void close() {
422                 db.close();
423                 System.out.println("DataBase closed");
424         }
425
426         public String toString() {
427                 return "bookingNumber=" + bookingNumber + " offerNumber=" + offerNumber;
428         }
429
430         /**
431          * @param usr
432          * @param ps
433          * @return
434          * @throws RemoteException
435          * @throws Exception
436          */
437         public Vector<Account> getAccount(Account proto) throws RemoteException,
438                         Exception {
439
440                 if (c.isDatabaseLocal() == false)
441                         openSDB();
442                 else
443                         openDB();
444
445                 try {
446                         ObjectSet<Account> result = db.queryByExample(proto);
447                         Vector<Account> accounts = new Vector<Account>();
448                         while (result.hasNext())
449                                 accounts.add((Account) result.next());
450                         return accounts;
451                 } finally {
452                         db.close();
453                 }
454         }
455
456         /**
457          * @param rh
458          */
459         public boolean storeRuralHouses(RuralHouse rh) {
460
461                 if (c.isDatabaseLocal() == false)
462                         openSDB();
463                 else
464                         openDB();
465
466                 boolean stored = false;
467                 RuralHouse house = new RuralHouse(rh.getHouseName(), null, null, null,
468                                 null);
469                 try {
470                         ObjectSet<RuralHouse> result = db.queryByExample(house);
471                         if (result.isEmpty()) {
472                                 Owner ow = (Owner) db.queryByExample(rh.getOwner()).get(0);
473                                 rh.setOwner(ow);
474                                 ow.addRuralHouse(rh);
475                                 db.store(rh);
476                                 db.commit();
477                                 stored = true;
478                         } else {
479                                 db.delete(result.get(0));
480                                 db.store(rh);
481                                 db.commit();
482                                 stored = true;
483                         }
484                 } finally {
485                         db.close();
486                 }
487                 return stored;
488         }
489
490         public void removeHouse(RuralHouse rh, Owner owner) {
491
492                 if (c.isDatabaseLocal() == false)
493                         openSDB();
494                 else
495                         openDB();
496                 try {
497                         ObjectSet<Owner> result = db.queryByExample(owner);
498                         ObjectSet<RuralHouse> rhs = db.queryByExample(rh);
499                         if (!rhs.isEmpty()) {
500                                 Owner found = result.get(0);
501                                 found.getRuralHouses().remove(rhs.get(0));
502                                 db.delete(rhs.get(0));
503                                 db.store(found);
504                                 db.commit();
505                         }
506                 } catch (Exception exc) {
507                         exc.printStackTrace();
508                 } finally {
509                         db.close();
510                 }
511
512         }
513
514         public Vector<RuralHouse> getRuralHouses(Owner ow, String name, String town,
515                         int nBed, int nKit, int nBath, int nPark, int nLiv) {
516                 HouseFeatures fea = new HouseFeatures(nBed, nKit, nBath, nLiv, nPark);
517                 RuralHouse rh = new RuralHouse(name, ow, null, town, fea);
518                 if (c.isDatabaseLocal() == false)
519                         openSDB();
520                 else
521                         openDB();
522
523                 try {
524                         ObjectSet<RuralHouse> result = db.queryByExample(rh);
525                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
526                         while (result.hasNext())
527                                 ruralHouses.add(result.next());
528                         db.close();
529                         return ruralHouses;
530                 } catch (NullPointerException e) {
531                         return null;
532                 }
533
534         }
535
536         public boolean addAccount(Account acc) {
537                 if (c.isDatabaseLocal() == false)
538                         openSDB();
539                 else
540                         openDB();
541
542                 try {
543                         ObjectSet<Account> result = db.queryByExample(new Account(acc
544                                         .getUsername()));
545                         if (result.isEmpty()) {
546                                 db.store(acc);
547                                 db.commit();
548                                 return true;
549                         }
550                 } catch (Exception exc) {
551                         exc.printStackTrace();
552                 } finally {
553                         db.close();
554                 }
555                 return false;
556         }
557
558         public boolean removeAccount(Owner own) {
559                 if (c.isDatabaseLocal() == false)
560                         openSDB();
561                 else
562                         openDB();
563
564                 try {
565                         ObjectSet<Account> result = db.queryByExample(new Account(own));
566                         if (!result.isEmpty()) {
567                                 db.delete(result.get(0));
568                                 db.commit();
569                                 return true;
570                         }
571                 } catch (Exception exc) {
572                         exc.printStackTrace();
573                 } finally {
574                         db.close();
575                 }
576                 return false;
577         }
578
579         public void acceptBooking(Offer of) {
580                 Offer off = new Offer(of.getOfferNumber(), new RuralHouse(of
581                                 .getRuralHouse().getHouseName(), null, null, null, null), null,
582                                 null, 0);
583                 if (c.isDatabaseLocal() == false)
584                         openSDB();
585                 else
586                         openDB();
587
588                 try {
589                         ObjectSet<Offer> result = db.queryByExample(off);
590                         db.delete(result.get(0));
591                         RuralHouse rh = result.get(0).getRuralHouse();
592                         of.setRuralHouse(rh);
593                         rh.getAllOffers().remove(result.get(0));
594                         rh.getAllOffers().add(of);
595                         db.store(rh);
596                         db.close();
597
598                 } catch (Exception e) {
599                         e.printStackTrace();
600                         ;
601                 }
602         }
603
604         public void removeBooking(Booking b) {
605                 if (c.isDatabaseLocal() == false)
606                         openSDB();
607                 else
608                         openDB();
609                 try {
610                         ObjectSet<Booking> result = db.queryByExample(b);
611                         result.get(0).getOffer().getBookings().remove(b);
612                         db.store(result.get(0).getOffer());
613                         db.delete(result.get(0));
614                         db.commit();
615                 } catch (Exception e) {
616                         e.printStackTrace();
617                 } finally {
618                         db.close();
619                 }
620
621         }
622 }