4 import java.util.Calendar;
6 import java.util.HashMap;
8 import java.util.Locale;
10 import java.util.ResourceBundle;
11 import java.util.Vector;
13 import javax.persistence.EntityManager;
14 import javax.persistence.EntityManagerFactory;
15 import javax.persistence.Persistence;
16 import javax.persistence.TypedQuery;
18 import configuration.ConfigXML;
19 import configuration.UtilDate;
21 import domain.Forecast;
22 import domain.Question;
24 import exceptions.IncorrectPassException;
25 import exceptions.QuestionAlreadyExist;
26 import exceptions.UserAlreadyExistException;
27 import exceptions.UserDoesNotExistException;
30 * It implements the data access to the objectDb database
32 public class DataAccess {
33 protected static EntityManager db;
34 protected static EntityManagerFactory emf;
37 ConfigXML c=ConfigXML.getInstance();
39 public DataAccess(boolean initializeMode) {
41 System.out.println("Creating DataAccess instance => isDatabaseLocal: "+c.isDatabaseLocal()+" getDatabBaseOpenMode: "+c.getDataBaseOpenMode());
48 new DataAccess(false);
53 * This is the data access method that initializes the database with some events and questions.
54 * This method is invoked by the business logic (constructor of BLFacadeImplementation) when the option "initialize" is declared in the tag dataBaseOpenMode of resources/config.xml file
56 public void initializeDB(){
58 db.getTransaction().begin();
62 Calendar today = Calendar.getInstance();
64 int month=today.get(Calendar.MONTH);
66 int year=today.get(Calendar.YEAR);
67 if (month==12) { month=0; year+=1;}
71 Event ev1=new Event(1, "Atlético-Athletic", UtilDate.newDate(year,month,17));
72 Event ev2=new Event(2, "Eibar-Barcelona", UtilDate.newDate(year,month,17));
73 Event ev3=new Event(3, "Getafe-Celta", UtilDate.newDate(year,month,17));
74 Event ev4=new Event(4, "Alavés-Deportivo", UtilDate.newDate(year,month,17));
75 Event ev5=new Event(5, "Español-Villareal", UtilDate.newDate(year,month,17));
76 Event ev6=new Event(6, "Las Palmas-Sevilla", UtilDate.newDate(year,month,17));
77 Event ev7=new Event(7, "Malaga-Valencia", UtilDate.newDate(year,month,17));
78 Event ev8=new Event(8, "Girona-Leganés", UtilDate.newDate(year,month,17));
79 Event ev9=new Event(9, "Real Sociedad-Levante", UtilDate.newDate(year,month,17));
80 Event ev10=new Event(10, "Betis-Real Madrid", UtilDate.newDate(year,month,17));
82 Event ev11=new Event(11, "Atletico-Athletic", UtilDate.newDate(year,month,1));
83 Event ev12=new Event(12, "Eibar-Barcelona", UtilDate.newDate(year,month,1));
84 Event ev13=new Event(13, "Getafe-Celta", UtilDate.newDate(year,month,1));
85 Event ev14=new Event(14, "Alavés-Deportivo", UtilDate.newDate(year,month,1));
86 Event ev15=new Event(15, "Español-Villareal", UtilDate.newDate(year,month,1));
87 Event ev16=new Event(16, "Las Palmas-Sevilla", UtilDate.newDate(year,month,1));
90 Event ev17=new Event(17, "Málaga-Valencia", UtilDate.newDate(year,month+1,28));
91 Event ev18=new Event(18, "Girona-Leganés", UtilDate.newDate(year,month+1,28));
92 Event ev19=new Event(19, "Real Sociedad-Levante", UtilDate.newDate(year,month+1,28));
93 Event ev20=new Event(20, "Betis-Real Madrid", UtilDate.newDate(year,month+1,28));
102 if (Locale.getDefault().equals(new Locale("es"))) {
103 q1=ev1.addQuestion("¿Quién ganará el partido?",1);
104 q2=ev1.addQuestion("¿Quién meterá el primer gol?",2);
105 q3=ev11.addQuestion("¿Quién ganará el partido?",1);
106 q4=ev11.addQuestion("¿Cuántos goles se marcarán?",2);
107 q5=ev17.addQuestion("¿Quién ganará el partido?",1);
108 q6=ev17.addQuestion("¿Habrá goles en la primera parte?",2);
110 else if (Locale.getDefault().equals(new Locale("en"))) {
111 q1=ev1.addQuestion("Who will win the match?",1);
112 q2=ev1.addQuestion("Who will score first?",2);
113 q3=ev11.addQuestion("Who will win the match?",1);
114 q4=ev11.addQuestion("How many goals will be scored in the match?",2);
115 q5=ev17.addQuestion("Who will win the match?",1);
116 q6=ev17.addQuestion("Will there be goals in the first half?",2);
119 q1=ev1.addQuestion("Zeinek irabaziko du partidua?",1);
120 q2=ev1.addQuestion("Zeinek sartuko du lehenengo gola?",2);
121 q3=ev11.addQuestion("Zeinek irabaziko du partidua?",1);
122 q4=ev11.addQuestion("Zenbat gol sartuko dira?",2);
123 q5=ev17.addQuestion("Zeinek irabaziko du partidua?",1);
124 q6=ev17.addQuestion("Golak sartuko dira lehenengo zatian?",2);
157 db.getTransaction().commit();
158 System.out.println("Db initialized");
166 * This method creates a question for an event, with a question text and the minimum bet
168 * @param event to which question is added
169 * @param question text of the question
170 * @param betMinimum minimum quantity of the bet
171 * @return the created question, or null, or an exception
172 * @throws QuestionAlreadyExist if the same question already exists for the event
174 public Question createQuestion(Event event, String question, float betMinimum) throws QuestionAlreadyExist {
175 System.out.println(">> DataAccess: createQuestion=> event= "+event+" question= "+question+" betMinimum="+betMinimum);
177 Event ev = db.find(Event.class, event.getEventNumber());
179 if (ev.DoesQuestionExists(question)) throw new QuestionAlreadyExist(ResourceBundle.getBundle("Etiquetas").getString("ErrorQueryAlreadyExist"));
181 db.getTransaction().begin();
182 Question q = ev.addQuestion(question, betMinimum);
184 db.persist(ev); // db.persist(q) not required when CascadeType.PERSIST is added in questions property of Event class
185 // @OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
186 db.getTransaction().commit();
192 * This method retrieves from the database the events of a given date
194 * @param date in which events are retrieved
195 * @return collection of events
197 public Vector<Event> getEvents(Date date) {
198 System.out.println(">> DataAccess: getEvents");
199 Vector<Event> res = new Vector<Event>();
200 TypedQuery<Event> query = db.createQuery("SELECT ev FROM Event ev WHERE ev.eventDate=?1",Event.class);
201 query.setParameter(1, date);
202 List<Event> events = query.getResultList();
203 for (Event ev:events){
204 System.out.println(ev.toString());
211 * This method retrieves from the database the dates a month for which there are events
213 * @param date of the month for which days with events want to be retrieved
214 * @return collection of dates
216 public Vector<Date> getEventsMonth(Date date) {
217 System.out.println(">> DataAccess: getEventsMonth");
218 Vector<Date> res = new Vector<Date>();
220 Date firstDayMonthDate= UtilDate.firstDayMonth(date);
221 Date lastDayMonthDate= UtilDate.lastDayMonth(date);
224 TypedQuery<Date> query = db.createQuery("SELECT DISTINCT ev.eventDate FROM Event ev WHERE ev.eventDate BETWEEN ?1 and ?2",Date.class);
225 query.setParameter(1, firstDayMonthDate);
226 query.setParameter(2, lastDayMonthDate);
227 List<Date> dates = query.getResultList();
229 System.out.println(d.toString());
236 public void open(boolean initializeMode){
238 System.out.println("Opening DataAccess instance => isDatabaseLocal: "+c.isDatabaseLocal()+" getDatabBaseOpenMode: "+c.getDataBaseOpenMode());
240 String fileName=c.getDbFilename();
241 if (initializeMode) {
242 fileName=fileName+";drop";
243 System.out.println("Deleting the DataBase");
246 if (c.isDatabaseLocal()) {
247 emf = Persistence.createEntityManagerFactory("objectdb:"+fileName);
248 db = emf.createEntityManager();
250 Map<String, String> properties = new HashMap<String, String>();
251 properties.put("javax.persistence.jdbc.user", c.getUser());
252 properties.put("javax.persistence.jdbc.password", c.getPassword());
254 emf = Persistence.createEntityManagerFactory("objectdb://"+c.getDatabaseNode()+":"+c.getDatabasePort()+"/"+fileName, properties);
256 db = emf.createEntityManager();
260 public boolean existQuestion(Event event, String question) {
261 System.out.println(">> DataAccess: existQuestion=> event= "+event+" question= "+question);
262 Event ev = db.find(Event.class, event.getEventNumber());
263 return ev.DoesQuestionExists(question);
268 System.out.println("DataBase closed");
271 public User login(String username, String pass) throws UserDoesNotExistException, IncorrectPassException {
273 User usuario = db.find(User.class, username);
275 if (usuario == null) {
276 throw new exceptions.UserDoesNotExistException("El usuario no existe");
278 if (!pass.equals(usuario.getUserPass())) {
279 throw new exceptions.IncorrectPassException("Contraseña incorrecta");
285 public boolean insertEvent(Event pEvento) {
287 db.getTransaction().begin();
289 db.getTransaction().commit();
291 } catch (Exception e) {
298 public boolean validoUsuario(String puser) throws UserAlreadyExistException {
300 User usuarioBD = db.find(User.class, puser);
301 if (usuarioBD == null) {
304 throw new UserAlreadyExistException("Ese usuario ya existe");
309 public User registrar(String user, String pass, String name, String lastName, String birthDate, String email,
310 String account, Integer numb, String address) throws UserAlreadyExistException {
311 db.getTransaction().begin();
312 User u = new User(user, pass, name, lastName, birthDate, email, account, numb, address);
314 boolean b = validoUsuario(user);
318 db.getTransaction().commit();
324 public int getNumberEvents() {
325 db.getTransaction().begin();
326 TypedQuery<Event> query = db.createQuery("SELECT ev FROM Event ev ",Event.class);
327 return query.getResultList().size();
330 public boolean existEvent(Event event) {
331 System.out.println(">> DataAccess: existEvent=> event= "+event);
332 return db.find(Event.class, event.getEventNumber()) != null ? true : false;
336 public boolean insertForecast(Forecast f) {
338 db.getTransaction().begin();
340 db.getTransaction().commit();
342 } catch (Exception e) {
348 public int getNumberForecasts() {
349 db.getTransaction().begin();
350 TypedQuery<Forecast> query = db.createQuery("SELECT f FROM Forecast f ",Forecast.class);
351 return query.getResultList().size();
354 public boolean existForecast(Forecast f) {
355 System.out.println(">> DataAccess: existForecast=> forecast= "+f);
356 return db.find(Forecast.class, f.getForecast()) != null ? true : false;