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