eb80b8683c4da08b38d5f17d98cf1d0f9c48eed2
[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
8
9 import java.util.Date;
10 import java.util.LinkedList;
11 import java.util.List;
12 import java.util.ListIterator;
13 import java.util.Vector;
14
15
16 import com.db4o.Db4oEmbedded;
17 import com.db4o.ObjectContainer;
18 import com.db4o.ObjectSet;
19 import com.db4o.config.EmbeddedConfiguration;
20 import com.db4o.cs.Db4oClientServer;
21 import com.db4o.cs.config.ClientConfiguration;
22 import com.db4o.query.Predicate;
23
24 import configuration.ConfigXML;
25 import domain.Account;
26 import domain.Administrator;
27 import domain.Booking;
28 import domain.HouseFeatures;
29 import domain.Offer;
30 //import dataModel.Offer;
31 import domain.Owner;
32 import domain.RuralHouse;
33 import exceptions.OfferCanNotBeBooked;
34 import exceptions.OverlappingOfferExists;
35
36 public class DB4oManager {
37
38         private static ObjectContainer db;
39         private static EmbeddedConfiguration configuration;
40         private static ClientConfiguration configurationCS;
41         private int bookingNumber = 0; // if it is "static" then it is not
42                                                                         // serialized
43         private int offerNumber = 0; // if it is "static" then it is not serialized
44         private static DB4oManager theDB4oManager = null;
45
46         private static DB4oManagerAux theDB4oManagerAux;
47
48         static ConfigXML c;
49
50         private DB4oManager() throws Exception {
51                 theDB4oManagerAux = new DB4oManagerAux(0, 0);
52                 c = ConfigXML.getInstance();
53                 System.out.println("Creating DB4oManager instance => isDatabaseLocal: "
54                                 + c.isDatabaseLocal() + " getDatabBaseOpenMode: "
55                                 + c.getDataBaseOpenMode());
56
57                 if ((c.getDataBaseOpenMode().equals("initialize"))
58                                 && (c.isDatabaseLocal()))
59                         new File(c.getDb4oFilename()).delete();
60
61                 if (c.isDatabaseLocal()) {
62                         openDB();
63                         System.out.println("DataBase opened");
64                 } else // c.isDatabaseLocal==false
65                 {
66                         openSDB();
67                         System.out.println("Remote DataBase opened");
68                 }
69                 if (c.getDataBaseOpenMode().equals("initialize")) {
70                         initializeDB();
71                         System.out.println("DataBase initialized");
72                 } else // c.getDataBaseOpenMode().equals("open")
73
74                 {
75                         ObjectSet res = db.queryByExample(DB4oManagerAux.class);
76                         ListIterator listIter = res.listIterator();
77                         if (listIter.hasNext())
78                                 theDB4oManagerAux = (DB4oManagerAux) res.next();
79                 }
80         }
81
82         private static void openDB() {
83                 configuration = Db4oEmbedded.newConfiguration();
84                 configuration.common().activationDepth(c.getActivationDepth());
85                 configuration.common().updateDepth(c.getUpdateDepth());
86                 configuration.common().objectClass(Owner.class).cascadeOnDelete(true);
87                 db = Db4oEmbedded.openFile(configuration, c.getDb4oFilename());
88         }
89
90         private void openSDB() {
91
92                 configurationCS = Db4oClientServer.newClientConfiguration();
93                 configurationCS.common().activationDepth(c.getActivationDepth());
94                 configurationCS.common().updateDepth(c.getUpdateDepth());
95                 configurationCS.common().objectClass(Owner.class).cascadeOnDelete(true);
96                 db = Db4oClientServer.openClient(configurationCS, c.getDatabaseNode(),
97                                 c.getDatabasePort(), c.getUser(), c.getPassword());
98
99         }
100
101         class DB4oManagerAux {
102                 int bookingNumber;
103                 int offerNumber;
104
105                 DB4oManagerAux(int bookingNumber, int offerNumber) {
106                         this.bookingNumber = bookingNumber;
107                         this.offerNumber = offerNumber;
108                 }
109         }
110
111         public static DB4oManager getInstance() throws Exception {
112                 if (theDB4oManager == null)
113                         theDB4oManager = new DB4oManager();
114                 return theDB4oManager;
115         }
116
117         public void initializeDB() {
118
119                 try {
120                         Owner jon = new Owner("Jon");
121                         Owner alfredo = new Owner("Alfredo");
122                         jon.addRuralHouse("Ezkioko", "Ezkioko etxea", "Beatriz", 3, 3, 3,
123                                         3, 3);
124                         jon.addRuralHouse("Eskiatze", "Eskiatzeko etxea", "Guazate", 4, 4,
125                                         4, 4, 4);
126                         jon.setBankAccount("1349 5677 21 2133567777");
127                         alfredo.addRuralHouse("Aitonako", "Casa del abuelo", "Vegas", 5, 5,
128                                         5, 5, 5);
129                         
130                         alfredo.addRuralHouse("Murgoitz", "", "Cedro", 6, 6, 6, 6, 6);
131                         alfredo.setBankAccount("4144 0087 23 9700002133");
132                         Account jonAcc = new Account("userJon", "passJon", jon);
133                         Account alfredoAcc = new Account("userAlfredo", "passAlfredo",
134                                         alfredo);
135
136                         Account admin = new Account("admin","admin", true);
137                         db.store(Administrator.giveAdmin());
138                         db.store(jon);
139                         db.store(alfredo);
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);
158                         ObjectSet result = db.queryByExample(proto);
159                         Vector<Owner> owners = new Vector<Owner>();
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         
203         public void deleteOffer(Offer offer) throws RemoteException,
204                         Exception {
205                 if (c.isDatabaseLocal() == false)
206                         openSDB();
207                 else
208                         openDB();
209
210                 try {
211                         ObjectSet<Offer> of = db.queryByExample(offer);
212                         RuralHouse rh =of.get(0).getRuralHouse();
213                         System.out.println(rh.offers.remove(of.get(0)));
214                         db.store(rh);
215                         db.commit();
216
217                 } catch (com.db4o.ext.ObjectNotStorableException e) {
218                         System.out
219                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createOffer");
220                 } finally {
221                         db.close();
222                 }
223         }
224
225         
226         public LinkedList<RuralHouse>[] getAdminData(){
227                 if (c.isDatabaseLocal() == false)
228                         openSDB();
229                 else
230                         openDB();
231                 LinkedList<RuralHouse>[] ret =  new LinkedList[2];
232                 
233                 try {
234                         
235                         List<Administrator> admL = db.query(new Predicate<Administrator>(){
236                                 public boolean match(Administrator admin){
237                                         return true;
238                                 }
239                         });
240                         
241                         ret[0] = admL.get(0).getAddRequest();
242                         ret[1] = admL.get(0).getRemoveRequest();
243                         return ret;
244                 }
245                 finally {
246                         db.close();
247                         
248                 }
249                 
250         }
251         
252         public void storeAdmin() {
253                 if (c.isDatabaseLocal() == false)
254                         openSDB();
255                 else
256                         openDB();               
257                 try {
258                         
259                         List<Administrator> admL = db.query(new Predicate<Administrator>(){
260                                 public boolean match(Administrator admin){
261                                         return true;
262                                 }
263                         });
264                         
265                         admL.get(0).setAddRequest(Administrator.getAddRequest());
266                         admL.get(0).setRemoveRequest(Administrator.getRemoveRequest());
267                         db.commit();
268                         
269                 }
270                 catch(Exception e){
271                         
272                 }
273                 finally {
274                         db.close();
275                 }
276                 
277                 
278         }
279         
280         
281         /**
282          * This method creates a book with a corresponding parameters
283          * 
284          * @param First
285          *            day, last day, house number and telephone
286          * @return a book
287          */
288         public Booking createBooking(RuralHouse ruralHouse, Date firstDate,
289                         Date lastDate, String bookTelephoneNumber)
290                         throws OfferCanNotBeBooked {
291
292                 if (c.isDatabaseLocal() == false)
293                         openSDB();
294                 else
295                         openDB();
296
297                 Booking bok = null;
298                 
299
300                 try {
301
302                         if (c.isDatabaseLocal() == false)
303                                 openSDB();
304
305                         RuralHouse proto = new RuralHouse(ruralHouse.getHouseName(), null,
306                                         ruralHouse.getDescription(), ruralHouse.getDistrict(), null);
307                         ObjectSet result = db.queryByExample(proto);
308                         RuralHouse rh = (RuralHouse) result.next();
309
310                         Offer offer;
311                         offer = rh.findOffer(firstDate, lastDate);
312
313                         if (offer != null) {
314                                 offer.createBooking(theDB4oManagerAux.bookingNumber++,
315                                                 bookTelephoneNumber);
316                                 db.store(theDB4oManagerAux); // To store the new value for
317                                                                                                 // bookingNumber
318                                 db.store(offer);
319                                 db.commit();
320                                 bok = offer.getBooking();
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 bok;
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);
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 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 pwd
415          * @return
416          * @throws RemoteException
417          * @throws Exception
418          */
419         public Vector<Account> getAccount(String usr, String pwd)
420                         throws RemoteException, Exception {
421
422                 if (c.isDatabaseLocal() == false)
423                         openSDB();
424                 else
425                         openDB();
426
427                 try {
428                         Account proto = new Account(usr, pwd, null);
429                         ObjectSet<Account> result = db.queryByExample(proto);
430                         Vector<Account> accounts = new Vector<Account>();
431                         while (result.hasNext())
432                                 accounts.add((Account) result.next());
433                         return accounts;
434                 } finally {
435                         db.close();
436                 }
437         }
438
439         /**
440          * @param rh
441          */
442         public boolean storeRuralHouses(RuralHouse rh) {
443
444                 if (c.isDatabaseLocal() == false)
445                         openSDB();
446                 else
447                         openDB();
448
449                 boolean stored = false;
450                 RuralHouse house = new RuralHouse(rh.getHouseName(), null, null, null,
451                                 null);
452                 try {
453                         ObjectSet<Owner> result = db.queryByExample(house);
454                         if (result.isEmpty()) {
455                                 db.store(rh);
456                                 db.commit();
457                                 stored = true;
458                         } else {
459                                 db.delete(result.get(0));
460                                 db.store(rh);
461                                 db.commit();
462                                 stored = true;
463                         }
464                 } finally {
465                         db.close();
466                 }
467                 return stored;
468         }
469
470         public void removeHouse(RuralHouse rh, Owner owner) {
471
472                 if (c.isDatabaseLocal() == false)
473                         openSDB();
474                 else
475                         openDB();
476                 try {
477                         ObjectSet<Owner> result = db.queryByExample(owner);
478                         ObjectSet<RuralHouse> rhs = db.queryByExample(rh);
479                         if (!rhs.isEmpty()) {
480                                 Owner found =  result.get(0);
481                                 found.getRuralHouses().remove(rhs.get(0));
482                                 db.store(found);
483                                 db.commit();
484                         }
485                 } catch (Exception exc) {
486                         exc.printStackTrace();
487                 } finally {
488                         db.close();
489                 }
490
491         }
492
493
494         public Vector<RuralHouse> getRuralHouses(String name, String town,
495                         int nBed, int nKit, int nBath, int nPark, int nLiv) {
496                 HouseFeatures fea = new HouseFeatures(nBed, nKit, nBath, nLiv, nPark);
497                 RuralHouse rh = new RuralHouse(name, null, null, town, fea);
498                 if (c.isDatabaseLocal() == false)
499                         openSDB();
500                 else
501                         openDB();
502
503                 try {
504                         ObjectSet<RuralHouse> result = db.queryByExample(rh);
505                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
506                         while (result.hasNext())
507                                 ruralHouses.add(result.next());
508                         db.close();
509                         return ruralHouses;
510                 } catch (NullPointerException e) {
511                         return null;
512                 }
513
514         }
515
516         
517 }