KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > rentacar > agency > services > reservation > AgencyReservationServiceImpl


1 package org.objectweb.rentacar.agency.services.reservation;
2
3 import java.net.MalformedURLException JavaDoc;
4 import java.net.URL JavaDoc;
5 import java.util.ArrayList JavaDoc;
6 import java.util.Date JavaDoc;
7 import java.util.GregorianCalendar JavaDoc;
8 import java.util.HashSet JavaDoc;
9 import java.util.Iterator JavaDoc;
10 import java.util.List JavaDoc;
11 import java.util.Set JavaDoc;
12
13 import javax.jws.WebMethod;
14 import javax.jws.WebParam;
15 import javax.jws.WebService;
16 import javax.xml.datatype.DatatypeConfigurationException JavaDoc;
17 import javax.xml.datatype.DatatypeFactory JavaDoc;
18 import javax.xml.datatype.XMLGregorianCalendar JavaDoc;
19 import javax.xml.namespace.QName JavaDoc;
20
21 import org.apache.log4j.Logger;
22 import org.objectweb.rentacar.AgencyException;
23 import org.objectweb.rentacar.persistance.bo.Agency;
24 import org.objectweb.rentacar.persistance.bo.Car;
25 import org.objectweb.rentacar.persistance.bo.CarCriteria;
26 import org.objectweb.rentacar.persistance.bo.CarVO;
27 import org.objectweb.rentacar.persistance.bo.CentralOffice;
28 import org.objectweb.rentacar.persistance.bo.Contact;
29 import org.objectweb.rentacar.persistance.bo.Reservation;
30 import org.objectweb.rentacar.persistance.dao.AgencyDAO;
31 import org.objectweb.rentacar.persistance.dao.CarDAO;
32 import org.objectweb.rentacar.persistance.dao.CentralOfficeDAO;
33 import org.objectweb.rentacar.persistance.dao.ContactDAO;
34 import org.objectweb.rentacar.persistance.dao.DAOException;
35 import org.objectweb.rentacar.persistance.dao.ReservationDAO;
36 import org.objectweb.rentacar.services.client.AgencyCheckAvailabilityServiceImpl;
37 import org.objectweb.rentacar.services.client.AgencyCheckAvailabilityServiceImplService;
38 import org.objectweb.rentacar.services.client.AgencyCriteria;
39 import org.objectweb.rentacar.services.client.AgencyException_Exception;
40 import org.objectweb.rentacar.services.client.AgencyReservationServiceImplService;
41 import org.objectweb.rentacar.services.client.AgencyVO;
42 import org.objectweb.rentacar.services.client.CentralOfficeException;
43 import org.objectweb.rentacar.services.client.CentralOfficeException_Exception;
44 import org.objectweb.rentacar.services.client.ConsultationImpl;
45 import org.objectweb.rentacar.services.client.ConsultationImplService;
46 import org.objectweb.rentacar.services.client.UpdateCentralDBImpl;
47 import org.objectweb.rentacar.services.client.UpdateCentralDBImplService;
48 import org.objectweb.rentacar.util.PropertiesLoader;
49 import org.objectweb.rentacar.util.PropertyLoadingException;
50
51 import sun.management.resources.agent;
52
53
54 /**
55  * This class expose web services
56  * that allow to control Reservation lifecycle (create, cancel, close...)
57  * @author wjoseph
58  */

59 @WebService
60 public class AgencyReservationServiceImpl {
61     
62     private Logger logger = Logger.getLogger(AgencyReservationServiceImpl.class);
63     
64     /**
65      * Create a new reservation in the agency database
66      * and update the central office database
67      * @param carId the reserved car Id
68      * @param start the starting date of the reservation
69      * @param end the ending date of the reservation
70      * @param customerId the customer Id
71      * @param startAgencyId the starting agency Id
72      * @param endAgencyId the ending agency Id
73      * @return
74      * @throws DAOException
75      * @throws AgencyException
76      */

77     @SuppressWarnings JavaDoc("unchecked")
78     @WebMethod
79     public String JavaDoc createReservation(@WebParam(name="carId")String JavaDoc carId,
80             @WebParam(name="startDate")Date JavaDoc start,
81             @WebParam(name="endDate")Date JavaDoc end,
82             @WebParam(name="customerId")String JavaDoc customerId,
83             @WebParam(name="startAgencyId")String JavaDoc startAgencyId,
84             @WebParam(name="endAgencyId")String JavaDoc endAgencyId) throws AgencyException {
85         
86         logger.info("Agency . createReservation : "+carId+", "+start.toString()+
87                 ", "+end.toString()+", "+customerId+
88                 ", "+startAgencyId+", "+endAgencyId);
89         
90         ReservationDAO reservationDAO = ReservationDAO.getInstance();
91         String JavaDoc result = null;
92         Set JavaDoc<Car> carsInitially = new HashSet JavaDoc<Car>();
93         
94         try {
95             CarCriteria criterium= new CarCriteria();
96             criterium.setCarId(carId);
97             
98             org.objectweb.rentacar.agency.services.availability.AgencyCheckAvailabilityServiceImpl check= new org.objectweb.rentacar.agency.services.availability.AgencyCheckAvailabilityServiceImpl();
99             CarVO[] availableCars = check.consultAvailability(criterium, start, end);
100             
101             if(availableCars.length >= 1){
102                 logger.debug("The car with Id "+ carId+"is disponible");
103                 carsInitially.add((Car) CarDAO.getInstance().retrieveById(Car.class, carId));
104                 
105                 
106                 Contact cont =(Contact) ContactDAO.getInstance().retrieveById(Contact.class, customerId);
107                 Agency stAg = (Agency)AgencyDAO.getInstance().retrieveById(Agency.class, startAgencyId);
108                 Agency enAg = (Agency)AgencyDAO.getInstance().retrieveById(Agency.class, endAgencyId);
109                 
110                 Reservation res = new Reservation(cont, carsInitially, start, end, stAg, enAg);
111                 
112                 
113                 result = reservationDAO.create(res);
114                 String JavaDoc centralOfficePresent= PropertiesLoader.getProperty("agency.properties", "central_office");
115                 if(centralOfficePresent != null && centralOfficePresent.equals("1")){
116                     //////// Update to central office
117
List JavaDoc<CentralOffice> centralOffices = new ArrayList JavaDoc<CentralOffice>();
118                     for (Object JavaDoc obj : CentralOfficeDAO.getInstance().retrieveAll(CentralOffice.class)) {
119                         centralOffices.add((CentralOffice) obj);
120                     }
121                     // There's only one central office in database
122
CentralOffice centralOffice = centralOffices.get(0);
123                     String JavaDoc centralOfficeHost = centralOffice.getHost();
124                     String JavaDoc centralOfficePort = centralOffice.getPort();
125                     
126                     URL JavaDoc updateWsdlLocation = new URL JavaDoc("http://"+centralOfficeHost+":"+centralOfficePort+"/rentacar-central-office/updateDB?wsdl");
127                     QName JavaDoc updateName = new QName JavaDoc("{http://update.services.centraloffice.rentacar.objectweb.org/}UpdateCentralDBImplPort");
128                     
129                     
130                     
131                     UpdateCentralDBImpl port = new UpdateCentralDBImplService(updateWsdlLocation,updateName).getUpdateCentralDBImplPort();
132                     
133                     //////// converts Dates
134

135                     XMLGregorianCalendar JavaDoc stDa = getDate(res.getStartingDate().getTime());
136                     
137                     XMLGregorianCalendar JavaDoc enDa = getDate(res.getEndingDate().getTime());
138                     
139                     port.addReservationInCentralDB(res.getCustomer().getContactId()
140                             ,carId,stDa,enDa,res.getStartingAgency().getAgencyId(),res.getEndingAgency().getAgencyId());
141                 }else{
142                     logger.debug("This car is already renting");
143                 }
144             }
145         } catch (DAOException e) {
146             logger.error("Error creating Reservation", e);
147             throw new AgencyException("Error creating Reservation", e);
148         } catch (CentralOfficeException_Exception e) {
149             logger.error("Error while updating central DB",e);
150             throw new AgencyException("Error while updating central DB",e);
151         } catch (MalformedURLException JavaDoc e) {
152             logger.error("Error while proccessing WSDL URL",e);
153             throw new AgencyException("Error while proccessing WSDL URL",e);
154         } catch (PropertyLoadingException e) {
155             logger.error("Error while loading the properties",e);
156             throw new AgencyException("Error while loading the properties",e);
157         }
158         return result;
159     }
160     
161     @SuppressWarnings JavaDoc("unchecked")
162     @WebMethod
163      public String JavaDoc[] createReservationPartner(@WebParam(name="criterion")CarCriteria criterium,
164                 @WebParam(name="quantity")int quantity, @WebParam(name="startDate")Date JavaDoc start,
165                 @WebParam(name="endDate")Date JavaDoc end,
166                 @WebParam(name="partnerId")String JavaDoc partnerId,
167                 @WebParam(name="startAgencyId")String JavaDoc startAgencyId,
168                 @WebParam(name="endAgencyId")String JavaDoc endAgencyId) throws DAOException {
169      String JavaDoc ids[] = {};
170      ArrayList JavaDoc<String JavaDoc> idList= new ArrayList JavaDoc<String JavaDoc>();
171      ArrayList JavaDoc<ElementsToReserve> carsToReserve = new ArrayList JavaDoc<ElementsToReserve>();
172      
173     
174      try {
175          XMLGregorianCalendar JavaDoc startDate = getDate(start.getTime());
176             
177         XMLGregorianCalendar JavaDoc endDate = getDate(end.getTime());
178      org.objectweb.rentacar.agency.services.availability.AgencyCheckAvailabilityServiceImpl check= new org.objectweb.rentacar.agency.services.availability.AgencyCheckAvailabilityServiceImpl();
179      CarVO[] availableCars = check.consultAvailability(criterium, start, end);
180      
181      //If there are enough car in the agency, the cars are reserve here
182
if (availableCars.length >= quantity){
183          for (CarVO carVO : availableCars) {
184             carsToReserve.add(new ElementsToReserve(null, carVO.getCarId()));
185          }
186      }
187      else{
188          //If it wants any cars, the agency search in close agencies
189
System.out.println(new String JavaDoc("Search in close Agencies \n"));
190          for (CarVO carVO : availableCars) {
191                 carsToReserve.add(new ElementsToReserve(null, carVO.getCarId()));
192              }
193         ArrayList JavaDoc<ElementsToReserve> availableAgencyBCars= availableCarsInCloseAgencies(criterium, quantity- availableCars.length,start,end);
194         carsToReserve.addAll(availableAgencyBCars);
195         System.out.println(new String JavaDoc("cars to rent\n" + carsToReserve.size()));
196         }
197         
198         if(carsToReserve.size()>= quantity){
199             int i=0;
200             while (i < quantity){
201                 String JavaDoc id;
202                 ElementsToReserve current=carsToReserve.get(i);
203             if (current.getResaImpl()==null){
204                 //Reservation in local agency
205
id=createReservation(current.getCarVOId(),start,end,partnerId,startAgencyId,endAgencyId);
206             }else{
207                 //Reservation in close agencies
208
id= current.getResaImpl().createReservation(current.getCarVOId(),startDate,endDate,partnerId,startAgencyId,endAgencyId);
209             }
210                 idList.add(id);
211                 i++;
212             }
213         }else
214             idList.add("There aren't enough cars matching with the criteria");
215             
216       }
217         catch (AgencyException e) {
218             throw new DAOException("Error creating Reservation", e);
219         }
220         catch (AgencyException_Exception e) {
221             throw new DAOException("Error creating Reservation", e);
222         }
223         return idList.toArray(ids);
224         }
225        
226     
227     /**
228      * Delete the reservation matching the given id
229      * TODO : modify a reservation statut instead of deleting the reservation
230      * @param reservationCode the reservationId of the reservation to close
231      * @throws AgencyException
232      */

233     @WebMethod
234     public void closeReservation(@WebParam(name="reservationCode")String JavaDoc reservationCode) throws AgencyException {
235         
236         logger.info("Agency . closeReservation : "+reservationCode);
237         
238         ReservationDAO reservationDAO = ReservationDAO.getInstance();
239         
240         try {
241             Reservation res = (Reservation) reservationDAO.retrieveById(Reservation.class, reservationCode);
242             reservationDAO.delete(res);
243             
244         }
245         catch (DAOException e) {
246             logger.error("Error closing Reservation", e);
247             throw new AgencyException("Error closing Reservation", e);
248         }
249     }
250     
251     /**
252      * Delete the reservation matching the given id
253      * TODO : modify a reservation statut instead of deleting the reservation
254      * @param reservationId the reservationId of the reservation to cancel
255      * @return
256      * @throws AgencyException
257      */

258     @WebMethod
259     public boolean cancelReservation(@WebParam(name="reservationId")String JavaDoc reservationId) throws AgencyException {
260         
261         logger.info("Agency . cancelReservation : "+reservationId);
262         
263         try {
264             Reservation resToCancel = (Reservation) ReservationDAO.getInstance().retrieveById(Reservation.class, reservationId);
265             ReservationDAO.getInstance().delete(resToCancel);
266             return true;
267         }
268         catch (DAOException e) {
269             logger.error("Error closing Reservation", e);
270             throw new AgencyException("Error closing Reservation", e);
271         }
272         
273     }
274     
275     /**
276      * Get a XMLGregorianCalendar from a time in milli second
277      * @param timeInMillis time in millis
278      * @return an xmlgregorian date corresponding to the timeInMillis
279      */

280     private XMLGregorianCalendar JavaDoc getDate(long timeInMillis) {
281         try {
282             GregorianCalendar JavaDoc cal = new GregorianCalendar JavaDoc();
283             cal.setTimeInMillis(timeInMillis);
284             return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
285         }
286         catch (DatatypeConfigurationException JavaDoc e) {
287             throw new Error JavaDoc(e);
288         }
289     }
290 ////////Ask to close agency for available cars
291
private ArrayList JavaDoc<ElementsToReserve> availableCarsInCloseAgencies(CarCriteria carCrit, int quantity, Date JavaDoc start, Date JavaDoc end) throws AgencyException{
292         
293         List JavaDoc<Object JavaDoc> centralOffices;
294         ArrayList JavaDoc<ElementsToReserve> availableCarsAgency = new ArrayList JavaDoc<ElementsToReserve>();
295         AgencyCriteria agencyCriteria= new AgencyCriteria();
296         try {
297         centralOffices = CentralOfficeDAO.getInstance().retrieveAll(CentralOffice.class);
298         // There's only one central office in database
299
CentralOffice centralOffice = (CentralOffice)centralOffices.get(0);
300         String JavaDoc centralOfficeHost = centralOffice.getHost();
301         String JavaDoc centralOfficePort = centralOffice.getPort();
302         
303         ConsultationImpl consultPort;
304         AgencyCheckAvailabilityServiceImpl availabilityPort;
305         org.objectweb.rentacar.services.client.AgencyReservationServiceImpl reservationPort;
306         
307         URL JavaDoc consultWsdlLocation;
308         
309         consultWsdlLocation = new URL JavaDoc("http://"+centralOfficeHost+":"+centralOfficePort+"/rentacar-central-office/consultation?wsdl");
310         logger.debug("http://"+centralOfficeHost+":"+centralOfficePort+"/rentacar-central-office/consultation?wsdl");
311         QName JavaDoc consultName = new QName JavaDoc("{http://consultation.services.centraloffice.rentacar.objectweb.org/}ConsultationImplPor");
312                 
313         consultPort= new ConsultationImplService(consultWsdlLocation, consultName).getConsultationImplPort();
314         
315         //////// converts Dates
316

317         XMLGregorianCalendar JavaDoc stDa = getDate(start.getTime());
318         
319         XMLGregorianCalendar JavaDoc enDa = getDate(end.getTime());
320         
321         agencyCriteria.setAgencyId("2");
322         
323         //Ask to central office the list of close agencies
324
List JavaDoc<org.objectweb.rentacar.services.client.AgencyVO> agencyClose = consultPort.retreiveAgencies(agencyCriteria);
325         
326         for (org.objectweb.rentacar.services.client.AgencyVO agencyVO : agencyClose) {
327             logger.debug("agencyVO "+ agencyVO);
328         }
329         String JavaDoc closeAgencyHost;
330         String JavaDoc closeAgencyPort;
331         String JavaDoc closeAgencyWarName;
332         Iterator JavaDoc<AgencyVO> it= agencyClose.iterator();
333         
334         while(it.hasNext() && (availableCarsAgency.size()< quantity)){
335             //While all cars aren't complete, it searches availables cars in close agencies
336

337             org.objectweb.rentacar.services.client.AgencyVO currentAgency= it.next();
338             logger.debug("agency "+ currentAgency.getAgencyId());
339             closeAgencyHost = currentAgency.getHost();
340             closeAgencyPort = currentAgency.getPort();
341             closeAgencyWarName = currentAgency.getWarName();
342             
343             //URL consultCloseAgenceLocation = new URL("http://"+closeAgencyHost+":"+closeAgencyPort+"/rentacar-agency-reservation2/availability?wsdl");
344
URL JavaDoc consultCloseAgenceLocation = new URL JavaDoc("http://"+closeAgencyHost+":"+closeAgencyPort+"/"+closeAgencyWarName+"/availability?wsdl");
345             QName JavaDoc consultAgencyName = new QName JavaDoc("{http://availability.services.agency.rentacar.objectweb.org/}AgencyCheckAvailabilityServiceImplPort");
346             availabilityPort = new AgencyCheckAvailabilityServiceImplService(consultCloseAgenceLocation, consultAgencyName).getAgencyCheckAvailabilityServiceImplPort();
347             //URL resaWsdlLocation = new URL("http://"+closeAgencyHost+":"+closeAgencyPort+"/rentacar-agency-reservation2/reservation?wsdl");
348
URL JavaDoc resaWsdlLocation = new URL JavaDoc("http://"+closeAgencyHost+":"+closeAgencyPort+"/"+closeAgencyWarName+"/reservation?wsdl");
349             QName JavaDoc resaName = new QName JavaDoc("{http://reservation.services.agency.rentacar.objectweb.org/}AgencyReservationServiceImplPort");
350             reservationPort = (org.objectweb.rentacar.services.client.AgencyReservationServiceImpl) new AgencyReservationServiceImplService(resaWsdlLocation, resaName).getAgencyReservationServiceImplPort();
351             // Get available cars
352

353             org.objectweb.rentacar.services.client.CarCriteria carCritCl= new org.objectweb.rentacar.services.client.CarCriteria();
354             carCritCl.setType(carCrit.getType());
355             carCritCl.setModel(carCrit.getModel());
356             carCritCl.setBrand(carCrit.getBrand());
357             
358             List JavaDoc<org.objectweb.rentacar.services.client.CarVO> result;
359             result = availabilityPort.consultAvailability(carCritCl, stDa, enDa);
360             
361             
362                 if (result.size() < 0 ){
363                     System.out.println("No car available for your criteria");
364                 }
365                 else{
366                     
367                     System.out.println(" There is "+ result.size() + " cars matching your criteria");
368                     
369                     for (org.objectweb.rentacar.services.client.CarVO carVO : result) {
370                         //logger.debug(carVO);
371
//add available cars in list of cars to resereve
372
availableCarsAgency.add(new ElementsToReserve(reservationPort, carVO.getCarId()));
373                     }
374                 }
375         }
376         return availableCarsAgency;
377         }catch (DAOException e1) {
378             throw new AgencyException("Error retriving all central offices ", e1);
379         }
380         catch (MalformedURLException JavaDoc e) {
381             throw new AgencyException("Error in service URL"+e);
382         } catch (CentralOfficeException_Exception e) {
383             throw new AgencyException("Error retriving all agencies matching to agency criteria "+ agencyCriteria, e);
384         } catch (AgencyException_Exception e) {
385             throw new AgencyException("Error consulting available cars"+e);
386         }
387     }
388     
389     
390     
391 }
392
Popular Tags