View Javadoc
1   /*
2    * Copyright (c) 2002-2014, Mairie de Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.plugins.form.utils;
35  
36  import fr.paris.lutece.plugins.form.business.EntryFilter;
37  import fr.paris.lutece.plugins.form.business.EntryHome;
38  import fr.paris.lutece.plugins.form.business.EntryType;
39  import fr.paris.lutece.plugins.form.business.EntryTypeHome;
40  import fr.paris.lutece.plugins.form.business.Field;
41  import fr.paris.lutece.plugins.form.business.FieldHome;
42  import fr.paris.lutece.plugins.form.business.Form;
43  import fr.paris.lutece.plugins.form.business.FormError;
44  import fr.paris.lutece.plugins.form.business.FormFilter;
45  import fr.paris.lutece.plugins.form.business.FormHome;
46  import fr.paris.lutece.plugins.form.business.FormSubmit;
47  import fr.paris.lutece.plugins.form.business.IEntry;
48  import fr.paris.lutece.plugins.form.business.Response;
49  import fr.paris.lutece.plugins.form.business.StatisticFormSubmit;
50  import fr.paris.lutece.portal.business.mailinglist.Recipient;
51  import fr.paris.lutece.portal.business.user.AdminUser;
52  import fr.paris.lutece.portal.service.captcha.CaptchaSecurityService;
53  import fr.paris.lutece.portal.service.i18n.I18nService;
54  import fr.paris.lutece.portal.service.mail.MailService;
55  import fr.paris.lutece.portal.service.mailinglist.AdminMailingListService;
56  import fr.paris.lutece.portal.service.plugin.Plugin;
57  import fr.paris.lutece.portal.service.plugin.PluginService;
58  import fr.paris.lutece.portal.service.template.AppTemplateService;
59  import fr.paris.lutece.portal.service.util.AppLogService;
60  import fr.paris.lutece.portal.service.workgroup.AdminWorkgroupService;
61  import fr.paris.lutece.util.ReferenceList;
62  import fr.paris.lutece.util.html.HtmlTemplate;
63  import fr.paris.lutece.util.xml.XmlUtil;
64  
65  import org.jfree.chart.ChartFactory;
66  import org.jfree.chart.JFreeChart;
67  import org.jfree.chart.plot.XYPlot;
68  import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
69  
70  import org.jfree.data.time.Day;
71  import org.jfree.data.time.Month;
72  import org.jfree.data.time.TimeSeries;
73  import org.jfree.data.time.TimeSeriesCollection;
74  import org.jfree.data.time.Week;
75  import org.jfree.data.xy.XYDataset;
76  
77  import java.awt.Color;
78  
79  import java.sql.Timestamp;
80  
81  import java.text.DateFormat;
82  
83  import java.util.ArrayList;
84  import java.util.Calendar;
85  import java.util.Collection;
86  import java.util.Date;
87  import java.util.GregorianCalendar;
88  import java.util.HashMap;
89  import java.util.List;
90  import java.util.Locale;
91  
92  import javax.servlet.http.HttpServletRequest;
93  import javax.servlet.http.HttpServletResponse;
94  
95  
96  /**
97   *
98   * class FormUtils
99   *
100  */
101 public final class FormUtils
102 {
103     // other constants
104     public static final String CONSTANT_GROUP_BY_DAY = "0";
105     public static final String CONSTANT_GROUP_BY_WEEK = "1";
106     public static final String CONSTANT_GROUP_BY_MONTH = "2";
107     public static final String EMPTY_STRING = "";
108     private static final String MARK_LOCALE = "locale";
109     private static final String MARK_URL_ACTION = "url_action";
110     private static final String MARK_ENTRY = "entry";
111     private static final String MARK_FIELD = "field";
112     private static final String MARK_STR_LIST_CHILDREN = "str_list_entry_children";
113     private static final String MARK_FORM = "form";
114     private static final String MARK_JCAPTCHA = "jcaptcha";
115     private static final String MARK_STR_ENTRY = "str_entry";
116     private static final String PARAMETER_ID_ENTRY_TYPE = "id_type";
117     private static final String JCAPTCHA_PLUGIN = "jcaptcha";
118     private static final String CONSTANT_WHERE = " WHERE ";
119     private static final String CONSTANT_AND = " AND ";
120 
121     //	 Xml Tags
122     private static final String TAG_FORM = "form";
123     private static final String TAG_FORM_TITLE = "form-title";
124     private static final String TAG_FORM_SUBMIT = "submit";
125     private static final String TAG_FORM_SUBMITS = "submits";
126     private static final String TAG_FORM_SUBMIT_ID = "submit-id";
127     private static final String TAG_FORM_SUBMIT_DATE = "submit-date";
128     private static final String TAG_FORM_SUBMIT_IP = "submit-ip";
129     private static final String TAG_QUESTIONS = "questions";
130     private static final String TAG_QUESTION = "question";
131     private static final String TAG_QUESTION_TITLE = "question-title";
132     private static final String TAG_RESPONSES = "responses";
133     private static final String TAG_RESPONSE = "response";
134 
135     //TEMPLATE
136     private static final String TEMPLATE_DIV_CONDITIONAL_ENTRY = "admin/plugins/form/html_code_div_conditional_entry.html";
137     private static final String TEMPLATE_HTML_CODE_FORM = "admin/plugins/form/html_code_form.html";
138     private static final String TEMPLATE_NOTIFICATION_MAIL_END_DISPONIBILITY = "admin/plugins/form/notification_mail_end_disponibility.html";
139     private static final String TEMPLATE_NOTIFICATION_MAIL_FORM_SUBMIT = "admin/plugins/form/notification_mail_form_submit.html";
140 
141     //property
142     private static final String PROPERTY_NOTIFICATION_MAIL_END_DISPONIBILITY_SUBJECT = "form.notificationMailEndDisponibility.subject";
143     private static final String PROPERTY_NOTIFICATION_MAIL_END_DISPONIBILITY_SENDER_NAME = "form.notificationMailEndDisponibility.senderName";
144     private static final String PROPERTY_NOTIFICATION_MAIL_FORM_SUBMIT_SUBJECT = "form.notificationMailFormSubmit.subject";
145     private static final String PROPERTY_NOTIFICATION_MAIL_FORM_SUBMIT_SENDER_NAME = "form.notificationMailFormSubmit.senderName";
146 
147     /**
148      * FormUtils
149      *
150      */
151     private FormUtils(  )
152     {
153     }
154 
155     /**
156      * sendMail to the mailing list associate to the form a mail of end disponibility
157      * @param form the form
158      * @param locale the locale
159      */
160     public static void sendNotificationMailEndDisponibility( Form form, Locale locale )
161     {
162         try
163         {
164             String strSubject = I18nService.getLocalizedString( PROPERTY_NOTIFICATION_MAIL_END_DISPONIBILITY_SUBJECT,
165                     locale );
166             String strSenderName = I18nService.getLocalizedString( PROPERTY_NOTIFICATION_MAIL_END_DISPONIBILITY_SENDER_NAME,
167                     locale );
168             String strSenderEmail = MailService.getNoReplyEmail(  );
169 
170             Collection<Recipient> listRecipients = AdminMailingListService.getRecipients( form.getIdMailingList(  ) );
171             HashMap model = new HashMap(  );
172             model.put( MARK_FORM, form );
173 
174             HtmlTemplate t = AppTemplateService.getTemplate( TEMPLATE_NOTIFICATION_MAIL_END_DISPONIBILITY, locale, model );
175 
176             // Send Mail
177             for ( Recipient recipient : listRecipients )
178             {
179                 // Build the mail message
180                 MailService.sendMailHtml( recipient.getEmail(  ), strSenderName, strSenderEmail, strSubject,
181                     t.getHtml(  ) );
182             }
183         }
184         catch ( Exception e )
185         {
186             AppLogService.error( "Error during Notify end disponibilty of form : " + e.getMessage(  ) );
187         }
188     }
189 
190     /**
191      * sendMail to the mailing list associate to the form a mail of new form submit
192      * @param form the form
193      * @param locale the locale
194      */
195     public static void sendNotificationMailFormSubmit( Form form, Locale locale )
196     {
197         try
198         {
199             String strSubject = I18nService.getLocalizedString( PROPERTY_NOTIFICATION_MAIL_FORM_SUBMIT_SUBJECT, locale );
200             String strSenderName = I18nService.getLocalizedString( PROPERTY_NOTIFICATION_MAIL_FORM_SUBMIT_SENDER_NAME,
201                     locale );
202             String strSenderEmail = MailService.getNoReplyEmail(  );
203 
204             Collection<Recipient> listRecipients = AdminMailingListService.getRecipients( form.getIdMailingList(  ) );
205             HashMap model = new HashMap(  );
206             model.put( MARK_FORM, form );
207 
208             HtmlTemplate t = AppTemplateService.getTemplate( TEMPLATE_NOTIFICATION_MAIL_FORM_SUBMIT, locale, model );
209 
210             // Send Mail
211             for ( Recipient recipient : listRecipients )
212             {
213                 // Build the mail message
214                 MailService.sendMailHtml( recipient.getEmail(  ), strSenderName, strSenderEmail, strSubject,
215                     t.getHtml(  ) );
216             }
217         }
218         catch ( Exception e )
219         {
220             AppLogService.error( "Error during Notify a new form submit" + e.getMessage(  ) );
221         }
222     }
223 
224     /**
225      * return a timestamp Object which correspond with the string specified in parameter.
226      * @param date the date who must convert
227      * @param locale the locale
228      * @return a timestamp Object which correspond with the string specified in parameter.
229      */
230     public static Timestamp getDateLastMinute( Date date, Locale locale )
231     {
232         if ( date == null )
233         {
234             return null;
235         }
236 
237         Calendar caldate = new GregorianCalendar(  );
238         caldate.setTime( date );
239         caldate.set( Calendar.MILLISECOND, 0 );
240         caldate.set( Calendar.SECOND, 0 );
241         caldate.set( Calendar.HOUR_OF_DAY, caldate.getActualMaximum( Calendar.HOUR_OF_DAY ) );
242         caldate.set( Calendar.MINUTE, caldate.getActualMaximum( Calendar.MINUTE ) );
243 
244         Timestamp timeStamp = new Timestamp( caldate.getTimeInMillis(  ) );
245 
246         return timeStamp;
247     }
248 
249     /**
250      * return a timestamp Object which correspond with the string specified in parameter.
251      * @param date the date who must convert
252      * @param locale the locale
253      * @return a timestamp Object which correspond with the string specified in parameter.
254      */
255     public static Timestamp getDateFirstMinute( Date date, Locale locale )
256     {
257         if ( date == null )
258         {
259             return null;
260         }
261 
262         Calendar caldate = new GregorianCalendar(  );
263         caldate.setTime( date );
264         caldate.set( Calendar.MILLISECOND, 0 );
265         caldate.set( Calendar.SECOND, 0 );
266         caldate.set( Calendar.HOUR_OF_DAY, caldate.getActualMinimum( Calendar.HOUR_OF_DAY ) );
267         caldate.set( Calendar.MINUTE, caldate.getActualMinimum( Calendar.MINUTE ) );
268 
269         Timestamp timeStamp = new Timestamp( caldate.getTimeInMillis(  ) );
270 
271         return timeStamp;
272     }
273 
274     /**
275      * return the day  of the timestamp
276      * in parameter
277      * @param timestamp date
278      * @return the day  of the timestamp in parameter
279      */
280     public static int getDay( Timestamp timestamp )
281     {
282         Calendar caldate = new GregorianCalendar(  );
283         caldate.setTime( timestamp );
284 
285         return caldate.get( Calendar.DAY_OF_MONTH );
286     }
287 
288     /**
289      * return the week  of the timestamp
290      * in parameter
291      * @param timestamp date
292      * @return the week  of the timestamp in parameter
293      */
294     public static int getWeek( Timestamp timestamp )
295     {
296         Calendar caldate = new GregorianCalendar(  );
297         caldate.setTime( timestamp );
298 
299         return caldate.get( Calendar.WEEK_OF_YEAR );
300     }
301 
302     /**
303      * return the month  of the timestamp
304      * in parameter
305      * @param timestamp date
306      * @return the month  of the timestamp in parameter
307      */
308     public static int getMonth( Timestamp timestamp )
309     {
310         Calendar caldate = new GregorianCalendar(  );
311         caldate.setTime( timestamp );
312 
313         return caldate.get( Calendar.MONTH );
314     }
315 
316     /**
317      * return the year  of the timestamp
318      * in parameter
319      * @param timestamp date
320      * @return the year  of the timestamp in parameter
321      */
322     public static int getYear( Timestamp timestamp )
323     {
324         Calendar caldate = new GregorianCalendar(  );
325         caldate.setTime( timestamp );
326 
327         return caldate.get( Calendar.YEAR );
328     }
329 
330     /**
331      * return a timestamp Object which correspond to the timestamp
332      * in parameter add with a  number of times unit (day,week,month)specify in strTimesUnit .
333      * @param timestamp date
334      * @param strTimesUnit (day,week,month)
335      * @param nDecal the number of timesUnit
336      * @return a timestamp Object which correspond with the string specified in parameter
337      * add with a  number of times unit (day,week,month)specify in strTimesUnit.
338      */
339     public static Timestamp addStatisticInterval( Timestamp timestamp, String strTimesUnit, int nDecal )
340     {
341         int nTimesUnit = Calendar.DAY_OF_MONTH;
342 
343         if ( strTimesUnit.equals( FormUtils.CONSTANT_GROUP_BY_WEEK ) )
344         {
345             nTimesUnit = Calendar.WEEK_OF_MONTH;
346         }
347         else if ( strTimesUnit.equals( FormUtils.CONSTANT_GROUP_BY_MONTH ) )
348         {
349             nTimesUnit = Calendar.MONTH;
350         }
351 
352         Calendar caldate = new GregorianCalendar(  );
353         caldate.setTime( timestamp );
354         caldate.set( Calendar.MILLISECOND, 0 );
355         caldate.set( Calendar.SECOND, 0 );
356         caldate.set( Calendar.HOUR_OF_DAY, caldate.getActualMaximum( Calendar.HOUR_OF_DAY ) );
357         caldate.set( Calendar.MINUTE, caldate.getActualMaximum( Calendar.MINUTE ) );
358         caldate.add( nTimesUnit, nDecal );
359 
360         Timestamp timeStamp1 = new Timestamp( caldate.getTimeInMillis(  ) );
361 
362         return timeStamp1;
363     }
364 
365     /**
366      * Compare two timestamp and return true if  they have the same times unit(Day,week,month)
367      * @param  timestamp1 timestamp1
368      * @param  timestamp2 timestamp2
369      * @param strTimesUnit (day,week,month)
370      * @return Compare two timestamp and return true if  they have the same times unit(Day,week,month)
371      */
372     public static boolean sameDate( Timestamp timestamp1, Timestamp timestamp2, String strTimesUnit )
373     {
374         Calendar caldate1 = new GregorianCalendar(  );
375         caldate1.setTime( timestamp1 );
376 
377         Calendar caldate2 = new GregorianCalendar(  );
378         caldate2.setTime( timestamp2 );
379 
380         if ( strTimesUnit.equals( CONSTANT_GROUP_BY_DAY ) &&
381                 ( caldate1.get( Calendar.YEAR ) == caldate2.get( Calendar.YEAR ) ) &&
382                 ( caldate1.get( Calendar.DAY_OF_YEAR ) == caldate2.get( Calendar.DAY_OF_YEAR ) ) )
383         {
384             return true;
385         }
386         else if ( strTimesUnit.equals( CONSTANT_GROUP_BY_WEEK ) &&
387                 ( caldate1.get( Calendar.YEAR ) == caldate2.get( Calendar.YEAR ) ) &&
388                 ( caldate1.get( Calendar.WEEK_OF_YEAR ) == caldate2.get( Calendar.WEEK_OF_YEAR ) ) )
389         {
390             return true;
391         }
392         else if ( strTimesUnit.equals( CONSTANT_GROUP_BY_MONTH ) &&
393                 ( caldate1.get( Calendar.YEAR ) == caldate2.get( Calendar.YEAR ) ) &&
394                 ( caldate1.get( Calendar.MONTH ) == caldate2.get( Calendar.MONTH ) ) )
395         {
396             return true;
397         }
398 
399         return false;
400     }
401 
402     /**
403      * Converts une java.sql.Timestamp date in a String date in a "jj/mm/aaaa" format
404      *
405      * @param date java.sql.Timestamp date to convert
406      * @param locale the locale
407      * @return strDate The String date in the short locale format or the emmpty String if the date is null
408      * @deprecated
409      */
410     public static String getDateString( Timestamp date, Locale locale )
411     {
412         DateFormat dateFormat = DateFormat.getDateInstance( DateFormat.SHORT, locale );
413 
414         return dateFormat.format( date );
415     }
416 
417     /**
418      * return current Timestamp
419      * @return return current Timestamp
420      */
421     public static Timestamp getCurrentTimestamp(  )
422     {
423         return new Timestamp( GregorianCalendar.getInstance(  ).getTimeInMillis(  ) );
424     }
425 
426     /**
427      * return current date without hours, minutes and milliseconds
428      * @return return current date
429      */
430     public static Date getCurrentDate(  )
431     {
432         Calendar cal1 = Calendar.getInstance(  );
433         cal1.setTime( new Date(  ) );
434         cal1.set( Calendar.HOUR_OF_DAY, 0 );
435         cal1.set( Calendar.MINUTE, 0 );
436         cal1.set( Calendar.SECOND, 0 );
437         cal1.set( Calendar.MILLISECOND, 0 );
438 
439         return cal1.getTime(  );
440     }
441 
442     /**
443      * return an instance of IEntry function of type entry
444      * @param request the request
445      * @param plugin the plugin
446      * @return an instance of IEntry function of type entry
447      */
448     public static IEntry createEntryByType( HttpServletRequest request, Plugin plugin )
449     {
450         String strIdType = request.getParameter( PARAMETER_ID_ENTRY_TYPE );
451         int nIdType = -1;
452         IEntry entry = null;
453         EntryType entryType;
454 
455         if ( ( strIdType != null ) && !strIdType.equals( EMPTY_STRING ) )
456         {
457             try
458             {
459                 nIdType = Integer.parseInt( strIdType );
460             }
461             catch ( NumberFormatException ne )
462             {
463                 AppLogService.error( ne );
464 
465                 return null;
466             }
467         }
468 
469         if ( nIdType == -1 )
470         {
471             return null;
472         }
473 
474         entryType = EntryTypeHome.findByPrimaryKey( nIdType, plugin );
475 
476         try
477         {
478             entry = (IEntry) Class.forName( entryType.getClassName(  ) ).newInstance(  );
479             entry.setEntryType( entryType );
480         }
481         catch ( ClassNotFoundException e )
482         {
483             //  class doesn't exist
484             AppLogService.error( e );
485         }
486         catch ( InstantiationException e )
487         {
488             // Class is abstract or is an  interface or haven't accessible builder
489             AppLogService.error( e );
490         }
491         catch ( IllegalAccessException e )
492         {
493             // can't access to rhe class
494             AppLogService.error( e );
495         }
496 
497         return entry;
498     }
499 
500     /**
501      * return the index in the list of the entry whose key is specified  in parameter
502      * @param nIdEntry the key of the entry
503      * @param listEntry the list of the entry
504      * @return the index in the list of the entry whose key is specified  in parameter
505      */
506     public static int getIndexEntryInTheEntryList( int nIdEntry, List<IEntry> listEntry )
507     {
508         int nIndex = 0;
509 
510         for ( IEntry entry : listEntry )
511         {
512             if ( entry.getIdEntry(  ) == nIdEntry )
513             {
514                 return nIndex;
515             }
516 
517             nIndex++;
518         }
519 
520         return nIndex;
521     }
522 
523     /**
524      *  return the index in the list of the field whose key is specified  in parameter
525      * @param nIdField the key of the field
526      * @param listField the list of field
527      * @return the index in the list of the field whose key is specified  in parameter
528      */
529     public static int getIndexFieldInTheFieldList( int nIdField, List<Field> listField )
530     {
531         int nIndex = 0;
532 
533         for ( Field field : listField )
534         {
535             if ( field.getIdField(  ) == nIdField )
536             {
537                 return nIndex;
538             }
539 
540             nIndex++;
541         }
542 
543         return nIndex;
544     }
545 
546     /**
547      *  return the html code of the form
548      * @param form the form which html code must be return
549      * @param strUrlAction  the url who must be call after the form submit
550      * @param plugin the plugin
551      * @param locale the locale
552      * @return the html code of the form
553      */
554     public static String getHtmlForm( Form form, String strUrlAction, Plugin plugin, Locale locale )
555     {
556         List<IEntry> listEntryFirstLevel;
557         HashMap model = new HashMap(  );
558         HtmlTemplate template;
559         EntryFilter filter;
560         StringBuffer strBuffer = new StringBuffer(  );
561         filter = new EntryFilter(  );
562         filter.setIdForm( form.getIdForm(  ) );
563         filter.setEntryParentNull( EntryFilter.FILTER_TRUE );
564         filter.setFieldDependNull( EntryFilter.FILTER_TRUE );
565         listEntryFirstLevel = EntryHome.getEntryList( filter, plugin );
566 
567         for ( IEntry entry : listEntryFirstLevel )
568         {
569             FormUtils.getHtmlEntry( entry.getIdEntry(  ), plugin, strBuffer, locale );
570         }
571 
572         if ( form.isActiveCaptcha(  ) && PluginService.isPluginEnable( JCAPTCHA_PLUGIN ) )
573         {
574             CaptchaSecurityService captchaSecurityService = new CaptchaSecurityService(  );
575             model.put( MARK_JCAPTCHA, captchaSecurityService.getHtmlCode(  ) );
576         }
577 
578         model.put( MARK_FORM, form );
579         model.put( MARK_URL_ACTION, strUrlAction );
580         model.put( MARK_STR_ENTRY, strBuffer.toString(  ) );
581         model.put( MARK_LOCALE, locale );
582 
583         template = AppTemplateService.getTemplate( TEMPLATE_HTML_CODE_FORM, locale, model );
584 
585         return template.getHtml(  );
586     }
587 
588     /**
589      * insert in the string buffer the content of the html code of the entry
590      * @param nIdEntry the key of the entry which html code must be insert in the stringBuffer
591      * @param plugin the plugin
592      * @param stringBuffer the buffer which contains the html code
593      * @param locale the locale
594      */
595     public static void getHtmlEntry( int nIdEntry, Plugin plugin, StringBuffer stringBuffer, Locale locale )
596     {
597         HashMap model = new HashMap(  );
598         StringBuffer strConditionalQuestionStringBuffer = null;
599         HtmlTemplate template;
600         IEntry entry = EntryHome.findByPrimaryKey( nIdEntry, plugin );
601 
602         if ( entry.getEntryType(  ).getGroup(  ) )
603         {
604             StringBuffer strGroupStringBuffer = new StringBuffer(  );
605 
606             for ( IEntry entryChild : entry.getChildren(  ) )
607             {
608                 getHtmlEntry( entryChild.getIdEntry(  ), plugin, strGroupStringBuffer, locale );
609             }
610 
611             model.put( MARK_STR_LIST_CHILDREN, strGroupStringBuffer.toString(  ) );
612         }
613         else
614         {
615             if ( entry.getNumberConditionalQuestion(  ) != 0 )
616             {
617                 for ( Field field : entry.getFields(  ) )
618                 {
619                     field.setConditionalQuestions( FieldHome.findByPrimaryKey( field.getIdField(  ), plugin )
620                                                             .getConditionalQuestions(  ) );
621                 }
622             }
623         }
624 
625         if ( entry.getNumberConditionalQuestion(  ) != 0 )
626         {
627             strConditionalQuestionStringBuffer = new StringBuffer(  );
628 
629             for ( Field field : entry.getFields(  ) )
630             {
631                 if ( field.getConditionalQuestions(  ).size(  ) != 0 )
632                 {
633                     StringBuffer strGroupStringBuffer = new StringBuffer(  );
634 
635                     for ( IEntry entryConditional : field.getConditionalQuestions(  ) )
636                     {
637                         getHtmlEntry( entryConditional.getIdEntry(  ), plugin, strGroupStringBuffer, locale );
638                     }
639 
640                     model.put( MARK_STR_LIST_CHILDREN, strGroupStringBuffer.toString(  ) );
641                     model.put( MARK_FIELD, field );
642                     template = AppTemplateService.getTemplate( TEMPLATE_DIV_CONDITIONAL_ENTRY, locale, model );
643                     strConditionalQuestionStringBuffer.append( template.getHtml(  ) );
644                 }
645             }
646 
647             model.put( MARK_STR_LIST_CHILDREN, strConditionalQuestionStringBuffer.toString(  ) );
648         }
649 
650         model.put( MARK_ENTRY, entry );
651         template = AppTemplateService.getTemplate( entry.getHtmlCode(  ), locale, model );
652         stringBuffer.append( template.getHtml(  ) );
653     }
654 
655     /**
656      * perform in the object formSubmit the responses associates with a entry specify in parameter.
657      * return null if there is no error in the response else return a FormError Object
658      * @param request the request
659      * @param nIdEntry the key of the entry
660      * @param plugin the plugin
661      * @param formSubmit Form Submit Object
662      * @param bResponseNull true if the response create must be null
663      * @param locale the locale
664      * @return null if there is no error in the response else return a FormError Object
665      */
666     public static FormError getResponseEntry( HttpServletRequest request, int nIdEntry, Plugin plugin,
667         FormSubmit formSubmit, boolean bResponseNull, Locale locale )
668     {
669         FormError formError = null;
670         Response response = null;
671         IEntry entry = null;
672         List<Response> listResponse = new ArrayList<Response>(  );
673         entry = EntryHome.findByPrimaryKey( nIdEntry, plugin );
674 
675         List<Field> listField = new ArrayList<Field>(  );
676 
677         for ( Field field : entry.getFields(  ) )
678         {
679             field = FieldHome.findByPrimaryKey( field.getIdField(  ), plugin );
680             listField.add( field );
681         }
682 
683         entry.setFields( listField );
684 
685         if ( entry.getEntryType(  ).getGroup(  ) )
686         {
687             for ( IEntry entryChild : entry.getChildren(  ) )
688             {
689                 formError = getResponseEntry( request, entryChild.getIdEntry(  ), plugin, formSubmit, false, locale );
690 
691                 if ( formError != null )
692                 {
693                     return formError;
694                 }
695             }
696         }
697         else if ( !entry.getEntryType(  ).getComment(  ) )
698         {
699             if ( !bResponseNull )
700             {
701                 formError = entry.getResponseData( request, listResponse, locale );
702             }
703             else
704             {
705                 response = new Response(  );
706                 response.setEntry( entry );
707                 listResponse.add( response );
708             }
709 
710             if ( formError != null )
711             {
712                 return formError;
713             }
714 
715             formSubmit.getListResponse(  ).addAll( listResponse );
716 
717             if ( entry.getNumberConditionalQuestion(  ) != 0 )
718             {
719                 for ( Field field : entry.getFields(  ) )
720                 {
721                     if ( isFieldInTheResponseList( field.getIdField(  ), listResponse ) )
722                     {
723                         for ( IEntry conditionalEntry : field.getConditionalQuestions(  ) )
724                         {
725                             formError = getResponseEntry( request, conditionalEntry.getIdEntry(  ), plugin, formSubmit,
726                                     false, locale );
727 
728                             if ( formError != null )
729                             {
730                                 return formError;
731                             }
732                         }
733                     }
734                     else
735                     {
736                         for ( IEntry conditionalEntry : field.getConditionalQuestions(  ) )
737                         {
738                             getResponseEntry( request, conditionalEntry.getIdEntry(  ), plugin, formSubmit, true, locale );
739                         }
740                     }
741                 }
742             }
743         }
744 
745         return null;
746     }
747 
748     /**
749      * return the field which key is specified in parameter
750      * @param nIdField the id of the field who is search
751      * @param listField the list of field
752      * @return the field which key is specified in parameter
753      */
754     public static Field findFieldByIdInTheList( int nIdField, List<Field> listField )
755     {
756         for ( Field field : listField )
757         {
758             if ( field.getIdField(  ) == nIdField )
759             {
760                 return field;
761             }
762         }
763 
764         return null;
765     }
766 
767     /**
768      * return true if the field which key is specified in parameter is in the response list
769      * @param nIdField the id of the field who is search
770      * @param listResponse the list of object Response
771      * @return true if the field which key is specified in parameter is in the response list
772      */
773     public static Boolean isFieldInTheResponseList( int nIdField, List<Response> listResponse )
774     {
775         for ( Response response : listResponse )
776         {
777             if ( ( response.getField(  ) != null ) && ( response.getField(  ).getIdField(  ) == nIdField ) )
778             {
779                 return true;
780             }
781         }
782 
783         return false;
784     }
785 
786     /**
787      * return the xml of form's response
788      * @param request the request
789      * @param form the form
790      * @param listFormSubmit the form submit list
791      * @param locale the locale
792      * @param plugin the plugin
793      * @return the xml of the response of a form
794      */
795     public static String getXmlResponses( HttpServletRequest request, Form form, List<FormSubmit> listFormSubmit,
796         Locale locale, Plugin plugin )
797     {
798         StringBuffer buffer = new StringBuffer(  );
799         XmlUtil.beginElement( buffer, TAG_FORM );
800         XmlUtil.addElementHtml( buffer, TAG_FORM_TITLE, form.getTitle(  ) );
801         XmlUtil.beginElement( buffer, TAG_FORM_SUBMITS );
802 
803         //ResponseFilter filter=new ResponseFilter();
804         //filter.setIdForm(form.getIdForm());
805         //List<FormSubmit> listFormSubmit=FormSubmitHome.getFormSubmitList(filter, plugin);
806         for ( FormSubmit formSubmit : listFormSubmit )
807         {
808             XmlUtil.beginElement( buffer, TAG_FORM_SUBMIT );
809             XmlUtil.addElement( buffer, TAG_FORM_SUBMIT_ID, formSubmit.getIdFormSubmit(  ) );
810             XmlUtil.addElement( buffer, TAG_FORM_SUBMIT_DATE, getDateString( formSubmit.getDateResponse(  ), locale ) );
811 
812             if ( formSubmit.getIp(  ) != null )
813             {
814                 XmlUtil.addElement( buffer, TAG_FORM_SUBMIT_IP, formSubmit.getIp(  ) );
815             }
816             else
817             {
818                 XmlUtil.addElement( buffer, TAG_FORM_SUBMIT_IP, EMPTY_STRING );
819             }
820 
821             //filter.setIdForm(formSubmit.getIdFormSubmit());
822             //List<Response> listResponses=ResponseHome.getResponseList(filter, plugin);
823             Response responseStore = null;
824             XmlUtil.beginElement( buffer, TAG_QUESTIONS );
825 
826             if ( ( formSubmit.getListResponse(  ) != null ) && ( formSubmit.getListResponse(  ).size(  ) != 0 ) )
827             {
828                 for ( Response response : formSubmit.getListResponse(  ) )
829                 {
830                     if ( ( responseStore != null ) &&
831                             ( response.getEntry(  ).getIdEntry(  ) != responseStore.getEntry(  ).getIdEntry(  ) ) )
832                     {
833                         XmlUtil.endElement( buffer, TAG_RESPONSES );
834                         XmlUtil.endElement( buffer, TAG_QUESTION );
835                     }
836 
837                     if ( ( responseStore == null ) ||
838                             ( ( responseStore != null ) &&
839                             ( response.getEntry(  ).getIdEntry(  ) != responseStore.getEntry(  ).getIdEntry(  ) ) ) )
840                     {
841                         XmlUtil.beginElement( buffer, TAG_QUESTION );
842                         XmlUtil.addElementHtml( buffer, TAG_QUESTION_TITLE, response.getEntry(  ).getTitle(  ) );
843                         XmlUtil.beginElement( buffer, TAG_RESPONSES );
844                     }
845 
846                     if ( response.getValueResponse(  ) != null )
847                     {
848                         XmlUtil.addElementHtml( buffer, TAG_RESPONSE,
849                             response.getEntry(  ).getResponseValueForExport( request, response, locale ) );
850                     }
851                     else
852                     {
853                         XmlUtil.addElement( buffer, TAG_RESPONSE, EMPTY_STRING );
854                     }
855 
856                     responseStore = response;
857                 }
858 
859                 XmlUtil.endElement( buffer, TAG_RESPONSES );
860                 XmlUtil.endElement( buffer, TAG_QUESTION );
861             }
862 
863             XmlUtil.endElement( buffer, TAG_QUESTIONS );
864             XmlUtil.endElement( buffer, TAG_FORM_SUBMIT );
865         }
866 
867         XmlUtil.endElement( buffer, TAG_FORM_SUBMITS );
868         XmlUtil.endElement( buffer, TAG_FORM );
869 
870         return buffer.toString(  );
871     }
872 
873     /**
874      * write the http header in the response
875      * @param request the httpServletRequest
876      * @param response the http response
877      * @param strFileName the name of the file who must insert in the response
878      * @param strFileExtension the file extension
879      */
880     public static void addHeaderResponse( HttpServletRequest request, HttpServletResponse response, String strFileName,
881         String strFileExtension )
882     {
883         response.setHeader( "Content-Disposition", "attachment ;filename=\"" + strFileName + "\"" );
884 
885         if ( strFileExtension.equals( "csv" ) )
886         {
887             response.setContentType( "application/csv" );
888         }
889         else
890         {
891             String strMimeType = request.getSession(  ).getServletContext(  ).getMimeType( strFileName );
892 
893             if ( strMimeType != null )
894             {
895                 response.setContentType( strMimeType );
896             }
897             else
898             {
899                 response.setContentType( "application/octet-stream" );
900             }
901         }
902 
903         response.setHeader( "Pragma", "public" );
904         response.setHeader( "Expires", "0" );
905         response.setHeader( "Cache-Control", "must-revalidate,post-check=0,pre-check=0" );
906     }
907 
908     /**
909      * create a JFreeChart Graph function of the statistic form submit
910      * @param listStatistic the list of statistic of form submit
911      * @param strLabelX the label of axis x
912      * @param strLableY the label of axis x
913      * @param strTimesUnit the times unit of axis x(Day,Week,Month)
914      * @return a JFreeChart Graph function of the statistic form submit
915      */
916     public static JFreeChart createXYGraph( List<StatisticFormSubmit> listStatistic, String strLabelX,
917         String strLableY, String strTimesUnit )
918     {
919         XYDataset xyDataset = createDataset( listStatistic, strTimesUnit );
920         JFreeChart jfreechart = ChartFactory.createTimeSeriesChart( EMPTY_STRING, strLabelX, strLableY, xyDataset,
921                 false, false, false );
922         jfreechart.setBackgroundPaint( Color.white );
923 
924         XYPlot xyplot = jfreechart.getXYPlot(  );
925 
926         //xyplot.setBackgroundPaint(Color.gray);
927         //xyplot.setRangeGridlinesVisible(true);
928         xyplot.setBackgroundPaint( Color.white );
929         xyplot.setBackgroundPaint( Color.lightGray );
930         xyplot.setDomainGridlinePaint( Color.white );
931         xyplot.setRangeGridlinePaint( Color.white );
932 
933         //		DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis(  );
934         //		dateaxis.setLowerMargin(0);
935         //		DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy");
936         //		dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY,7,formatter));
937         //dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY,7));
938         //dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY,7));
939 
940         //dateaxis.setMinimumDate((Date)listStatistic.get(0).getTimesUnit());
941         //dateaxis.setMaximumDate((Date)listStatistic.get(listStatistic.size()-1).getTimesUnit());
942 
943         //dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,1));
944         //dateaxis.setTickUnit(new DateTickUnit(1, 1, DateFormat.getDateInstance(DateFormat.SHORT, Locale.FRENCH)));
945         //dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH, 1, new SimpleDateFormat("MM/YY")));
946         //dateaxis.setVerticalTickLabels( true );
947         XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyplot.getRenderer(  );
948         renderer.setBaseShapesVisible( true );
949         renderer.setSeriesFillPaint( 0, Color.RED );
950         renderer.setUseFillPaint( true );
951 
952         //		renderer.setToolTipGenerator( new StandardXYToolTipGenerator( "{0} {1} {2}",
953         //				DateFormat.getDateInstance( DateFormat.SHORT, Locale.FRENCH ), NumberFormat.getInstance(  ) ) );
954         //
955         //		ChartRenderingInfo info = new ChartRenderingInfo( new StandardEntityCollection(  ) );
956         return jfreechart;
957     }
958 
959     /**
960      * create graph dataset function of the statistic form submit
961      * @param listStatistic the list of statistic of form submit
962      * @param strTimesUnit the times unit of axis x(Day,Week,Month)
963      * @return create graph dataset function of the statistic form submit
964      */
965     private static XYDataset createDataset( List<StatisticFormSubmit> listStatistic, String strTimesUnit )
966     {
967         TimeSeries series = null;
968 
969         if ( strTimesUnit.equals( CONSTANT_GROUP_BY_DAY ) )
970         {
971             series = new TimeSeries( EMPTY_STRING, Day.class );
972 
973             for ( StatisticFormSubmit statistic : listStatistic )
974             {
975                 series.add( new Day( (Date) statistic.getStatisticDate(  ) ), statistic.getNumberResponse(  ) );
976             }
977         }
978         else if ( strTimesUnit.equals( CONSTANT_GROUP_BY_WEEK ) )
979         {
980             series = new TimeSeries( EMPTY_STRING, Week.class );
981 
982             for ( StatisticFormSubmit statistic : listStatistic )
983             {
984                 series.add( new Week( (Date) statistic.getStatisticDate(  ) ), statistic.getNumberResponse(  ) );
985             }
986         }
987 
988         else if ( strTimesUnit.equals( CONSTANT_GROUP_BY_MONTH ) )
989         {
990             series = new TimeSeries( EMPTY_STRING, Month.class );
991 
992             for ( StatisticFormSubmit statistic : listStatistic )
993             {
994                 series.add( new Month( (Date) statistic.getStatisticDate(  ) ), statistic.getNumberResponse(  ) );
995             }
996         }
997 
998         TimeSeriesCollection dataset = new TimeSeriesCollection(  );
999         dataset.addSeries( series );
1000 
1001         return dataset;
1002     }
1003 
1004     /**
1005      * Load the data of all  form that the user is authorized to see depends workgroups user
1006      * @param plugin the plugin
1007      * @param user the current user
1008      * @return  a  reference list of form
1009      */
1010     public static ReferenceList getFormList( Plugin plugin, AdminUser user )
1011     {
1012         List<Form> listForms = FormHome.getFormList( new FormFilter(  ), plugin );
1013         listForms = (List) AdminWorkgroupService.getAuthorizedCollection( listForms, user );
1014 
1015         ReferenceList refListForms = new ReferenceList(  );
1016 
1017         for ( Form form : listForms )
1018         {
1019             refListForms.addItem( form.getIdForm(  ), form.getTitle(  ) );
1020         }
1021 
1022         return refListForms;
1023     }
1024 
1025     public static ReferenceList getRefListAllQuestions( int nIdForm, Plugin plugin )
1026     {
1027         ReferenceList refListQuestions = new ReferenceList(  );
1028 
1029         for ( IEntry entry : getAllQuestionList( nIdForm, plugin ) )
1030         {
1031             if ( entry.getTitle(  ) != null )
1032             {
1033                 refListQuestions.addItem( entry.getIdEntry(  ), entry.getTitle(  ) );
1034             }
1035             else
1036             {
1037                 refListQuestions.addItem( entry.getIdEntry(  ), entry.getComment(  ) );
1038             }
1039         }
1040 
1041         return refListQuestions;
1042     }
1043 
1044     /**
1045      * return the questions list
1046      * @param nIdForm the form id
1047      * @param plugin the plugin
1048      * @return  the questions list
1049      */
1050     public static List<IEntry> getAllQuestionList( int nIdForm, Plugin plugin )
1051     {
1052         List<IEntry> listEntry = new ArrayList<IEntry>(  );
1053         EntryFilterm/business/EntryFilter.html#EntryFilter">EntryFilter filter = new EntryFilter(  );
1054         filter.setIdForm( nIdForm );
1055         filter.setEntryParentNull( EntryFilter.FILTER_TRUE );
1056         filter.setIdIsComment( EntryFilter.FILTER_FALSE );
1057         filter.setFieldDependNull( EntryFilter.FILTER_TRUE );
1058 
1059         for ( IEntry entryFirstLevel : EntryHome.getEntryList( filter, plugin ) )
1060         {
1061             if ( entryFirstLevel.getEntryType(  ).getGroup(  ) )
1062             {
1063                 filter = new EntryFilter(  );
1064                 filter.setIdForm( nIdForm );
1065                 filter.setIdEntryParent( entryFirstLevel.getIdEntry(  ) );
1066 
1067                 for ( IEntry entryChild : EntryHome.getEntryList( filter, plugin ) )
1068                 {
1069                     listEntry.add( entryChild );
1070                     addConditionnalsEntry( entryChild, listEntry, plugin );
1071                 }
1072             }
1073             else
1074             {
1075                 listEntry.add( entryFirstLevel );
1076                 addConditionnalsEntry( entryFirstLevel, listEntry, plugin );
1077             }
1078         }
1079 
1080         return listEntry;
1081     }
1082 
1083     /**
1084      * add children question of the root entryParent node
1085      * @param entryParent the parent entry
1086      * @param listEntry the entry list
1087      * @param plugin the plugin
1088      */
1089     private static void addConditionnalsEntry( IEntry entryParent, List<IEntry> listEntry, Plugin plugin )
1090     {
1091         entryParent = EntryHome.findByPrimaryKey( entryParent.getIdEntry(  ), plugin );
1092 
1093         for ( Field field : entryParent.getFields(  ) )
1094         {
1095             field = FieldHome.findByPrimaryKey( field.getIdField(  ), plugin );
1096 
1097             if ( field.getConditionalQuestions(  ) != null )
1098             {
1099                 for ( IEntry entryConditionnal : field.getConditionalQuestions(  ) )
1100                 {
1101                     listEntry.add( entryConditionnal );
1102                     addConditionnalsEntry( entryConditionnal, listEntry, plugin );
1103                 }
1104             }
1105         }
1106     }
1107 
1108     /**
1109      * return  all entries of form
1110      * @param nIdForm the form id
1111      * @param plugin the plugin
1112      * @return  the all entries of form
1113      */
1114     public static List<IEntry> getEntriesList( int nIdForm, Plugin plugin )
1115     {
1116         List<IEntry> listEntry = new ArrayList<IEntry>(  );
1117         EntryFilterm/business/EntryFilter.html#EntryFilter">EntryFilter filter = new EntryFilter(  );
1118         filter.setIdForm( nIdForm );
1119         filter.setEntryParentNull( EntryFilter.FILTER_TRUE );
1120         filter.setFieldDependNull( EntryFilter.FILTER_TRUE );
1121 
1122         for ( IEntry entryFirstLevel : EntryHome.getEntryList( filter, plugin ) )
1123         {
1124             if ( entryFirstLevel.getEntryType(  ).getGroup(  ) )
1125             {
1126                 filter = new EntryFilter(  );
1127                 filter.setIdForm( nIdForm );
1128                 filter.setIdEntryParent( entryFirstLevel.getIdEntry(  ) );
1129 
1130                 List<IEntry> listEntryChild = new ArrayList<IEntry>(  );
1131 
1132                 for ( IEntry entryChild : EntryHome.getEntryList( filter, plugin ) )
1133                 {
1134                     listEntryChild.add( entryChild );
1135                     addConditionnalsEntry( entryChild, listEntryChild, plugin );
1136                 }
1137 
1138                 entryFirstLevel.setChildren( listEntryChild );
1139                 listEntry.add( entryFirstLevel );
1140             }
1141             else
1142             {
1143                 listEntry.add( entryFirstLevel );
1144                 addConditionnalsEntry( entryFirstLevel, listEntry, plugin );
1145             }
1146         }
1147 
1148         return listEntry;
1149     }
1150 
1151     /**
1152      * Builds a query with filters placed in parameters
1153      * @param strSelect the select of the  query
1154      * @param listStrFilter the list of filter to add in the query
1155      * @param listStrGroupBy the list of group by to add in the query
1156      * @param strOrder the order by of the query
1157      * @return a query
1158      */
1159     public static String buildRequestWithFilter( String strSelect, List<String> listStrFilter,
1160         List<String> listStrGroupBy, String strOrder )
1161     {
1162         StringBuffer strBuffer = new StringBuffer(  );
1163         strBuffer.append( strSelect );
1164 
1165         int nCount = 0;
1166 
1167         for ( String strFilter : listStrFilter )
1168         {
1169             if ( ++nCount == 1 )
1170             {
1171                 strBuffer.append( CONSTANT_WHERE );
1172             }
1173 
1174             strBuffer.append( strFilter );
1175 
1176             if ( nCount != listStrFilter.size(  ) )
1177             {
1178                 strBuffer.append( CONSTANT_AND );
1179             }
1180         }
1181 
1182         if ( listStrGroupBy != null )
1183         {
1184             for ( String strGroupBy : listStrGroupBy )
1185             {
1186                 strBuffer.append( strGroupBy );
1187             }
1188         }
1189 
1190         if ( strOrder != null )
1191         {
1192             strBuffer.append( strOrder );
1193         }
1194 
1195         return strBuffer.toString(  );
1196     }
1197 }