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