View Javadoc

1   /*
2    Copyright (C) 2004
3   
4    This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
5   
6    This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
7   
8    You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
9    
10   Written by St�phane Gauchet
11   mail me at : sgauchet@free.fr
12   */
13  package fr.hyphonem.conges;
14  
15  import java.awt.Color;
16  import java.text.DecimalFormat;
17  import java.text.ParseException;
18  import java.text.SimpleDateFormat;
19  import java.util.ArrayList;
20  import java.util.Calendar;
21  import java.util.Date;
22  import java.util.Enumeration;
23  import java.util.Hashtable;
24  import java.util.Iterator;
25  import java.util.List;
26  import java.util.Properties;
27  import java.util.Vector;
28  
29  import javax.mail.Message;
30  import javax.mail.Session;
31  import javax.mail.Transport;
32  import javax.mail.internet.InternetAddress;
33  import javax.mail.internet.MimeMessage;
34  import javax.servlet.ServletException;
35  import javax.servlet.http.HttpServletRequest;
36  import javax.servlet.http.HttpSession;
37  
38  import org.jfree.chart.ChartFactory;
39  import org.jfree.chart.JFreeChart;
40  import org.jfree.chart.plot.CategoryPlot;
41  import org.jfree.chart.renderer.GanttRenderer;
42  import org.jfree.data.IntervalCategoryDataset;
43  import org.jfree.data.gantt.Task;
44  import org.jfree.data.gantt.TaskSeries;
45  import org.jfree.data.gantt.TaskSeriesCollection;
46  
47  import fr.hyphonem.conges.data.CalendarData;
48  import fr.hyphonem.conges.data.EmployeeData;
49  import fr.hyphonem.conges.data.EmployeeIdCalData;
50  import fr.hyphonem.conges.data.GetMaxDaysReturnBean;
51  import fr.hyphonem.conges.data.NationalDayData;
52  import fr.hyphonem.conges.data.ParamsData;
53  import fr.hyphonem.conges.data.PendingEventData;
54  import fr.hyphonem.conges.data.PeriodParamsData;
55  import fr.hyphonem.conges.data.StatsData;
56  import fr.hyphonem.conges.data.UserData;
57  import fr.hyphonem.conges.resources.Messages;
58  
59  /*
60   * Copyright (C) 2004-... Stephane Gauchet for Hyphonem
61   * 
62   * This program is free software; you can redistribute it and/or modify it under
63   * the terms of the GNU General Public License as published by the Free Software
64   * Foundation; either version 2 of the License, or (at your option) any later
65   * version.
66   * 
67   * This program is distributed in the hope that it will be useful, but WITHOUT
68   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
69   * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
70   * details.
71   * 
72   * You should have received a copy of the GNU General Public License along with
73   * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
74   * Place, Suite 330, Boston, MA 02111-1307 USA
75   * 
76   * Written by Stephane Gauchet mail me at : sgauchet@free.fr
77   */
78  /**
79   * @author Stephane Gauchet pour Hyphonem
80   * 
81   * common class for useful stuff
82   */
83  
84  public class CommonCal {
85  
86  	/**
87  	 * Constructor for CommonCal.
88  	 */
89  	public CommonCal() {
90  		super();
91  	}
92  
93  	/**
94  	 * retourne le nombre de jours dans le mois de la date pass�e en param�tre
95  	 * <br/> return nb of days in the month of the date passed in parameter
96  	 * 
97  	 * @param date -
98  	 *            Calendar
99  	 * @return int
100 	 */
101 	private int getMaxJoursInMonth(Calendar date) {
102 		return date.getActualMaximum(Calendar.DAY_OF_MONTH);
103 	}
104 
105 	/**
106 	 * retourne le nombre de jours dans les mois suivants la date pass�e en
107 	 * param�tre <br/> return nb of days in the nth next months following the
108 	 * date in parameter
109 	 * 
110 	 * @param date
111 	 * @param nMonthsForward
112 	 * @return bean GetMaxDaysReturnBean
113 	 */
114 	public GetMaxDaysReturnBean getMaxJoursForNMonthsForwardDate(Calendar date,
115 			int nMonthsForward) {
116 		GetMaxDaysReturnBean bean = new GetMaxDaysReturnBean();
117 		Hashtable ht = new Hashtable(nMonthsForward);
118 
119 		// les nMonthsForward mois superieurs y compris le mois en cours
120 		for (int i = 0; i < nMonthsForward; i++) {
121 			Calendar date2 = calculateNthMonth(date, i);
122 			SimpleDateFormat sdf = new SimpleDateFormat("MMMMM");
123 			String nomMois = sdf.format(date2.getTime());
124 			int year = date2.get(Calendar.YEAR);
125 			int month = date2.get(Calendar.MONTH) + 1;
126 			int daysInMonth = getMaxJoursInMonth(date2);
127 
128 			// remise � z�ro � la date initiale
129 			date = calculateNthMonth(date2, -i);
130 			ht.put("" + i, nomMois + "#" + month + " " + year + "|"
131 					+ daysInMonth);
132 
133 			if (i == 0) {
134 				bean.setDebper("01/" + month + "/" + year);
135 			}
136 			if (i == nMonthsForward - 1) {
137 				bean.setFinper("" + daysInMonth + "/" + month + "/" + year);
138 			}
139 		}
140 
141 		bean.setHt(ht);
142 		return bean;
143 	}
144 
145 	/**
146 	 * calcule la date en ajoutant ou enlevant n mois � la date pass�e en
147 	 * param�tre return date calculated by add or remove nth month to the date
148 	 * passec in parameter
149 	 * 
150 	 * @param date
151 	 * @param numMonth
152 	 * @return Calendar
153 	 */
154 	private Calendar calculateNthMonth(Calendar date, int numMonth) {
155 		date.add(Calendar.MONTH, numMonth);
156 		return date;
157 	}
158 
159 	/**
160 	 * do a list of calendarData with only one day in it and no fery days or
161 	 * weekend days
162 	 * 
163 	 * @param vCalendarData
164 	 * @param employee
165 	 * @param hJF :
166 	 *            hashtable des jours feries
167 	 * @return Vector
168 	 * @throws Exception
169 	 */
170 	public Vector getDiscretCalData(Vector vCalendarData,
171 			EmployeeData employee, Hashtable hJF) throws Exception {
172 		Vector lstCalData = new Vector();
173 
174 		// vCalendarData a des CalendarData contenant une periode
175 		// on va creer des CalendarData ne contenant qu'un jour
176 		// et on enleve les Samedi et les Dimanche
177 		// et les jours feries
178 
179 		for (Enumeration e = vCalendarData.elements(); e.hasMoreElements();) {
180 			CalendarData cd = (CalendarData) e.nextElement();
181 			String ddeb = cd.getDatedeb();
182 			String dfin = cd.getDatefin();
183 			String raison = cd.getRaison();
184 			boolean cbmatin = cd.isCbmatin();
185 			boolean cbaprem = cd.isCbaprem();
186 			int id = new Integer(cd.getId()).intValue();
187 
188 			if (ddeb != null && dfin != null && raison != null) {
189 				try {
190 					Date datedeb = new SimpleDateFormat("dd/MM/yyyy")
191 							.parse(ddeb);
192 					Date datefin = new SimpleDateFormat("dd/MM/yyyy")
193 							.parse(dfin);
194 
195 					if (datedeb.compareTo(datefin) == 0) {
196 						CalendarData cda = checkDateForCalendarData(datedeb,
197 								cbmatin, cbaprem, raison, employee, "" + id,
198 								hJF);
199 						if (cda != null) {
200 							lstCalData.add(cda);
201 						// lstCalData.add(cd);
202 						}
203 					} else if (datedeb.compareTo(datefin) < 0) {
204 						Date date = datedeb;
205 						while (date.compareTo(datefin) <= 0) {
206 							CalendarData cda = checkDateForCalendarData(date,
207 									cbmatin, cbaprem, raison, employee,
208 									"" + id, hJF);
209 							if (cda != null) {
210 								lstCalData.add(cda);
211 							}
212 							Calendar cal = Calendar.getInstance();
213 							cal.setTime(date);
214 							cal.add(Calendar.DATE, 1);
215 							date = cal.getTime();
216 							id += 1;
217 						}
218 						Calendar.getInstance().clear();
219 					} else {
220 						throw new Exception("erreur DateDeb " + ddeb
221 								+ " > DateFin " + dfin);
222 					}
223 				} catch (ParseException ex) {
224 					throw new Exception(ex.getLocalizedMessage());
225 				}
226 			}
227 		}
228 		return lstCalData;
229 	}
230 
231 	/**
232 	 * suppress non working day (weekend days and fery days) in the calendarData
233 	 * 
234 	 * @param date -
235 	 *            Date
236 	 * @param cbmatin -
237 	 *            boolean
238 	 * @param cbaprem -
239 	 *            boolean
240 	 * @param raison
241 	 * @param employee -
242 	 *            EmployeeDataCal
243 	 * @param id
244 	 * @param hJF
245 	 * @return CalendarData
246 	 * @throws ParseException
247 	 */
248 	private CalendarData checkDateForCalendarData(Date date, boolean cbmatin,
249 			boolean cbaprem, String raison, EmployeeData employee, String id,
250 			Hashtable hJF) throws ParseException {
251 		Calendar cal = Calendar.getInstance();
252 		cal.setTime(date);
253 		CalendarData cdr = new CalendarData();
254 		boolean isAWorkedDay = true;
255 
256 		List dayoffs = new ArrayList();
257 		if (employee.isDayoff1()) {
258 			dayoffs.add("" + Calendar.MONDAY);
259 		}
260 		if (employee.isDayoff2()) {
261 			dayoffs.add("" + Calendar.TUESDAY);
262 		}
263 		if (employee.isDayoff3()) {
264 			dayoffs.add("" + Calendar.WEDNESDAY);
265 		}
266 		if (employee.isDayoff4()) {
267 			dayoffs.add("" + Calendar.THURSDAY);
268 		}
269 		if (employee.isDayoff5()) {
270 			dayoffs.add("" + Calendar.FRIDAY);
271 		}
272 		if (employee.isDayoff6()) {
273 			dayoffs.add("" + Calendar.SATURDAY);
274 		}
275 		if (employee.isDayoff7()) {
276 			dayoffs.add("" + Calendar.SUNDAY);
277 		}
278 
279 		// on teste si c un jour de repos / dayoff
280 		for (Iterator iter = dayoffs.iterator(); iter.hasNext();) {
281 			int day = Integer.parseInt((String) iter.next());
282 			if (cal.get(Calendar.DAY_OF_WEEK) == day) {
283 				// on ne met pas cette date dans notre nouvelle liste
284 				isAWorkedDay = false;
285 				break;
286 			}
287 		}
288 
289 		if (isAWorkedDay) {
290 			// on teste si c un jour ferie
291 			// liste des jours feries
292 
293 			String annee = "" + cal.get(Calendar.YEAR);
294 			if (hJF.containsKey(annee)) {
295 				Vector vDays = (Vector) hJF.get(annee);
296 				Iterator iter = vDays.iterator();
297 				String sdate = new java.text.SimpleDateFormat("dd/MM/yyyy")
298 						.format(date);
299 				while (iter.hasNext()) {
300 					NationalDayData ndd = (NationalDayData) iter.next();
301 					if (ndd.getDate().equals(sdate)) {
302 						isAWorkedDay = false;
303 						break;
304 					}
305 				}
306 			}
307 
308 		}
309 
310 		if (isAWorkedDay) {
311 			String datedf = new SimpleDateFormat("dd/MM/yyyy").format(date);
312 			cdr.setDatedeb(datedf);
313 			cdr.setDatefin(datedf);
314 			cdr.setCbmatin(cbmatin);
315 			cdr.setCbaprem(cbaprem);
316 			cdr.setRaison(raison);
317 			cdr.setEmployee(employee);
318 			cdr.setId(id);
319 		} else {
320 			cdr = null;
321 		}
322 
323 		return cdr;
324 	}
325 
326 	/**
327 	 * create a Gantt diagram
328 	 * 
329 	 * @param dataPlanning
330 	 * @return JFreeChart
331 	 * @throws ParseException,
332 	 *             NoClassDefFoundError, InternalError
333 	 * @throws NoClassDefFoundError
334 	 * @throws InternalError
335 	 */
336 	public JFreeChart createGantt(Hashtable dataPlanning)
337 			throws ParseException, NoClassDefFoundError, InternalError {
338 
339 		IntervalCategoryDataset dataset = createDataset(dataPlanning);
340 		JFreeChart chart = createChart(dataset);
341 		return chart;
342 	}
343 
344 	/**
345 	 * @param data
346 	 * @return IntervalCategoryDataset
347 	 * @throws ParseException
348 	 */
349 	public IntervalCategoryDataset createDataset(Hashtable data)
350 			throws ParseException {
351 
352 		final TaskSeries s1 = new TaskSeries("Conges");
353 		for (Enumeration edata = data.keys(); edata.hasMoreElements();) {
354 			String nom = (String) edata.nextElement();
355 			Vector list = (Vector) data.get(nom);
356 			Date firstDate = new Date();
357 			Date lastDate = new Date();
358 			for (Enumeration enlist = list.elements(); enlist.hasMoreElements();) {
359 				CalendarData cd = (CalendarData) enlist.nextElement();
360 
361 				String db = cd.getDatedeb();
362 				String df = cd.getDatefin();
363 				Date ddb = new SimpleDateFormat("dd/MM/yyyy").parse(db);
364 				Date ddf = new SimpleDateFormat("dd/MM/yyyy").parse(df);
365 				Calendar cal = Calendar.getInstance();
366 				cal.setTime(ddf);
367 				cal.add(Calendar.DATE, 1);
368 				ddf = cal.getTime();
369 
370 				if (ddb.compareTo(firstDate) < 0) {
371 					firstDate = ddb;
372 				}
373 				if (ddf.compareTo(lastDate) > 0) {
374 					lastDate = ddf;
375 				}
376 			}
377 			Task task = new Task(nom, firstDate, lastDate);
378 			task.setPercentComplete(1.0);
379 
380 			for (Enumeration enlist = list.elements(); enlist.hasMoreElements();) {
381 				CalendarData cd = (CalendarData) enlist.nextElement();
382 				String raison = cd.getRaison();
383 				String db = cd.getDatedeb();
384 				String df = cd.getDatefin();
385 				Date ddb = new SimpleDateFormat("dd/MM/yyyy").parse(db);
386 				Date ddf = new SimpleDateFormat("dd/MM/yyyy").parse(df);
387 
388 				Calendar cal = Calendar.getInstance();
389 				cal.setTime(ddf);
390 				cal.add(Calendar.DATE, 1);
391 				ddf = cal.getTime();
392 
393 				if (ddb.compareTo(firstDate) < 0) {
394 					firstDate = ddb;
395 				}
396 				if (ddf.compareTo(lastDate) > 0) {
397 					lastDate = ddf;
398 				}
399 				Task subtask = new Task(raison, ddb, ddf);
400 				subtask.setPercentComplete(1.0);
401 				task.addSubtask(subtask);
402 			}
403 
404 			s1.add(task);
405 
406 		}
407 
408 		TaskSeriesCollection collection = new TaskSeriesCollection();
409 		collection.add(s1);
410 
411 		return collection;
412 	}
413 
414 	private JFreeChart createChart(IntervalCategoryDataset dataset)
415 			throws NoClassDefFoundError, InternalError {
416 		JFreeChart chart = ChartFactory.createGanttChart("Planning", // chart
417 				// title
418 				"Employé(e)s", // domain axis label
419 				"Date", // range axis label
420 				dataset, // data
421 				false, // include legend
422 				false, // tooltips
423 				false // urls
424 				);
425 		// chart.getCategoryPlot().getDomainAxis().setMaxCategoryLabelWidthRatio(10.0f);
426 		CategoryPlot plot = (CategoryPlot) chart.getPlot();
427 
428 		plot.getDomainAxis().setMaxCategoryLabelWidthRatio(1000.0f);
429 		plot.getRangeAxis().setAutoRange(true);
430 		GanttRenderer renderer = (GanttRenderer) plot.getRenderer();
431 
432 		renderer.setCompletePaint(Color.blue);
433 		renderer.setIncompletePaint(Color.blue);
434 		renderer.setSeriesPaint(0, Color.blue);
435 
436 		return chart;
437 	}
438 
439 	/**
440 	 * 
441 	 * @param ped
442 	 * @param employee
443 	 * @param request
444 	 * @param httpSession
445 	 * @param ad
446 	 * @param type
447 	 */
448 	public void sendEmail(PendingEventData ped, EmployeeData employee,
449 			HttpServletRequest request, HttpSession httpSession, AccessData ad,
450 			int type) throws Exception {
451 		// on envoie un mail contenant les donn�es de l'absence et le demandeur
452 		// au responsable hi�rarchique
453 		// Get system properties
454 
455 		if (httpSession.getServletContext().getAttribute("server") != null
456 				&& !httpSession.getServletContext().getAttribute("server")
457 						.toString().equals("")) {
458 
459 			String server = (String) httpSession.getServletContext()
460 					.getAttribute("server");
461 
462 			// comme adresse email d'envoi on prend l'email de l'admin
463 			UserData adminData = ad.searchUser("ADMIN");
464 			String from = adminData.getEmail();
465 			// le (ou les) superieur hierarchique est averti de la demande
466 			Vector supervisors = ad.searchSupervisor(employee, ad);
467 			String toSupervisor = "";
468 			if (supervisors != null && supervisors.size() > 1) {
469 				Iterator iter = supervisors.iterator();
470 				// on verifie si l'employ� est le chef d'�quipe
471 				while (iter.hasNext()) {
472 					UserData supervisor = (UserData) iter.next();
473 					if (supervisor.getNom().equals(employee.getNom())
474 							&& supervisor.getPrenom().equals(
475 									employee.getPrenom())) {
476 						toSupervisor = supervisor.getEmail();
477 						break;
478 					}
479 				}
480 
481 				if (toSupervisor.equals("")) {
482 					// si l'employ� n'est pas le chef d equipe alors on cherche
483 					// ce dernier
484 					iter = supervisors.iterator();
485 					while (iter.hasNext()) {
486 						UserData supervisor = (UserData) iter.next();
487 						if (supervisor.getTeam().equals(employee.getTeam())) {
488 							toSupervisor = supervisor.getEmail();
489 							break;
490 						}
491 					}
492 				}
493 			} else if (supervisors == null || supervisors.size() == 0) {
494 				toSupervisor = "";
495 			} else {
496 				toSupervisor = ((UserData) supervisors.get(0)).getEmail();
497 			}
498 
499 			if (!toSupervisor.equals("")) {
500 				Properties props = System.getProperties();
501 
502 				// Setup mail server
503 				props.put("mail.smtp.host", server);
504 
505 				// Get session
506 				Session session = Session.getDefaultInstance(props, null);
507 
508 				// Define message
509 				MimeMessage message = new MimeMessage(session);
510 				message.setFrom(new InternetAddress(from));
511 				message.addRecipient(Message.RecipientType.TO,
512 						new InternetAddress(toSupervisor));
513 
514 				message.setSubject(Messages.getString("mail.subject.1"));
515 				String text = "";
516 				text += Messages.getString("mail.text.event.0")
517 						+ ped.getRaison();
518 				String mode = "";
519 				if (type == 0) {
520 					mode = Messages.getString("validating.C");
521 				}
522 				if (type == 1) {
523 					mode = Messages.getString("validating.M");
524 				}
525 				if (type == 2) {
526 					mode = Messages.getString("validating.D");
527 				}
528 				text += Messages.getString("mail.text.event.1") + " " + mode;
529 				text += " " + Messages.getString("mail.text.event.2") + " "
530 						+ ped.getPrenom() + " " + ped.getNom();
531 				text += " " + Messages.getString("mail.text.event.datedeb")
532 						+ " " + ped.getDatedeb();
533 				text += " " + Messages.getString("mail.text.event.datefin")
534 						+ " " + ped.getDatefin() + ".\n";
535 				text += Messages.getString("mail.text.event.confirm")
536 						+ " http://" + request.getServerName() + ":"
537 						+ request.getServerPort() + request.getContextPath();
538 				System.out.println("text email=" + text);
539 
540 				message.setText(text);
541 
542 				// Send message
543 				Transport.send(message);
544 			}
545 
546 		} else {
547 			throw new Exception(Messages.getString("error.no.mail.server"));
548 		}
549 	}
550 
551 	/**
552 	 * @param ped
553 	 * @param eid
554 	 * @param request
555 	 * @param httpSession
556 	 * @param ad
557 	 * @param type
558 	 */
559 	public void sendEmailValidation(PendingEventData ped,
560 			EmployeeIdCalData eid, HttpServletRequest request,
561 			HttpSession httpSession, AccessData ad, int type) throws Exception {
562 		// on envoie un mail contenant la reponse du responsable hi�rarchique
563 		// sur les donn�es de l'absence au le demandeur
564 
565 		if (httpSession.getServletContext().getAttribute("server") != null
566 				&& !httpSession.getServletContext().getAttribute("server")
567 						.toString().equals("")) {
568 
569 			String server = (String) httpSession.getServletContext()
570 					.getAttribute("server");
571 
572 			// comme adresse email d'envoi on prend l'email de l'admin
573 			UserData adminData = ad.searchUser("ADMIN");
574 			String from = adminData.getEmail();
575 
576 			// l employee est le destinataire
577 			String toEmployee = "";
578 			EmployeeData employee = new EmployeeData();
579 			employee.setNom(eid.getNom());
580 			employee.setPrenom(eid.getPrenom());
581 			UserData user = ad.searchUser(employee);
582 			toEmployee = user.getEmail();
583 			if (!toEmployee.equals("")) {
584 				Properties props = System.getProperties();
585 
586 				// Setup mail server
587 				props.put("mail.smtp.host", server);
588 
589 				// Get session
590 				Session session = Session.getDefaultInstance(props, null);
591 
592 				// Define message
593 				MimeMessage message = new MimeMessage(session);
594 				message.setFrom(new InternetAddress(from));
595 				message.addRecipient(Message.RecipientType.TO,
596 						new InternetAddress(toEmployee));
597 				if (type == 0) {
598 					message.setSubject(Messages
599 							.getString("mail.subject.accept"));
600 				}
601 				if (type == 1) {
602 					message.setSubject(Messages
603 							.getString("mail.subject.refuse"));
604 				}
605 				String text = "";
606 				text += Messages.getString("mail.text.event.10")
607 						+ ped.getRaison();
608 				text += Messages.getString("mail.text.event.12");
609 				text += " " + Messages.getString("mail.text.event.datedeb")
610 						+ " " + ped.getDatedeb();
611 				text += " " + Messages.getString("mail.text.event.datefin")
612 						+ " " + ped.getDatefin();
613 				if (type == 0) {
614 					text += " " + Messages.getString("mail.text.event.accept");
615 				}
616 				if (type == 1) {
617 					text += " " + Messages.getString("mail.text.event.refuse");
618 				}
619 				text += "\nhttp://" + request.getServerName() + ":"
620 						+ request.getServerPort() + request.getContextPath();
621 				System.out.println("text email=" + text);
622 
623 				message.setText(text);
624 
625 				// Send message
626 				Transport.send(message);
627 			}
628 
629 		} else {
630 			throw new Exception(Messages.getString("error.no.mail.server"));
631 		}
632 	}
633 
634 	/**
635 	 * 
636 	 * @param params
637 	 * @param reason
638 	 * @param employee
639 	 * @param fromDate
640 	 * @param toDate
641 	 * @return maxNBJours
642 	 * @throws Exception
643 	 */
644 	public String getMaxNbDaysForReasonInParams(Vector params, String reason,
645 			EmployeeData employee, String fromDate, String toDate)
646 			throws Exception {
647 		// on cherche le nb max de jours autorises
648 		String maxNbJours = "0";
649 		Iterator iter = params.iterator();
650 		String type = "progressif";
651 		while (iter.hasNext()) {
652 			ParamsData param = (ParamsData) iter.next();
653 			String praison = param.getReason();
654 
655 			if (praison.equals(reason)) {
656 				maxNbJours = param.getNbJours();
657 				type = param.getType();
658 				break;
659 			}
660 		}
661 
662 		// on verifie si le nombre max de jours ne doit pas etre restreint en
663 		// fonction de la date d'entr�e de l'employ�(e)
664 		String entryDate = employee.getEntryDate();
665 		if (entryDate != null && !entryDate.equals("")) {
666 			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
667 			Date entryDate_d = sdf.parse(entryDate);
668 			Date fromDate_d = sdf.parse(fromDate);
669 			Date toDate_d = sdf.parse(toDate);
670 
671 			if (type.equals("revolu")) {
672 				Calendar cal = Calendar.getInstance();
673 				cal.setTime(fromDate_d);
674 				cal.add(Calendar.YEAR, -1);
675 				fromDate_d = cal.getTime();
676 				cal.setTime(toDate_d);
677 				cal.add(Calendar.YEAR, -1);
678 				toDate_d = cal.getTime();
679 			}
680 
681 			if (entryDate_d.after(toDate_d)) {
682 				maxNbJours = "0";
683 			} else if (entryDate_d.after(fromDate_d)
684 					&& entryDate_d.before(toDate_d)) {
685 				long difference = entryDate_d.getTime() - fromDate_d.getTime();
686 				long msPerDay = 24 * 60 * 60 * 1000;
687 				long days = difference / msPerDay;
688 				// System.out.println("nb jours de difference " + days);
689 				// days = Math.round(days);
690 
691 				float restdaysPerDay = new Float(maxNbJours).floatValue()
692 						/ (12 * 30);
693 				// System.out.println("restdaysPerDays " +restdaysPerDay);
694 				float decreasingDays = days * restdaysPerDay;
695 				// System.out.println("decreasingDays " + decreasingDays);
696 
697 				float maxNbDays_f = new Float(maxNbJours).floatValue()
698 						- decreasingDays;
699 				// System.out.println("maxNbDays_f " + maxNbDays_f);
700 				DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
701 				// keep only two decimal
702 				df.setMaximumFractionDigits(2);
703 				maxNbJours = df.format(maxNbDays_f);
704 			}
705 		}
706 
707 		return maxNbJours;
708 	}
709 
710 	/**
711 	 * retourne la p�riode de calcul des cong�s � partir de la date du jour
712 	 * 
713 	 * @param params -
714 	 *            Vector des param�tres de cong�s
715 	 * @return PeriodParamsData
716 	 * @throws Exception
717 	 */
718 	public PeriodParamsData searchPeriodInParams(Vector params)
719 			throws Exception {
720 		Date fromDate = new Date();
721 		Date endDate = new Date();
722 
723 		for (Enumeration enumr = params.elements(); enumr.hasMoreElements();) {
724 			ParamsData param = (ParamsData) enumr.nextElement();
725 			String datedeb = param.getDateDebut();
726 			if (datedeb != null && !datedeb.equals("")) {
727 				String datefin = param.getDateFin();
728 
729 				Date dateDeb = new Date();
730 				Date dateFin = new Date();
731 
732 				// format attendu jj/mm
733 				int idx = datedeb.indexOf("/");
734 				if (idx > -1 && idx < datedeb.length()) {
735 					String jjdeb = datedeb.substring(0, idx);
736 					String mmdeb = datedeb.substring(idx + 1);
737 					String jjfin = datefin.substring(0, idx);
738 					String mmfin = datefin.substring(idx + 1);
739 
740 					int debMonth = new Integer(mmdeb).intValue();
741 					int finMonth = new Integer(mmfin).intValue();
742 					int debDay = new Integer(jjdeb).intValue();
743 					int finDay = new Integer(jjfin).intValue();
744 
745 					Calendar cal = Calendar.getInstance();
746 
747 					int currentMonth = cal.get(Calendar.MONTH) + 1;
748 
749 					if (currentMonth >= debMonth) {
750 						// on est dans la meme annee
751 						int year = cal.get(Calendar.YEAR);
752 						cal.set(year, debMonth - 1, debDay);
753 						dateDeb = cal.getTime();
754 						cal = Calendar.getInstance();
755 					}
756 					if (currentMonth < debMonth) {
757 						// on est dans l'annee + 1
758 						int year = cal.get(Calendar.YEAR) - 1;
759 						cal.set(year, debMonth - 1, debDay);
760 						dateDeb = cal.getTime();
761 						cal = Calendar.getInstance();
762 					}
763 					if (currentMonth > finMonth) {
764 						// on est dans l'annee - 1
765 						int year = cal.get(Calendar.YEAR) + 1;
766 						cal.set(year, finMonth - 1, finDay);
767 						dateFin = cal.getTime();
768 						cal = Calendar.getInstance();
769 					}
770 					if (currentMonth <= finMonth) {
771 						// on est dans la meme annee
772 						int year = cal.get(Calendar.YEAR);
773 						cal.set(year, finMonth - 1, finDay);
774 						dateFin = cal.getTime();
775 						cal = Calendar.getInstance();
776 					}
777 
778 					if (dateDeb.compareTo(fromDate) < 0) {
779 						fromDate = dateDeb;
780 					}
781 					if (dateFin.compareTo(endDate) > 0) {
782 						endDate = dateFin;
783 					}
784 				}
785 			}
786 		}
787 
788 		PeriodParamsData ppd = new PeriodParamsData();
789 		ppd.setFromDate(fromDate);
790 		ppd.setEndDate(endDate);
791 
792 		return ppd;
793 	}
794 
795 	/**
796 	 * 
797 	 * @param params
798 	 * @param raison
799 	 * @return PeriodParamsData
800 	 * @throws Exception
801 	 */
802 	public PeriodParamsData searchPeriodInParamsForReason(Vector params,
803 			String raison) throws Exception {
804 		Date debut = new Date();
805 		Date fin = new Date();
806 
807 		for (Enumeration enumeration = params.elements(); enumeration
808 				.hasMoreElements();) {
809 			ParamsData param = (ParamsData) enumeration.nextElement();
810 			String praison = param.getReason();
811 
812 			if (praison.equals(raison)) {
813 				String datedeb = param.getDateDebut();
814 				if (datedeb != null && !datedeb.equals("")) {
815 					String datefin = param.getDateFin();
816 
817 					// format attendu jj/mm
818 					int idx = datedeb.indexOf("/");
819 					if (idx > -1 && idx < datedeb.length()) {
820 						String jjdeb = datedeb.substring(0, idx);
821 						String mmdeb = datedeb.substring(idx + 1);
822 						String jjfin = datefin.substring(0, idx);
823 						String mmfin = datefin.substring(idx + 1);
824 
825 						int debMonth = new Integer(mmdeb).intValue();
826 						int finMonth = new Integer(mmfin).intValue();
827 						int debDay = new Integer(jjdeb).intValue();
828 						int finDay = new Integer(jjfin).intValue();
829 
830 						Calendar cal = Calendar.getInstance();
831 
832 						int currentMonth = cal.get(Calendar.MONTH) + 1;
833 						if (currentMonth >= debMonth) {
834 							// on est dans la meme annee
835 							int year = cal.get(Calendar.YEAR);
836 							cal.set(year, debMonth - 1, debDay);
837 							debut = cal.getTime();
838 							cal = Calendar.getInstance();
839 						}
840 						if (currentMonth < debMonth) {
841 							// on est dans l'annee + 1
842 							int year = cal.get(Calendar.YEAR) - 1;
843 							cal.set(year, debMonth - 1, debDay);
844 							debut = cal.getTime();
845 							cal = Calendar.getInstance();
846 						}
847 						if (currentMonth > finMonth) {
848 							// on est dans l'annee - 1
849 							int year = cal.get(Calendar.YEAR) + 1;
850 							cal.set(year, finMonth - 1, finDay);
851 							fin = cal.getTime();
852 							cal = Calendar.getInstance();
853 						}
854 						if (currentMonth <= finMonth) {
855 							// on est dans la meme annee
856 							int year = cal.get(Calendar.YEAR);
857 							cal.set(year, finMonth - 1, finDay);
858 							fin = cal.getTime();
859 							cal = Calendar.getInstance();
860 						}
861 					}
862 				}
863 			}
864 		}
865 
866 		PeriodParamsData ppd = new PeriodParamsData();
867 		ppd.setFromDate(debut);
868 		ppd.setEndDate(fin);
869 
870 		return ppd;
871 	}
872 
873 	/**
874 	 * 
875 	 * @param fileDirPath
876 	 * @param employee
877 	 * @param params
878 	 * @return Vector
879 	 * @throws Exception
880 	 */
881 	public Vector getEmployeeStats(String fileDirPath, EmployeeData employee,
882 			Vector params) throws Exception {
883 		Vector stats = new Vector();
884 
885 		PeriodParamsData ppd = searchPeriodInParams(params);
886 
887 		Date fromDate = ppd.getFromDate();
888 		Date endDate = ppd.getEndDate();
889 
890 		String debDate = new SimpleDateFormat("dd/MM/yyyy").format(fromDate);
891 		String finDate = new SimpleDateFormat("dd/MM/yyyy").format(endDate);
892 
893 		AccessData ad = new AccessDataMng().getInstance(employee, fileDirPath,
894 				debDate, finDate);
895 
896 		Vector vCalendarData = new Vector();
897 		try {
898 			vCalendarData = ad.readCalendarData(employee);
899 		} catch (Exception e) {
900 			throw new ServletException(e.getMessage());
901 		}
902 		// System.out.println(vCalendarData.toString());
903 		// � pr�sent on cr�� des calendarData ne contenant qu'une seule journ�e
904 		// i.e. on discretise les CalendarData pr�c�demment obtenus
905 		// CommonCal commonCal = new CommonCal();
906 
907 		Vector lstCalendarData = getDiscretCalData(vCalendarData, employee,
908 				new Hashtable());
909 
910 		for (Enumeration enumr = lstCalendarData.elements(); enumr
911 				.hasMoreElements();) {
912 			CalendarData cd = (CalendarData) enumr.nextElement();
913 			String raison = cd.getRaison();
914 
915 			// dans params il y a la periode en fonction de la raison
916 			ppd = searchPeriodInParamsForReason(params, raison);
917 			Date debut = ppd.getFromDate();
918 			Date fin = ppd.getEndDate();
919 
920 			Date cddeb = new SimpleDateFormat("dd/MM/yyyy").parse(cd
921 					.getDatedeb());
922 			Date cdfin = new SimpleDateFormat("dd/MM/yyyy").parse(cd
923 					.getDatefin());
924 
925 			if (cddeb.compareTo(debut) >= 0 && cddeb.compareTo(fin) <= 0
926 					&& cdfin.compareTo(debut) >= 0 && cdfin.compareTo(fin) <= 0) {
927 				double nombreJours = 0;
928 				double jourAjout = 0;
929 
930 				boolean foundSD = false;
931 
932 				for (Enumeration en = stats.elements(); en.hasMoreElements();) {
933 					StatsData stat = (StatsData) en.nextElement();
934 					String sraison = stat.getRaison();
935 					String nbJours = stat.getNbJours();
936 					String ddeb = stat.getDateDebut();
937 					String dfin = stat.getDateFin();
938 
939 					if (sraison.equals(raison)) {
940 
941 						nombreJours = new Double(nbJours).doubleValue();
942 
943 						if (cd.isCbaprem() && cd.isCbmatin()) {
944 							jourAjout = 1;
945 						} else if (cd.isCbaprem() || cd.isCbmatin()) {
946 							jourAjout = 0.5;
947 						}
948 
949 						nombreJours += jourAjout;
950 
951 						stats.remove(stat);
952 
953 						stat.setDateDebut(ddeb);
954 						stat.setDateFin(dfin);
955 						stat.setNbJours("" + nombreJours);
956 						stat.setRaison(sraison);
957 
958 						// on cherche le nb max de jours autorises
959 						// for(Enumeration enumeration = params.elements();
960 						// enumeration.hasMoreElements();)
961 						// {
962 						// ParamsData param =
963 						// (ParamsData)enumeration.nextElement();
964 						// String praison = param.getReason();
965 						//						
966 						// if(praison.equals(raison))
967 						// {
968 						// stat.setMaxNBJours(""+param.getNbJours());
969 						// break;
970 						// }
971 						// }
972 						String maxNbJours = getMaxNbDaysForReasonInParams(
973 								params, raison, employee, ddeb, dfin);
974 						stat.setMaxNBJours(maxNbJours);
975 
976 						stats.add(stat);
977 						foundSD = true;
978 						break;
979 					}
980 				}
981 
982 				if (!foundSD) {
983 					// on cree le StatsData correspondant a la raison
984 					StatsData stat = new StatsData();
985 					stat.setDateDebut(new SimpleDateFormat("dd/MM/yyyy")
986 							.format(debut));
987 					stat.setDateFin(new SimpleDateFormat("dd/MM/yyyy")
988 							.format(fin));
989 					if (cd.isCbaprem() && cd.isCbmatin()) {
990 						jourAjout = 1;
991 					} else if (cd.isCbaprem() || cd.isCbmatin()) {
992 						jourAjout = 0.5;
993 					}
994 
995 					nombreJours += jourAjout;
996 					stat.setNbJours("" + nombreJours);
997 					// on cherche le nb max de jours autorises
998 					for (Enumeration enumeration = params.elements(); enumeration
999 							.hasMoreElements();) {
1000 						ParamsData param = (ParamsData) enumeration
1001 								.nextElement();
1002 						String praison = param.getReason();
1003 
1004 						if (praison.equals(raison)) {
1005 							stat.setMaxNBJours("" + param.getNbJours());
1006 							break;
1007 						}
1008 					}
1009 					stat.setRaison(raison);
1010 
1011 					stats.add(stat);
1012 				}
1013 			}
1014 		}
1015 
1016 		return stats;
1017 	}
1018 
1019 }