Username is saved hashed and password hashed and salted
[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
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");
123                         Owner alfredo = new Owner("Alfredo");
124                         jon.addRuralHouse("Ezkioko", "Ezkioko etxea", "Beatriz", 3, 3, 3,
125                                         3, 3);
126                         jon.addRuralHouse("Eskiatze", "Eskiatzeko etxea", "Guazate", 4, 4,
127                                         4, 4, 4);
128                         jon.setBankAccount("1349 5677 21 2133567777");
129                         alfredo.addRuralHouse("Aitonako", "Casa del abuelo", "Vegas", 5, 5,
130                                         5, 5, 5);
131
132                         alfredo.addRuralHouse("Murgoitz", "", "Cedro", 6, 6, 6, 6, 6);
133                         alfredo.setBankAccount("4144 0087 23 9700002133");
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);
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
223         public Administrator getAdminData() {
224                 if (c.isDatabaseLocal() == false)
225                         openSDB();
226                 else
227                         openDB();
228
229                 try {
230
231                         List<Administrator> admL = db.query(new Predicate<Administrator>() {
232                                 /**
233                                  * 
234                                  */
235                                 private static final long serialVersionUID = 1L;
236
237                                 public boolean match(Administrator admin) {
238                                         return true;
239                                 }
240                         });
241
242                         return admL.get(0);
243                 } finally {
244                         db.close();
245
246                 }
247
248         }
249
250         @SuppressWarnings("static-access")
251         public void storeAdmin() {
252                 if (c.isDatabaseLocal() == false)
253                         openSDB();
254                 else
255                         openDB();
256                 try {
257
258                         List<Administrator> admL = db.query(new Predicate<Administrator>() {
259                                 /**
260                                  * 
261                                  */
262                                 private static final long serialVersionUID = 1L;
263
264                                 public boolean match(Administrator admin) {
265                                         return true;
266                                 }
267                         });
268
269                         
270                         admL.get(0).setAddRequest(Administrator.getInstance().getAddRequest());
271                         admL.get(0).setRemoveRequest(Administrator.getInstance().getRemoveRequest());
272                         admL.get(0).setNewOwnerRequest(Administrator.getInstance().getNewOwnerRequest());
273                         db.commit();
274
275                 } catch (Exception e) {
276
277                 } finally {
278                         db.close();
279                 }
280
281         }
282
283         /**
284          * This method creates a book with a corresponding parameters
285          * 
286          * @param First
287          *            day, last day, house number and telephone
288          * @return a book
289          */
290         public Booking createBooking(RuralHouse ruralHouse, Date firstDate,
291                         Date lastDate, String bookTelephoneNumber)
292                         throws OfferCanNotBeBooked {
293
294                 if (c.isDatabaseLocal() == false)
295                         openSDB();
296                 else
297                         openDB();
298
299                 Booking bok = null;
300
301                 try {
302
303                         if (c.isDatabaseLocal() == false)
304                                 openSDB();
305
306                         RuralHouse proto = new RuralHouse(ruralHouse.getHouseName(), null,
307                                         ruralHouse.getDescription(), ruralHouse.getDistrict(), null);
308                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
309                         RuralHouse rh = (RuralHouse) result.next();
310
311                         Offer offer;
312                         offer = rh.findOffer(firstDate, lastDate);
313
314                         if (offer != null) {
315                                 offer.createBooking(theDB4oManagerAux.bookingNumber++,
316                                                 bookTelephoneNumber);
317                                 db.store(theDB4oManagerAux); // To store the new value for
318                                                                                                 // bookingNumber
319                                 db.store(offer);
320                                 db.commit();
321                                 bok = offer.getBooking();
322                         }
323
324                 } catch (com.db4o.ext.ObjectNotStorableException e) {
325                         System.out
326                                         .println("Error: com.db4o.ext.ObjectNotStorableException in createBooking");
327                 } catch (Exception exc) {
328                         exc.printStackTrace();
329                 } finally {
330                         db.close();
331                 }
332                 return bok;
333         }
334
335         /**
336          * This method existing owners
337          * 
338          */
339         public Vector<Owner> getOwners() throws RemoteException, Exception {
340
341                 if (c.isDatabaseLocal() == false)
342                         openSDB();
343                 else
344                         openDB();
345
346                 try {
347                         Owner proto = new Owner(null, null);
348                         ObjectSet<Owner> result = db.queryByExample(proto);
349                         Vector<Owner> owners = new Vector<Owner>();
350                         while (result.hasNext())
351                                 owners.add((Owner) result.next());
352                         return owners;
353                 } finally {
354                         db.close();
355                 }
356         }
357
358         public Vector<RuralHouse> getAllRuralHouses() throws RemoteException,
359                         Exception {
360
361                 if (c.isDatabaseLocal() == false)
362                         openSDB();
363                 else
364                         openDB();
365
366                 try {
367                         RuralHouse proto = new RuralHouse(null, null, null, null, null);
368                         ObjectSet<RuralHouse> result = db.queryByExample(proto);
369                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
370                         while (result.hasNext())
371                                 ruralHouses.add((RuralHouse) result.next());
372                         return ruralHouses;
373                 } finally {
374                         db.close();
375                 }
376         }
377
378         public boolean existsOverlappingOffer(RuralHouse rh, Date firstDay,
379                         Date lastDay) throws RemoteException, OverlappingOfferExists {
380
381                 if (c.isDatabaseLocal() == false)
382                         openSDB();
383                 else
384                         openDB();
385
386                 try {
387
388                         RuralHouse rhn = (RuralHouse) db.queryByExample(
389                                         new RuralHouse(rh.getHouseName(), null, null, null, null))
390                                         .next();
391                         if (rhn.overlapsWith(firstDay, lastDay) != null)
392                                 throw new OverlappingOfferExists();
393                         else
394                                 return false;
395                 } finally {
396                         db.close();
397                 }
398         }
399
400         public static ObjectContainer getContainer() {
401                 return db;
402         }
403
404         public void close() {
405                 db.close();
406                 System.out.println("DataBase closed");
407         }
408
409         public String toString() {
410                 return "bookingNumber=" + bookingNumber + " offerNumber=" + offerNumber;
411         }
412
413         /**
414          * @param usr
415          * @param ps
416          * @return
417          * @throws RemoteException
418          * @throws Exception
419          */
420         public Vector<Account> getAccount(Account proto)
421                         throws RemoteException, Exception {
422
423                 if (c.isDatabaseLocal() == false)
424                         openSDB();
425                 else
426                         openDB();
427
428                 try {
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<RuralHouse> result = db.queryByExample(house);
454                         if (result.isEmpty()) {
455                                 Owner ow = (Owner) db.queryByExample(rh.getOwner()).get(0);
456                                 rh.setOwner(ow);
457                                 ow.addRuralHouse(rh);
458                                 db.store(rh);
459                                 db.commit();
460                                 stored = true;
461                         } else {
462                                 db.delete(result.get(0));
463                                 db.store(rh);
464                                 db.commit();
465                                 stored = true;
466                         }
467                 } finally {
468                         db.close();
469                 }
470                 return stored;
471         }
472
473         public void removeHouse(RuralHouse rh, Owner owner) {
474
475                 if (c.isDatabaseLocal() == false)
476                         openSDB();
477                 else
478                         openDB();
479                 try {
480                         ObjectSet<Owner> result = db.queryByExample(owner);
481                         ObjectSet<RuralHouse> rhs = db.queryByExample(rh);
482                         if (!rhs.isEmpty()) {
483                                 Owner found = result.get(0);
484                                 found.getRuralHouses().remove(rhs.get(0));
485                                 db.delete(rhs.get(0));
486                                 db.store(found);
487                                 db.commit();
488                         }
489                 } catch (Exception exc) {
490                         exc.printStackTrace();
491                 } finally {
492                         db.close();
493                 }
494
495         }
496
497         public Vector<RuralHouse> getRuralHouses(String name, String town,
498                         int nBed, int nKit, int nBath, int nPark, int nLiv) {
499                 HouseFeatures fea = new HouseFeatures(nBed, nKit, nBath, nLiv, nPark);
500                 RuralHouse rh = new RuralHouse(name, null, null, town, fea);
501                 if (c.isDatabaseLocal() == false)
502                         openSDB();
503                 else
504                         openDB();
505
506                 try {
507                         ObjectSet<RuralHouse> result = db.queryByExample(rh);
508                         Vector<RuralHouse> ruralHouses = new Vector<RuralHouse>();
509                         while (result.hasNext())
510                                 ruralHouses.add(result.next());
511                         db.close();
512                         return ruralHouses;
513                 } catch (NullPointerException e) {
514                         return null;
515                 }
516
517         }
518
519 }