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