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