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