0e6e881961d927f4789e389a255683b2db844ff4
[RRRRHHHH_Code] / ruralHouses / src / dataAccess / DB4oManager.java
1 package dataAccess;
2
3 import java.io.File;
4 //import java.util.Enumeration;
5 //import java.util.Vector;
6 import java.rmi.RemoteException;
7 import java.util.Date;
8 import java.util.LinkedList;
9 import java.util.List;
10 import java.util.ListIterator;
11 import java.util.Vector;
12
13 import com.db4o.Db4oEmbedded;
14 import com.db4o.ObjectContainer;
15 import com.db4o.ObjectSet;
16 import com.db4o.config.EmbeddedConfiguration;
17 import com.db4o.cs.Db4oClientServer;
18 import com.db4o.cs.config.ClientConfiguration;
19 import com.db4o.query.Predicate;
20
21 import configuration.ConfigXML;
22 import domain.Account;
23 import domain.Administrator;
24 import domain.Booking;
25 import domain.HouseFeatures;
26 import domain.Offer;
27 //import dataModel.Offer;
28 import domain.Owner;
29 import domain.RuralHouse;
30 import exceptions.OfferCanNotBeBooked;
31 import exceptions.OverlappingOfferExists;
32
33 public class DB4oManager {
34
35         private static ObjectContainer db;
36         private static EmbeddedConfiguration configuration;
37         private static ClientConfiguration configurationCS;
38         private int bookingNumber = 0; // if it is "static" then it is not
39                                                                         // serialized
40         private int offerNumber = 0; // if it is "static" then it is not serialized
41         private static DB4oManager theDB4oManager = null;
42
43         private static DB4oManagerAux theDB4oManagerAux;
44
45         static ConfigXML c;
46
47         private DB4oManager() throws Exception {
48                 theDB4oManagerAux = new DB4oManagerAux(0, 0);
49                 c = ConfigXML.getInstance();
50                 System.out.println("Creating DB4oManager instance => isDatabaseLocal: "
51                                 + c.isDatabaseLocal() + " getDatabBaseOpenMode: "
52                                 + c.getDataBaseOpenMode());
53
54                 if ((c.getDataBaseOpenMode().equals("initialize"))
55                                 && (c.isDatabaseLocal()))
56                         new File(c.getDb4oFilename()).delete();
57
58                 if (c.isDatabaseLocal()) {
59                         openDB();
60                         System.out.println("DataBase opened");
61                 } else // c.isDatabaseLocal==false
62                 {
63                         openSDB();
64                         System.out.println("Remote DataBase opened");
65                 }
66                 if (c.getDataBaseOpenMode().equals("initialize")) {
67                         initializeDB();
68                         System.out.println("DataBase initialized");
69                 } else // c.getDataBaseOpenMode().equals("open")
70
71                 {
72                         ObjectSet<DB4oManagerAux> res = db.queryByExample(DB4oManagerAux.class);
73                         ListIterator<DB4oManagerAux> listIter = res.listIterator();
74                         if (listIter.hasNext())
75                                 theDB4oManagerAux = (DB4oManagerAux) res.next();
76                 }
77         }
78
79         private static void openDB() {
80                 configuration = Db4oEmbedded.newConfiguration();
81                 configuration.common().activationDepth(c.getActivationDepth());
82                 configuration.common().updateDepth(c.getUpdateDepth());
83                 configuration.common().objectClass(Owner.class).cascadeOnDelete(true);
84                 db = Db4oEmbedded.openFile(configuration, c.getDb4oFilename());
85         }
86
87         private void openSDB() {
88
89                 configurationCS = Db4oClientServer.newClientConfiguration();
90                 configurationCS.common().activationDepth(c.getActivationDepth());
91                 configurationCS.common().updateDepth(c.getUpdateDepth());
92                 configurationCS.common().objectClass(Owner.class).cascadeOnDelete(true);
93                 db = Db4oClientServer.openClient(configurationCS, c.getDatabaseNode(),
94                                 c.getDatabasePort(), c.getUser(), c.getPassword());
95
96         }
97
98         class DB4oManagerAux {
99                 int bookingNumber;
100                 int offerNumber;
101
102                 DB4oManagerAux(int bookingNumber, int offerNumber) {
103                         this.bookingNumber = bookingNumber;
104                         this.offerNumber = offerNumber;
105                 }
106         }
107
108         public static DB4oManager getInstance() throws Exception {
109                 if (theDB4oManager == null)
110                         theDB4oManager = new DB4oManager();
111                 return theDB4oManager;
112         }
113
114         public void initializeDB() {
115
116                 try {
117                         Owner jon = new Owner("Jon");
118                         Owner alfredo = new Owner("Alfredo");
119                         jon.addRuralHouse("Ezkioko", "Ezkioko etxea", "Beatriz", 3, 3, 3,
120                                         3, 3);
121                         jon.addRuralHouse("Eskiatze", "Eskiatzeko etxea", "Guazate", 4, 4,
122                                         4, 4, 4);
123                         jon.setBankAccount("1349 5677 21 2133567777");
124                         alfredo.addRuralHouse("Aitonako", "Casa del abuelo", "Vegas", 5, 5,
125                                         5, 5, 5);
126                         
127                         alfredo.addRuralHouse("Murgoitz", "", "Cedro", 6, 6, 6, 6, 6);
128                         alfredo.setBankAccount("4144 0087 23 9700002133");
129                         Account jonAcc = new Account("userJon", "passJon", jon);
130                         Account alfredoAcc = new Account("userAlfredo", "passAlfredo",
131                                         alfredo);
132
133                         Account admin = new Account("admin","admin", true);
134                         db.store(Administrator.giveAdmin());
135                         db.store(jon);
136                         db.store(alfredo);
137                         db.store(jonAcc);
138                         db.store(alfredoAcc);
139                         db.store(admin);
140                         db.commit();
141                 } finally {
142                         db.close();     
143                 }
144         }
145
146         public void deleteDB() {
147
148                 if (c.isDatabaseLocal() == false)
149                         openSDB();
150                 else
151                         openDB();
152
153                 try {
154                         Owner proto = new Owner(null, null);
155                         ObjectSet<Owner> result = db.queryByExample(proto);
156                         while (result.hasNext()) {
157                                 Owner o = (Owner) result.next();
158                                 System.out.println("Deleted owner: " + o.toString());
159                                 db.delete(o);
160                         }
161                         db.commit();
162                 } finally {
163                         db.close();
164                 }
165         }
166
167         public Offer createOffer(RuralHouse ruralHouse, Date firstDay,
168                         Date lastDay, float price) throws RemoteException, Exception {
169                 Offer o = null;
170
171                 if (c.isDatabaseLocal() == false)
172                         openSDB();
173                 else
174                         openDB();
175
176                 try {
177
178                         RuralHouse proto = new RuralHouse(ruralHouse.getHouseName(), null,
179                                         null, null, null);
180                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
181                         RuralHouse rh = (RuralHouse) result.next();
182                         o = rh.createOffer(theDB4oManagerAux.offerNumber++, firstDay,
183                                         lastDay, price);
184                         db.store(theDB4oManagerAux); // To store the new value for
185                                                                                         // offerNumber
186                         db.store(o);
187                         db.commit();
188
189                 } catch (com.db4o.ext.ObjectNotStorableException e) {
190                         System.out
191                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createOffer");
192                 } finally {
193                         db.close();
194                 }
195                 return o;
196         }
197
198         
199         public void deleteOffer(Offer offer) throws RemoteException,
200                         Exception {
201                 if (c.isDatabaseLocal() == false)
202                         openSDB();
203                 else
204                         openDB();
205
206                 try {
207                         ObjectSet<Offer> of = db.queryByExample(offer);
208                         RuralHouse rh =of.get(0).getRuralHouse();
209                         System.out.println(rh.offers.remove(of.get(0)));
210                         db.store(rh);
211                         db.commit();
212
213                 } catch (com.db4o.ext.ObjectNotStorableException e) {
214                         System.out
215                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createOffer");
216                 } finally {
217                         db.close();
218                 }
219         }
220
221         
222         @SuppressWarnings("static-access")
223         public LinkedList<RuralHouse>[] getAdminData(){
224                 if (c.isDatabaseLocal() == false)
225                         openSDB();
226                 else
227                         openDB();
228                 @SuppressWarnings("unchecked")
229                 LinkedList<RuralHouse>[] ret =  new LinkedList[2];
230                 
231                 try {
232                         
233                         List<Administrator> admL = db.query(new Predicate<Administrator>(){
234                                 /**
235                                  * 
236                                  */
237                                 private static final long serialVersionUID = 1L;
238
239                                 public boolean match(Administrator admin){
240                                         return true;
241                                 }
242                         });
243                         
244                         ret[0] = admL.get(0).getAddRequest();
245                         ret[1] = admL.get(0).getRemoveRequest();
246                         return ret;
247                 }
248                 finally {
249                         db.close();
250                         
251                 }
252                 
253         }
254         
255         @SuppressWarnings("static-access")
256         public void storeAdmin() {
257                 if (c.isDatabaseLocal() == false)
258                         openSDB();
259                 else
260                         openDB();               
261                 try {
262                         
263                         List<Administrator> admL = db.query(new Predicate<Administrator>(){
264                                 /**
265                                  * 
266                                  */
267                                 private static final long serialVersionUID = 1L;
268
269                                 public boolean match(Administrator admin){
270                                         return true;
271                                 }
272                         });
273                         
274                         admL.get(0).setAddRequest(Administrator.getAddRequest());
275                         admL.get(0).setRemoveRequest(Administrator.getRemoveRequest());
276                         db.commit();
277                         
278                 }
279                 catch(Exception e){
280                         
281                 }
282                 finally {
283                         db.close();
284                 }
285                 
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 Booking createBooking(RuralHouse ruralHouse, Date firstDate,
298                         Date lastDate, String bookTelephoneNumber)
299                         throws OfferCanNotBeBooked {
300
301                 if (c.isDatabaseLocal() == false)
302                         openSDB();
303                 else
304                         openDB();
305
306                 Booking bok = null;
307                 
308
309                 try {
310
311                         if (c.isDatabaseLocal() == false)
312                                 openSDB();
313
314                         RuralHouse proto = new RuralHouse(ruralHouse.getHouseName(), null,
315                                         ruralHouse.getDescription(), ruralHouse.getDistrict(), null);
316                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
317                         RuralHouse rh = (RuralHouse) result.next();
318
319                         Offer offer;
320                         offer = rh.findOffer(firstDate, lastDate);
321
322                         if (offer != null) {
323                                 offer.createBooking(theDB4oManagerAux.bookingNumber++,
324                                                 bookTelephoneNumber);
325                                 db.store(theDB4oManagerAux); // To store the new value for
326                                                                                                 // bookingNumber
327                                 db.store(offer);
328                                 db.commit();
329                                 bok = offer.getBooking();
330                         }
331
332                 } catch (com.db4o.ext.ObjectNotStorableException e) {
333                         System.out
334                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createBooking");
335                 } catch (Exception exc) {
336                         exc.printStackTrace();
337                 } finally {
338                         db.close();
339                 }
340                 return bok;
341         }
342
343         /**
344          * This method existing owners
345          * 
346          */
347         public Vector<Owner> getOwners() throws RemoteException, Exception {
348
349                 if (c.isDatabaseLocal() == false)
350                         openSDB();
351                 else
352                         openDB();
353
354                 try {
355                         Owner proto = new Owner(null, null);
356                         ObjectSet<Owner> result = db.queryByExample(proto);
357                         Vector<Owner> owners = new Vector<Owner>();
358                         while (result.hasNext())
359                                 owners.add((Owner) result.next());
360                         return owners;
361                 } finally {
362                         db.close();
363                 }
364         }
365
366         public Vector<RuralHouse> getAllRuralHouses() throws RemoteException,
367                         Exception {
368
369                 if (c.isDatabaseLocal() == false)
370                         openSDB();
371                 else
372                         openDB();
373
374                 try {
375                         RuralHouse proto = new RuralHouse(null, null, null, null, null);
376                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
377                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
378                         while (result.hasNext())
379                                 ruralHouses.add((RuralHouse) result.next());
380                         return ruralHouses;
381                 } finally {
382                         db.close();
383                 }
384         }
385
386         public boolean existsOverlappingOffer(RuralHouse rh, Date firstDay,
387                         Date lastDay) throws RemoteException, OverlappingOfferExists {
388
389                 if (c.isDatabaseLocal() == false)
390                         openSDB();
391                 else
392                         openDB();
393
394                 try {
395
396                         RuralHouse rhn = (RuralHouse) db.queryByExample(
397                                         new RuralHouse(rh.getHouseName(), null, null, null, null))
398                                         .next();
399                         if (rhn.overlapsWith(firstDay, lastDay) != null)
400                                 throw new OverlappingOfferExists();
401                         else
402                                 return false;
403                 } finally {
404                         db.close();
405                 }
406         }
407
408         public static ObjectContainer getContainer() {
409                 return db;
410         }
411
412         public void close() {
413                 db.close();
414                 System.out.println("DataBase closed");
415         }
416
417         public String toString() {
418                 return "bookingNumber=" + bookingNumber + " offerNumber=" + offerNumber;
419         }
420
421         /**
422          * @param usr
423          * @param pwd
424          * @return
425          * @throws RemoteException
426          * @throws Exception
427          */
428         public Vector<Account> getAccount(String usr, String pwd)
429                         throws RemoteException, Exception {
430
431                 if (c.isDatabaseLocal() == false)
432                         openSDB();
433                 else
434                         openDB();
435
436                 try {
437                         Account proto = new Account(usr, pwd, null);
438                         ObjectSet<Account> result = db.queryByExample(proto);
439                         Vector<Account> accounts = new Vector<Account>();
440                         while (result.hasNext())
441                                 accounts.add((Account) result.next());
442                         return accounts;
443                 } finally {
444                         db.close();
445                 }
446         }
447
448         /**
449          * @param rh
450          */
451         public boolean storeRuralHouses(RuralHouse rh) {
452
453                 if (c.isDatabaseLocal() == false)
454                         openSDB();
455                 else
456                         openDB();
457
458                 boolean stored = false;
459                 RuralHouse house = new RuralHouse(rh.getHouseName(), null, null, null,
460                                 null);
461                 try {
462                         ObjectSet<Owner> result = db.queryByExample(house);
463                         if (result.isEmpty()) {
464                                 db.store(rh);
465                                 db.commit();
466                                 stored = true;
467                         } else {
468                                 db.delete(result.get(0));
469                                 db.store(rh);
470                                 db.commit();
471                                 stored = true;
472                         }
473                 } finally {
474                         db.close();
475                 }
476                 return stored;
477         }
478
479         public void removeHouse(RuralHouse rh, Owner owner) {
480
481                 if (c.isDatabaseLocal() == false)
482                         openSDB();
483                 else
484                         openDB();
485                 try {
486                         ObjectSet<Owner> result = db.queryByExample(owner);
487                         ObjectSet<RuralHouse> rhs = db.queryByExample(rh);
488                         if (!rhs.isEmpty()) {
489                                 Owner found =  result.get(0);
490                                 found.getRuralHouses().remove(rhs.get(0));
491                                 db.store(found);
492                                 db.commit();
493                         }
494                 } catch (Exception exc) {
495                         exc.printStackTrace();
496                 } finally {
497                         db.close();
498                 }
499
500         }
501
502
503         public Vector<RuralHouse> getRuralHouses(String name, String town,
504                         int nBed, int nKit, int nBath, int nPark, int nLiv) {
505                 HouseFeatures fea = new HouseFeatures(nBed, nKit, nBath, nLiv, nPark);
506                 RuralHouse rh = new RuralHouse(name, null, null, town, fea);
507                 if (c.isDatabaseLocal() == false)
508                         openSDB();
509                 else
510                         openDB();
511
512                 try {
513                         ObjectSet<RuralHouse> result = db.queryByExample(rh);
514                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
515                         while (result.hasNext())
516                                 ruralHouses.add(result.next());
517                         db.close();
518                         return ruralHouses;
519                 } catch (NullPointerException e) {
520                         return null;
521                 }
522
523         }
524
525         
526 }