61dd24b2980cb1ef135c4e6fb5eae8e6fa4a47d9
[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.LinkedList;
9 import java.util.List;
10 import java.util.ListIterator;
11 import java.util.Vector;
12
13 import com.db4o.Db4oEmbedded;
14 import com.db4o.ObjectContainer;
15 import com.db4o.ObjectSet;
16 import com.db4o.config.EmbeddedConfiguration;
17 import com.db4o.cs.Db4oClientServer;
18 import com.db4o.cs.config.ClientConfiguration;
19 import com.db4o.query.Predicate;
20
21 import configuration.ConfigXML;
22 import domain.Account;
23 import domain.Administrator;
24 import domain.Booking;
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         @SuppressWarnings("static-access")
250         public void storeAdmin() {
251                 if (c.isDatabaseLocal() == false)
252                         openSDB();
253                 else
254                         openDB();
255                 try {
256
257                         List<Administrator> admL = db.query(new Predicate<Administrator>() {
258                                 /**
259                                  * 
260                                  */
261                                 private static final long serialVersionUID = 1L;
262
263                                 public boolean match(Administrator admin) {
264                                         return true;
265                                 }
266                         });
267
268                         admL.get(0).setAddRequest(
269                                         Administrator.getInstance().getAddRequest());
270                         admL.get(0).setRemoveRequest(
271                                         Administrator.getInstance().getRemoveRequest());
272                         admL.get(0).setNewOwnerRequest(
273                                         Administrator.getInstance().getNewOwnerRequest());
274                         db.commit();
275
276                 } catch (Exception e) {
277
278                 } finally {
279                         db.close();
280                 }
281
282         }
283
284         /**
285          * This method creates a book with a corresponding parameters
286          * 
287          * @param First
288          *            day, last day, house number and telephone
289          * @return a book
290          */
291         public Booking createBooking(RuralHouse ruralHouse, Date firstDate,
292                         Date lastDate, String bookTelephoneNumber)
293                         throws OfferCanNotBeBooked {
294
295                 if (c.isDatabaseLocal() == false)
296                         openSDB();
297                 else
298                         openDB();
299
300                 Booking bok = null;
301
302                 try {
303
304                         if (c.isDatabaseLocal() == false)
305                                 openSDB();
306
307                         RuralHouse proto = new RuralHouse(ruralHouse.getHouseName(), null,
308                                         ruralHouse.getDescription(), ruralHouse.getDistrict(), null);
309                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
310                         RuralHouse rh = (RuralHouse) result.next();
311
312                         Offer offer;
313                         offer = rh.findOffer(firstDate, lastDate);
314
315                         if (offer != null) {
316                                 offer.createBooking(theDB4oManagerAux.bookingNumber++,
317                                                 bookTelephoneNumber);
318                                 db.store(theDB4oManagerAux); // To store the new value for
319                                                                                                 // bookingNumber
320                                 db.store(offer);
321                                 db.commit();
322                                 bok = offer.getBooking();
323                         }
324
325                 } catch (com.db4o.ext.ObjectNotStorableException e) {
326                         System.out
327                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createBooking");
328                 } catch (Exception exc) {
329                         exc.printStackTrace();
330                 } finally {
331                         db.close();
332                 }
333                 return bok;
334         }
335
336         /**
337          * This method existing owners
338          * 
339          */
340         public Vector<Owner> getOwners() throws RemoteException, Exception {
341
342                 if (c.isDatabaseLocal() == false)
343                         openSDB();
344                 else
345                         openDB();
346
347                 try {
348                         Owner proto = new Owner(null, null, null);
349                         ObjectSet<Owner> result = db.queryByExample(proto);
350                         Vector<Owner> owners = new Vector<Owner>();
351                         while (result.hasNext())
352                                 owners.add((Owner) result.next());
353                         return owners;
354                 } finally {
355                         db.close();
356                 }
357         }
358
359         public Vector<RuralHouse> getAllRuralHouses() throws RemoteException,
360                         Exception {
361
362                 if (c.isDatabaseLocal() == false)
363                         openSDB();
364                 else
365                         openDB();
366
367                 try {
368                         RuralHouse proto = new RuralHouse(null, null, null, null, null);
369                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
370                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
371                         while (result.hasNext())
372                                 ruralHouses.add((RuralHouse) result.next());
373                         return ruralHouses;
374                 } finally {
375                         db.close();
376                 }
377         }
378
379         public boolean existsOverlappingOffer(RuralHouse rh, Date firstDay,
380                         Date lastDay) throws RemoteException, OverlappingOfferExists {
381
382                 if (c.isDatabaseLocal() == false)
383                         openSDB();
384                 else
385                         openDB();
386
387                 try {
388
389                         RuralHouse rhn = (RuralHouse) db.queryByExample(
390                                         new RuralHouse(rh.getHouseName(), null, null, null, null))
391                                         .next();
392                         if (rhn.overlapsWith(firstDay, lastDay) != null)
393                                 throw new OverlappingOfferExists();
394                         else
395                                 return false;
396                 } finally {
397                         db.close();
398                 }
399         }
400
401         public static ObjectContainer getContainer() {
402                 return db;
403         }
404
405         public void close() {
406                 db.close();
407                 System.out.println("DataBase closed");
408         }
409
410         public String toString() {
411                 return "bookingNumber=" + bookingNumber + " offerNumber=" + offerNumber;
412         }
413
414         /**
415          * @param usr
416          * @param ps
417          * @return
418          * @throws RemoteException
419          * @throws Exception
420          */
421         public Vector<Account> getAccount(Account proto) throws RemoteException,
422                         Exception {
423
424                 if (c.isDatabaseLocal() == false)
425                         openSDB();
426                 else
427                         openDB();
428
429                 try {
430                         ObjectSet<Account> result = db.queryByExample(proto);
431                         Vector<Account> accounts = new Vector<Account>();
432                         while (result.hasNext())
433                                 accounts.add((Account) result.next());
434                         return accounts;
435                 } finally {
436                         db.close();
437                 }
438         }
439
440         /**
441          * @param rh
442          */
443         public boolean storeRuralHouses(RuralHouse rh) {
444
445                 if (c.isDatabaseLocal() == false)
446                         openSDB();
447                 else
448                         openDB();
449
450                 boolean stored = false;
451                 RuralHouse house = new RuralHouse(rh.getHouseName(), null, null, null,
452                                 null);
453                 try {
454                         ObjectSet<RuralHouse> result = db.queryByExample(house);
455                         if (result.isEmpty()) {
456                                 Owner ow = (Owner) db.queryByExample(rh.getOwner()).get(0);
457                                 rh.setOwner(ow);
458                                 ow.addRuralHouse(rh);
459                                 db.store(rh);
460                                 db.commit();
461                                 stored = true;
462                         } else {
463                                 db.delete(result.get(0));
464                                 db.store(rh);
465                                 db.commit();
466                                 stored = true;
467                         }
468                 } finally {
469                         db.close();
470                 }
471                 return stored;
472         }
473
474         public void removeHouse(RuralHouse rh, Owner owner) {
475
476                 if (c.isDatabaseLocal() == false)
477                         openSDB();
478                 else
479                         openDB();
480                 try {
481                         ObjectSet<Owner> result = db.queryByExample(owner);
482                         ObjectSet<RuralHouse> rhs = db.queryByExample(rh);
483                         if (!rhs.isEmpty()) {
484                                 Owner found = result.get(0);
485                                 found.getRuralHouses().remove(rhs.get(0));
486                                 db.delete(rhs.get(0));
487                                 db.store(found);
488                                 db.commit();
489                         }
490                 } catch (Exception exc) {
491                         exc.printStackTrace();
492                 } finally {
493                         db.close();
494                 }
495
496         }
497
498         public Vector<RuralHouse> getRuralHouses(String name, String town,
499                         int nBed, int nKit, int nBath, int nPark, int nLiv) {
500                 HouseFeatures fea = new HouseFeatures(nBed, nKit, nBath, nLiv, nPark);
501                 RuralHouse rh = new RuralHouse(name, null, null, town, fea);
502                 if (c.isDatabaseLocal() == false)
503                         openSDB();
504                 else
505                         openDB();
506
507                 try {
508                         ObjectSet<RuralHouse> result = db.queryByExample(rh);
509                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
510                         while (result.hasNext())
511                                 ruralHouses.add(result.next());
512                         db.close();
513                         return ruralHouses;
514                 } catch (NullPointerException e) {
515                         return null;
516                 }
517
518         }
519
520         public boolean addAccount(Account acc) {
521                 if (c.isDatabaseLocal() == false)
522                         openSDB();
523                 else
524                         openDB();
525
526                 try {
527                                 //TODO realize if there is another account with same username. 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 }