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