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