KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > core > util > DateUtils


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: DateUtils.java,v 1.7 2007/01/07 06:14:00 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.core.util;
23
24 import java.sql.Timestamp JavaDoc;
25 import java.text.DateFormat JavaDoc;
26 import java.text.ParseException JavaDoc;
27 import java.text.SimpleDateFormat JavaDoc;
28 import java.util.Calendar JavaDoc;
29 import java.util.Date JavaDoc;
30 import java.util.GregorianCalendar JavaDoc;
31
32 import org.opensubsystems.core.error.OSSInvalidDataException;
33
34 /**
35  * Collection of useful utilities to work with dates.
36  *
37  * @version $Id: DateUtils.java,v 1.7 2007/01/07 06:14:00 bastafidli Exp $
38  * @author Miro Halas
39  * @code.reviewer Miro Halas
40  * @code.reviewed 1.5 2005/09/13 13:23:15 bastafidli
41  */

42 public final class DateUtils
43 {
44    // Constants ////////////////////////////////////////////////////////////////
45

46    /**
47     * One second in milliseconds.
48     */

49    public static final long ONE_SECOND = 1000L;
50    
51    /**
52     * One minute in milliseconds.
53     */

54    public static final long ONE_MINUTE = ONE_SECOND * 60L;
55    
56    /**
57     * One hour in milliseconds.
58     */

59    public static final long ONE_HOUR = ONE_MINUTE * 60L;
60    
61    /**
62     * One day in milliseconds.
63     */

64    public static final long ONE_DAY = ONE_HOUR * 24L;
65    
66    /**
67     * Separator we used to separate time from the nanosecond portion of the
68     * timestamp when converted to string.
69     */

70    public static final char NANO_SEPARATOR = ':';
71    
72    /**
73     * Constant for timing type
74     */

75    public static final int TIMING_NEVER = 0;
76
77    /**
78     * Constant for timing type
79     */

80    public static final int TIMING_MINUTES = 1;
81
82    /**
83     * Constant for timing type
84     */

85    public static final int TIMING_HOURS = 2;
86
87    /**
88     * Constant for timing type
89     */

90    public static final int TIMING_DAYS = 3;
91
92    /**
93     * Constant for timing type
94     */

95    public static final int TIMING_WEEKS = 4;
96
97    /**
98     * Constant for timing type
99     */

100    public static final int TIMING_MONTHS = 5;
101
102    /**
103     * Constant for timing type
104     */

105    public static final int TIMING_YEARS = 6;
106    
107    /**
108     * Constant for timing type
109     */

110    public static final int TIMING_NONE = 7;
111
112    /**
113     * Constant for current date code used in date/time formulas
114     */

115    public static final String JavaDoc CURRENT_DATE_CODE = "now";
116    
117    /**
118     * Constant for dynamic date code used in date/time formulas
119     */

120    public static final char YEAR_CODE = 'y';
121    
122    /**
123     * Constant for dynamic date code used in date/time formulas
124     */

125    public static final char MONTH_CODE = 'M';
126
127    /**
128     * Constant for dynamic date code used in date/time formulas
129     */

130    public static final char WEEK_CODE = 'w';
131
132    /**
133     * Constant for dynamic date code used in date/time formulas
134     */

135    public static final char DAY_CODE = 'd';
136
137    /**
138     * Constant for dynamic date code used in date/time formulas
139     */

140    public static final char HOUR_CODE = 'h';
141
142    /**
143     * Constant for dynamic date code used in date/time formulas
144     */

145    public static final char MINUTE_CODE = 'm';
146    
147    /**
148     * Constant for dynamic date code used in date/time formulas
149     */

150    public static final char SECOND_CODE = 's';
151
152    /**
153     * constant for date type DATE
154     */

155    public static final int DATE_TYPE_DATE = 1;
156
157    /**
158     * constant for date type TIME
159     */

160    public static final int DATE_TYPE_TIME = 2;
161
162    /**
163     * constant for date type DATETIME
164     */

165    public static final int DATE_TYPE_DATETIME = 3;
166    
167    // Constants for period start types /////////////////////////////////////////
168

169 // TODO: For Miro: Remove this code once all the code which referred to these
170
// constants was fixed
171
// /**
172
// * constant for period type
173
// */
174
// public static final int PERIOD_START_TYPE_NONE = 0;
175
//
176
// /**
177
// * constant for period type
178
// */
179
// public static final int PERIOD_START_TYPE_CREATION = 1;
180
//
181
// /**
182
// * constant for period type
183
// */
184
// public static final int PERIOD_START_TYPE_COMPLETION = 2;
185
//
186
// /**
187
// * constant for period type
188
// */
189
// public static final int PERIOD_START_TYPE_APPROVAL = 3;
190
//
191
// /**
192
// * constant for period type
193
// */
194
// public static final int PERIOD_START_TYPE_ACTIVATION = 4;
195
//
196
// /**
197
// * constant for period type
198
// */
199
// public static final int PERIOD_START_TYPE_INACTIVATION = 5;
200
//
201
// /**
202
// * constant for period type
203
// */
204
// public static final int PERIOD_START_TYPE_DYNAMIC = 6;
205
//
206
// /**
207
// * constant for period type code
208
// */
209
// public static final int PERIOD_TYPE_CODE = 99;
210
//
211
// /**
212
// * constant for period type object
213
// */
214
// public static final Integer PERIOD_TYPE_OBJ = new Integer(PERIOD_TYPE_CODE);
215

216    // Cached variables /////////////////////////////////////////////////////////
217

218    /**
219     * static SimpleDateFormat for date format to display on UI and in messages.
220     */

221    public static final SimpleDateFormat JavaDoc DATE_FORMAT
222                           = (SimpleDateFormat JavaDoc) DateFormat.getDateInstance(DateFormat.SHORT);
223    
224    /**
225     * static SimpleDateFormat for time format to display on UI and in messages.
226     */

227    public static final SimpleDateFormat JavaDoc TIME_FORMAT
228                           = (SimpleDateFormat JavaDoc) DateFormat.getTimeInstance(DateFormat.MEDIUM);
229    
230    /**
231     * static SimpleDateFormat for datetime format to display on UI and in messages.
232     */

233    public static final SimpleDateFormat JavaDoc DATETIME_FORMAT
234                           = (SimpleDateFormat JavaDoc) DateFormat.getDateTimeInstance(DateFormat.SHORT,
235                                                            DateFormat.MEDIUM);
236
237    /**
238     * static SimpleDateFormat for date format to store date as string so that
239     * it is stored consistently.
240     */

241    public static final SimpleDateFormat JavaDoc DATE_STORE_FORMAT
242                           = new SimpleDateFormat JavaDoc("MM/dd/yyyy");
243    
244    /**
245     * static SimpleDateFormat for time format to store time as string so that
246     * it is stored consistently.
247     */

248    public static final SimpleDateFormat JavaDoc TIME_STORE_FORMAT
249                           = new SimpleDateFormat JavaDoc("HH:mm:ss");
250    
251    /**
252     * static SimpleDateFormat for datetime format to store date and time as
253     * string so that it is stored consistently.
254     */

255    public static final SimpleDateFormat JavaDoc DATETIME_STORE_FORMAT
256                           = new SimpleDateFormat JavaDoc("MM/dd/yyyy HH:mm:ss");
257
258
259    /**
260     * static SimpleDateFormat for date format for sql date
261     */

262    public static final SimpleDateFormat JavaDoc DATE_SQL_FORMAT
263                           = new SimpleDateFormat JavaDoc("yyyy-MM-dd 00:00:00");
264    
265    /**
266     * static SimpleDateFormat for time format for sql time
267     */

268    public static final SimpleDateFormat JavaDoc TIME_SQL_FORMAT
269                           = new SimpleDateFormat JavaDoc("1970-01-01 HH:mm:ss");
270    
271    /**
272     * static SimpleDateFormat for datetime format for sql date and time
273     */

274    public static final SimpleDateFormat JavaDoc DATETIME_SQL_FORMAT
275                           = new SimpleDateFormat JavaDoc("yyyy-MM-dd HH:mm:ss");
276
277    // Constructors /////////////////////////////////////////////////////////////
278

279    /**
280     * Private constructor since this class cannot be instantiated
281     */

282    private DateUtils(
283    )
284    {
285       // Do nothing
286
}
287    
288    // Public methods ///////////////////////////////////////////////////////////
289

290    /**
291     * Check if two dates equals regardless of the time. Two null dates are equal.
292     * Null and not null dates are not equal.
293     *
294     * @param dtFirst - first date to compare, can be null
295     * @param dtSecond - second date to compare, can be null
296     * @return boolean - true if two dates equals regardless of what the time is
297     */

298    public static boolean dateEquals(
299       Date JavaDoc dtFirst,
300       Date JavaDoc dtSecond
301    )
302    {
303       boolean bReturn = false;
304       
305       // If they are the same object, they are equals
306
bReturn = (dtFirst == dtSecond);
307       if (!bReturn)
308       {
309          if (dtFirst == null)
310          {
311             // Two null dates are the same
312
bReturn = (dtSecond == null);
313          }
314          else
315          {
316             if (dtSecond != null)
317             {
318                Calendar JavaDoc compCalendar;
319                int iEra;
320                int iYear;
321                int iMonth;
322                int iDay;
323                
324                compCalendar = Calendar.getInstance();
325                compCalendar.setTime(dtFirst);
326                iEra = compCalendar.get(Calendar.ERA);
327                iYear = compCalendar.get(Calendar.YEAR);
328                iMonth = compCalendar.get(Calendar.MONTH);
329                iDay = compCalendar.get(Calendar.DATE);
330                compCalendar.setTime(dtSecond);
331          
332                bReturn = ((iEra == compCalendar.get(Calendar.ERA))
333                          && (iYear == compCalendar.get(Calendar.YEAR))
334                          && (iMonth == compCalendar.get(Calendar.MONTH))
335                          && (iDay == compCalendar.get(Calendar.DATE)));
336             }
337          }
338       }
339             
340       return bReturn;
341    }
342    
343    /**
344     * Check if two times equals regardless of the date. Two null times are equal.
345     * Null and not null times are not equal.
346     *
347     * @param dtFirst - first time to compare, can be null
348     * @param dtSecond - second time to compare, can be null
349     * @param bIgnoreMilliseconds - if true milliseconds will be ignored in comparison
350     * @return boolean - true if two time equals regardless of what the date is
351     */

352    public static boolean timeEquals(
353       Date JavaDoc dtFirst,
354       Date JavaDoc dtSecond,
355       boolean bIgnoreMilliseconds
356    )
357    {
358       boolean bReturn = false;
359       
360       // If they are the same object, they are equals
361
bReturn = (dtFirst == dtSecond);
362       if (!bReturn)
363       {
364          if (dtFirst == null)
365          {
366             // Two null dates are the same
367
bReturn = (dtSecond == null);
368          }
369          else
370          {
371             if (dtSecond != null)
372             {
373                Calendar JavaDoc compCalendar;
374                int iHour;
375                int iMinute;
376                int iSecond;
377                int iMili;
378                
379                compCalendar = Calendar.getInstance();
380                compCalendar.setTime(dtFirst);
381                iHour = compCalendar.get(Calendar.HOUR_OF_DAY);
382                iMinute = compCalendar.get(Calendar.MINUTE);
383                iSecond = compCalendar.get(Calendar.SECOND);
384                iMili = compCalendar.get(Calendar.MILLISECOND);
385                compCalendar.setTime(dtSecond);
386          
387                bReturn = ((iHour == compCalendar.get(Calendar.HOUR_OF_DAY))
388                          && (iMinute == compCalendar.get(Calendar.MINUTE))
389                          && (iSecond == compCalendar.get(Calendar.SECOND))
390                          && ((bIgnoreMilliseconds)
391                             || (iMili == compCalendar.get(Calendar.MILLISECOND))));
392             }
393          }
394       }
395             
396       return bReturn;
397    }
398
399    /**
400     * Check if two dates and times are equal. Two null dates are equal. Null
401     * and not null dates are not equal.
402     *
403     * @param dtFirst - first date time to compare, can be null
404     * @param dtSecond - second date time to compare, can be null
405     * @return boolean - true if two date and times are equal
406     */

407    public static boolean dateAndTimeEquals(
408       Date JavaDoc dtFirst,
409       Date JavaDoc dtSecond
410    )
411    {
412       boolean bReturn = false;
413       
414       // If they are the same object, they are equals
415
bReturn = (dtFirst == dtSecond);
416       if (!bReturn)
417       {
418          if (dtFirst == null)
419          {
420             // Two null dates are the same
421
bReturn = (dtSecond == null);
422          }
423          else
424          {
425             if (dtSecond != null)
426             {
427                // They are both not null so they have to match to millisecond
428
// (actually to nanosecond since the getTime takes nanoseconds
429
// into account)
430
bReturn = (dtFirst.getTime() == dtSecond.getTime());
431             }
432          }
433       }
434             
435       return bReturn;
436    }
437
438    /**
439     * Check if String representing date is function or date. Date is a function
440     * (formula) if it starts with the current date/time variable which can be
441     * followed by expression describing period from current date.
442     *
443     * @param strValue - string representation of date or date function
444     * @return boolean - date function flag
445     */

446    public static boolean isFunction(
447       String JavaDoc strValue
448    )
449    {
450       boolean bReturn = false;
451
452       if ((strValue != null) && (strValue.length() > 0)
453          && (strValue.trim().startsWith(CURRENT_DATE_CODE)))
454       {
455          bReturn = true;
456       }
457       
458       return bReturn;
459    }
460    
461    /**
462     * Parse date time value from given string resolving any functions or formulas
463     * the string can contain. This method can be therefore used if the passed
464     * string contains string representation date, time or timestamp or a formula
465     * such as now + 3h - 1m + 4d.
466     *
467     * @param strValue - string representation of date or date function
468     * @param iDateType - date type code, one of the DATE_TYPE_XXX constants
469     * @param stored - flag if Date should be parsed using format used for
470     * storage or for display
471     * @return Timestamp - parsed date or null if date was null
472     * @throws OSSInvalidDataException - error during parsing
473     */

474    public static Timestamp JavaDoc parseDateTime(
475       String JavaDoc strValue,
476       int iDateType,
477       boolean stored
478    ) throws OSSInvalidDataException
479    {
480       Timestamp JavaDoc tsReturn = null;
481       Calendar JavaDoc workCal = GregorianCalendar.getInstance();
482       
483       if (strValue != null && strValue.length() > 0)
484       {
485          strValue = strValue.trim();
486          if (strValue.startsWith(CURRENT_DATE_CODE))
487          {
488             strValue = strValue.replaceAll("[ ]", "");
489
490             // If the user specified "UseCurrent", then substitute the
491
// current date/time in the value
492
workCal.setTime(new Date JavaDoc());
493
494 // Log.getInstance().debug("Parsing current date " + strValue);
495

496             // Parse the date math
497
int iBeginIndex = CURRENT_DATE_CODE.length();
498             int iMaxLength = strValue.length();
499             int iSign = 1;
500             int iNumberIndex;
501             int iValue;
502             char cChar = ' ';
503
504             while (iBeginIndex < iMaxLength)
505             {
506                // This has to be sign
507
if (strValue.charAt(iBeginIndex) == '+')
508                {
509                   iSign = 1;
510                }
511                else if (strValue.charAt(iBeginIndex) == '-')
512                {
513                   iSign = -1;
514                }
515                else
516                {
517                   // Incorrect String
518
throw new OSSInvalidDataException(
519                            "Date function is in incorrect format: "
520                            + strValue + " at " + strValue.substring(iBeginIndex));
521                }
522                iBeginIndex++;
523
524                // Now we have to have number
525
iNumberIndex = iBeginIndex;
526                
527                while (((iBeginIndex == iNumberIndex) || Character.isDigit(cChar))
528                      && (iBeginIndex < iMaxLength))
529                {
530                   cChar = strValue.charAt(iBeginIndex++);
531                }
532
533                // We have to go one back because we should stop on modifier (e.g 1m)
534
iBeginIndex--;
535
536                try
537                {
538                   iValue = Integer.parseInt(strValue.substring(iNumberIndex, iBeginIndex));
539                }
540                catch (NumberFormatException JavaDoc nmeExc)
541                {
542                   // Incorrect String
543
throw new OSSInvalidDataException(
544                            "Date function is in incorrect format: "
545                            + strValue + " at " + strValue.substring(iNumberIndex));
546                }
547
548                // This has to be modifier: y - year, M - month, w - week,
549
// d - day, h - hour, m - minute, s - second
550
cChar = strValue.charAt(iBeginIndex);
551                switch(cChar)
552                {
553                   case(YEAR_CODE):
554                   {
555                      if (iDateType == DATE_TYPE_TIME)
556                      {
557                         throw new OSSInvalidDataException(
558                            "Date function is in incorrect format: " +
559                            "used YEAR modifier for TIME type");
560                      }
561                      workCal.add(Calendar.YEAR, iSign * iValue);
562                      break;
563                   }
564                   case(MONTH_CODE):
565                   {
566                      if (iDateType == DATE_TYPE_TIME)
567                      {
568                         throw new OSSInvalidDataException(
569                            "Date function is in incorrect format: " +
570                            "used MONTH modifier for TIME type");
571                      }
572                      workCal.add(Calendar.MONTH, iSign * iValue);
573                      break;
574                   }
575                   case(WEEK_CODE):
576                   {
577                      if (iDateType == DATE_TYPE_TIME)
578                      {
579                         throw new OSSInvalidDataException(
580                            "Date function is in incorrect format: " +
581                            "used WEEK modifier for TIME type");
582                      }
583                      workCal.add(Calendar.WEEK_OF_YEAR, iSign * iValue);
584                      break;
585                   }
586                   case(DAY_CODE):
587                   {
588                      if (iDateType == DATE_TYPE_TIME)
589                      {
590                         throw new OSSInvalidDataException(
591                            "Date function is in incorrect format: " +
592                            "used DAY modifier for TIME type");
593                      }
594                      workCal.add(Calendar.DATE, iSign * iValue);
595                      break;
596                   }
597                   case(HOUR_CODE):
598                   {
599                      if (iDateType == DATE_TYPE_DATE)
600                      {
601                         throw new OSSInvalidDataException(
602                            "Date function is in incorrect format: " +
603                            "used HOUR modifier for DATE type");
604                      }
605                      workCal.add(Calendar.HOUR, iSign * iValue);
606                      break;
607                   }
608                   case(MINUTE_CODE):
609                   {
610                      if (iDateType == DATE_TYPE_DATE)
611                      {
612                         throw new OSSInvalidDataException(
613                            "Date function is in incorrect format: " +
614                            "used MINUTE modifier for DATE type");
615                      }
616                      workCal.add(Calendar.MINUTE, iSign * iValue);
617                      break;
618                   }
619                   case(SECOND_CODE):
620                   {
621                      if (iDateType == DATE_TYPE_DATE)
622                      {
623                         throw new OSSInvalidDataException(
624                            "Date function is in incorrect format: " +
625                            "used SECOND modifier for DATE type");
626                      }
627                      workCal.add(Calendar.SECOND, iSign * iValue);
628                      break;
629                   }
630                   default:
631                   {
632                      // Incorrect String
633
throw new OSSInvalidDataException(
634                            "Date function is in incorrect format: "
635                            + strValue + " at " + strValue.substring(iBeginIndex));
636                   }
637                }
638
639                iBeginIndex++;
640             }
641             
642             tsReturn = new Timestamp JavaDoc(workCal.getTimeInMillis());
643             
644          }
645          else
646          {
647             try
648             {
649                if (stored)
650                {
651                   switch (iDateType)
652                   {
653                      case (DATE_TYPE_DATE) :
654                      {
655                         tsReturn = new Timestamp JavaDoc(DATE_STORE_FORMAT.parse(strValue).getTime());
656                         break;
657                      }
658                      case (DATE_TYPE_TIME) :
659                      {
660                         tsReturn = new Timestamp JavaDoc(TIME_STORE_FORMAT.parse(strValue).getTime());
661                         break;
662                      }
663                      case (DATE_TYPE_DATETIME) :
664                      {
665                         tsReturn = new Timestamp JavaDoc(DATETIME_STORE_FORMAT.parse(strValue).getTime());
666                         break;
667                      }
668                      default:
669                      {
670                         assert false : "Unknown date type " + iDateType;
671                      }
672                   }
673                }
674                else
675                {
676                   switch (iDateType)
677                   {
678                      case (DATE_TYPE_DATE) :
679                      {
680                         tsReturn = new Timestamp JavaDoc(DATE_FORMAT.parse(strValue).getTime());
681                         break;
682                      }
683                      case (DATE_TYPE_TIME) :
684                      {
685                         tsReturn = new Timestamp JavaDoc(TIME_FORMAT.parse(strValue).getTime());
686                         break;
687                      }
688                      case (DATE_TYPE_DATETIME) :
689                      {
690                         tsReturn = new Timestamp JavaDoc(DATETIME_FORMAT.parse(strValue).getTime());
691                         break;
692                      }
693                      default:
694                      {
695                         assert false : "Unknown date type " + iDateType;
696                      }
697                   }
698                }
699             }
700             catch (ParseException JavaDoc peExc)
701             {
702                throw new OSSInvalidDataException(
703                      "Date is in incorrect format. Problems with parsing.",
704                      peExc);
705             }
706          }
707       }
708
709       return tsReturn;
710    }
711    
712    /**
713     * Parse the specified period into string displaying number of days the
714     * period represents.
715     *
716     * @param lPeriod - period in miliseconds
717     * @return String - period in format 'x day(s)' or '' if not valid period
718     */

719    public static String JavaDoc parseDayPeriod(
720       long lPeriod
721    )
722    {
723       StringBuffer JavaDoc sbReturn = new StringBuffer JavaDoc();
724       long lDays = 0L;
725       
726       if (lPeriod > 0)
727       {
728          // we will count each started day as counted day
729
lPeriod = lPeriod + DateUtils.ONE_DAY - 1;
730          
731          lDays = lPeriod / DateUtils.ONE_DAY;
732          sbReturn.append(lDays);
733          if (lDays == 1L)
734          {
735             sbReturn.append(" day");
736          }
737          else
738          {
739             sbReturn.append(" days");
740          }
741       }
742       else
743       {
744          sbReturn.append("0 days");
745       }
746
747       return sbReturn.toString();
748    }
749    
750    /**
751     * Parse the specified period into string displaying date and time the
752     * period represents.
753     *
754     * @param lPeriod - preiod in miliseconds
755     * @return String - period in format 'x day(s) y hour(s) z minute(s)'
756     * or '' if not valid period
757     */

758    public static String JavaDoc parseDayTimePeriod(
759       long lPeriod
760    )
761    {
762       StringBuffer JavaDoc sbReturn = new StringBuffer JavaDoc();
763       long lHelp = 0L;
764       
765       
766       if (lPeriod > 0)
767       {
768          lPeriod = lPeriod + DateUtils.ONE_MINUTE - 1;
769          // we will count each started day as counted day
770
lHelp = lPeriod / DateUtils.ONE_DAY;
771          if (lHelp > 0)
772          {
773             sbReturn.append(lHelp);
774             if (lHelp == 1L)
775             {
776                sbReturn.append(" d ");
777             }
778             else
779             {
780                sbReturn.append(" d ");
781             }
782          }
783          lPeriod = lPeriod % DateUtils.ONE_DAY;
784          lHelp = lPeriod / DateUtils.ONE_HOUR;
785          if (lHelp > 0 || sbReturn.length() > 0)
786          {
787             sbReturn.append(lHelp);
788             if (lHelp == 1L)
789             {
790                sbReturn.append(" h ");
791             }
792             else
793             {
794                sbReturn.append(" h ");
795             }
796          }
797          lPeriod = lPeriod % DateUtils.ONE_HOUR;
798          lHelp = lPeriod / DateUtils.ONE_MINUTE;
799          if (lHelp > 0 || sbReturn.length() > 0)
800          {
801             sbReturn.append(lHelp);
802             if (lHelp == 1L)
803             {
804                sbReturn.append(" min");
805             }
806             else
807             {
808                sbReturn.append(" min");
809             }
810          }
811       }
812       else
813       {
814          sbReturn.append("0 min");
815       }
816       return sbReturn.toString();
817    }
818    
819 // TODO: For Miro: Remove this code once all the code which referred to these
820
// was fixed. These should be moved to a GUI related class.
821
// /**
822
// * Method for list of timing types.
823
// *
824
// * @return List - list of timing types
825
// */
826
// public static List getTimingTypes(
827
// )
828
// {
829
// List lstTimingTypes = new ArrayList();
830
//
831
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_MINUTES),
832
// "Minute(s)"));
833
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_HOURS), "Hour(s)"));
834
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_DAYS), "Day(s)"));
835
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_WEEKS), "Week(s)"));
836
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_MONTHS), "Month(s)"));
837
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_YEARS), "Year(s)"));
838
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_NEVER), "Never"));
839
//
840
// return lstTimingTypes;
841
// }
842

843 // /**
844
// * Method for list of timing types with None option.
845
// *
846
// * @return List - list of timing types
847
// */
848
// public static List getTimingTypesWithNone(
849
// )
850
// {
851
// List lstTimingTypes = new ArrayList();
852
//
853
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_NONE), "None"));
854
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_MINUTES),
855
// "Minute(s)"));
856
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_HOURS), "Hour(s)"));
857
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_DAYS), "Day(s)"));
858
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_WEEKS), "Week(s)"));
859
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_MONTHS), "Month(s)"));
860
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_YEARS), "Year(s)"));
861
// lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_NEVER), "Never"));
862
//
863
// return lstTimingTypes;
864
// }
865

866 // /**
867
// * Method for getting string name of the timing type.
868
// *
869
// * @param iTimingType - timing type constant
870
// * @return String - string name of timing type
871
// */
872
// public static String getTimingTypeName(
873
// int iTimingType
874
// )
875
// {
876
// String outTimingTypeName = "Never";
877
// switch (iTimingType)
878
// {
879
// case (DateUtils.TIMING_NEVER):
880
// {
881
// outTimingTypeName = "Never";
882
// break;
883
// }
884
// case (DateUtils.TIMING_MINUTES):
885
// {
886
// outTimingTypeName = "Minute(s)";
887
// break;
888
// }
889
// case (DateUtils.TIMING_HOURS):
890
// {
891
// outTimingTypeName = "Hour(s)";
892
// break;
893
// }
894
// case (DateUtils.TIMING_DAYS):
895
// {
896
// outTimingTypeName = "Day(s)";
897
// break;
898
// }
899
// case (DateUtils.TIMING_WEEKS):
900
// {
901
// outTimingTypeName = "Week(s)";
902
// break;
903
// }
904
// case (DateUtils.TIMING_MONTHS):
905
// {
906
// outTimingTypeName = "Month(s)";
907
// break;
908
// }
909
// case (DateUtils.TIMING_YEARS):
910
// {
911
// outTimingTypeName = "Year(s)";
912
// break;
913
// }
914
// case (DateUtils.TIMING_NONE):
915
// {
916
// outTimingTypeName = "None";
917
// break;
918
// }
919
// }
920
//
921
// return outTimingTypeName;
922
// }
923

924    /**
925     * Get expiration timestamp from start date, period type and duration. For
926     * example if the start date is now, period type is hour and duration is 2
927     * then the result will be timestamp representing now + 2 hours.
928     *
929     * @param tsStartDate - start date of period counting
930     * @param iPeriodType - one of the period type constant TIMING_XXX
931     * @param iPeriodDuration - period duration, number of time units specified
932     * by period type
933     * @return Timestamp - date of period expiration or null if any problem
934     */

935    public static Timestamp JavaDoc getPeriodExpiration(
936       Timestamp JavaDoc tsStartDate,
937       int iPeriodType,
938       int iPeriodDuration
939    )
940    {
941       Timestamp JavaDoc tsReturn = null;
942       Calendar JavaDoc calHelp;
943       if (tsStartDate != null && iPeriodDuration > 0
944             && iPeriodType > TIMING_NEVER && iPeriodType < TIMING_NONE)
945       {
946          calHelp = Calendar.getInstance();
947          calHelp.setTime(tsStartDate);
948          
949          switch (iPeriodType)
950          {
951             case (TIMING_MINUTES) :
952             {
953                calHelp.add(Calendar.MINUTE, iPeriodDuration);
954                break;
955             }
956             case (TIMING_HOURS) :
957             {
958                calHelp.add(Calendar.HOUR, iPeriodDuration);
959                break;
960             }
961             case (TIMING_DAYS) :
962             {
963                calHelp.add(Calendar.DATE, iPeriodDuration);
964                break;
965             }
966             case (TIMING_WEEKS) :
967             {
968                calHelp.add(Calendar.WEEK_OF_YEAR, iPeriodDuration);
969                break;
970             }
971             case (TIMING_MONTHS) :
972             {
973                calHelp.add(Calendar.MONTH, iPeriodDuration);
974                break;
975             }
976             case (TIMING_YEARS) :
977             {
978                calHelp.add(Calendar.YEAR, iPeriodDuration);
979                break;
980             }
981             default :
982             {
983                assert false : "Not supported Timing type " + iPeriodType;
984             }
985          }
986          tsReturn = new Timestamp JavaDoc(calHelp.getTimeInMillis());
987       }
988       
989       return tsReturn;
990    }
991    
992    /**
993     * Method to compare time periods
994     *
995     * @param iPeriodType1 - first period type, one of the period type constant
996     * TIMING_XXX
997     * @param iPeriodDuration1 - first period duration
998     * @param iPeriodType2 - second period type, one of the period type constant
999     * TIMING_XXX
1000    * @param iPeriodDuration2 - second period duration
1001    * @return int - 1 - first period is longer
1002    * 0 - periods are same
1003    * -1 - first period is shorter
1004    */

1005   public static int comparePeriods(
1006      int iPeriodType1,
1007      int iPeriodDuration1,
1008      int iPeriodType2,
1009      int iPeriodDuration2
1010   )
1011   {
1012      int iReturn = 0;
1013      
1014      if ((iPeriodType1 != TIMING_NEVER) && (iPeriodType1 != TIMING_NONE)
1015         && (iPeriodType2 != TIMING_NEVER) && (iPeriodType2 != TIMING_NONE))
1016      {
1017         Timestamp JavaDoc tsTimestamp1 = getPeriodExpiration(
1018               new Timestamp JavaDoc(0), iPeriodType1, iPeriodDuration1);
1019         Timestamp JavaDoc tsTimestamp2 = getPeriodExpiration(
1020               new Timestamp JavaDoc(0), iPeriodType2, iPeriodDuration2);
1021         
1022         // TODO: Improve: When would any of these be null?
1023
if ((tsTimestamp1 != null) && (tsTimestamp2 != null))
1024         {
1025            if (tsTimestamp1.after(tsTimestamp2))
1026            {
1027               iReturn = 1;
1028            }
1029            else if (tsTimestamp2.after(tsTimestamp1))
1030            {
1031               iReturn = -1;
1032            }
1033         }
1034      }
1035      else
1036      {
1037         if (iPeriodType1 != iPeriodType2)
1038         {
1039            if (iPeriodType1 == TIMING_NEVER)
1040            {
1041               iReturn = 1;
1042            }
1043            else if (iPeriodType1 == TIMING_NONE)
1044            {
1045               iReturn = -1;
1046            }
1047            else if (iPeriodType2 == TIMING_NEVER)
1048            {
1049               iReturn = -1;
1050            }
1051            else if (iPeriodType2 == TIMING_NONE)
1052            {
1053               iReturn = 1;
1054            }
1055         }
1056      }
1057
1058      return iReturn;
1059   }
1060   
1061   /**
1062    * Convert timestamp to string including it's nanosecond portion so that it
1063    * can be safely stored in variable of web page.
1064    *
1065    * @param tsTimestamp - timestamp to convert
1066    * @return String - text containing time and nanosecond portion of timestamp
1067    */

1068   public static String JavaDoc getTimestampAsString(
1069      Timestamp JavaDoc tsTimestamp
1070   )
1071   {
1072      StringBuffer JavaDoc sbTimestamp = new StringBuffer JavaDoc();
1073      
1074      sbTimestamp.append(tsTimestamp.getTime());
1075      sbTimestamp.append(NANO_SEPARATOR);
1076      sbTimestamp.append(tsTimestamp.getNanos());
1077      
1078      return sbTimestamp.toString();
1079   }
1080   
1081   /**
1082    * Convert string to timestamp including if available it's nanosecond portion
1083    * so that it can be safely restored from variable in web page.
1084    *
1085    * @param strTimestamp - timestamp to convert
1086    * @return Timestamp - restored timestamp
1087    * @throws NumberFormatException - problem parsing the string
1088    */

1089   public static Timestamp JavaDoc parseTimestamp(
1090      String JavaDoc strTimestamp
1091   ) throws NumberFormatException JavaDoc
1092   {
1093      long lTime;
1094      int iNanos;
1095
1096      if ("0".equals(strTimestamp))
1097      {
1098         lTime = 0L;
1099         iNanos = 0;
1100      }
1101      else
1102      {
1103         int iIndex;
1104         
1105         iIndex = strTimestamp.indexOf(NANO_SEPARATOR);
1106         if (iIndex == -1)
1107         {
1108            throw new NumberFormatException JavaDoc(
1109                         "The timestamp string doesn't contain nanosecond separator: "
1110                         + strTimestamp);
1111         }
1112         
1113         lTime = Long.parseLong(strTimestamp.substring(0, iIndex));
1114         iNanos = Integer.parseInt(strTimestamp.substring(iIndex + 1));
1115      }
1116      
1117      return new TimestampCopy(lTime, iNanos);
1118   }
1119
1120   /**
1121    * Function returns time string in the form MM:SS.MS from the input specified in miliseconds.
1122    *
1123    * @param lTimeInMiliseconds - time in miliseconds
1124    * @return String - string representation of miliseconds in the form MM:SS.MS
1125    */

1126   public static String JavaDoc getStringTime(
1127      long lTimeInMiliseconds
1128   )
1129   {
1130      long lTotalMS = lTimeInMiliseconds;
1131      long lMS = lTotalMS % 1000;
1132      long lTotalSecs = lTotalMS / 1000;
1133      long lSecs = lTotalSecs % 60;
1134      long lTotalMins = lTotalSecs / 60;
1135      long lMinutes = lTotalMins % 60;
1136      long lHours = lTotalMins / 60;
1137      StringBuffer JavaDoc sbBuffer = new StringBuffer JavaDoc();
1138
1139      if (lHours > 0)
1140      {
1141         sbBuffer.append(lHours);
1142         sbBuffer.append(":");
1143         sbBuffer.append(lMinutes);
1144         sbBuffer.append(":");
1145         sbBuffer.append(lSecs);
1146         sbBuffer.append(".");
1147         sbBuffer.append(lMS);
1148      }
1149      else if (lMinutes > 0)
1150      {
1151         sbBuffer.append(lMinutes);
1152         sbBuffer.append(":");
1153         sbBuffer.append(lSecs);
1154         sbBuffer.append(".");
1155         sbBuffer.append(lMS);
1156      }
1157      else if (lSecs > 0)
1158      {
1159         sbBuffer.append(lSecs);
1160         sbBuffer.append(".");
1161         sbBuffer.append(lMS);
1162         sbBuffer.append(" seconds");
1163      }
1164      else
1165      {
1166         sbBuffer.append(lMS);
1167         sbBuffer.append(" ms");
1168      }
1169      
1170      return sbBuffer.toString();
1171   }
1172
1173// TODO: For Miro: Remove this code once all the code which referred to these
1174
// was fixed. These should be moved to a GUI or business logic related class.
1175
// /**
1176
// * Method to check if valid period settings
1177
// *
1178
// * @param iPeriod - period length
1179
// * @param iPeriodType - period type
1180
// * @param iPeriodStartType - period start type
1181
// * @param iAttributeId - attribute ID for dynamic period start type
1182
// * @param bPeriodException - period exception flag
1183
// * @param strPeriodName - period name used for exception message
1184
// * @param bAdvancePeriodType - flag if advanced period type (includes also start type)
1185
// * @param bfideException - invalid data exception
1186
// */
1187
// public static void validatePeriod(
1188
// int iPeriod,
1189
// int iPeriodType,
1190
// int iPeriodStartType,
1191
// int iAttributeId,
1192
// boolean bPeriodException,
1193
// String strPeriodName,
1194
// boolean bAdvancePeriodType,
1195
// OSSInvalidDataException messageException
1196
// )
1197
// {
1198
// if ((iPeriod > 0)
1199
// || ((iPeriodType != TIMING_NONE) && (iPeriodType != TIMING_NEVER))
1200
// || (bPeriodException) || (iPeriodStartType != PERIOD_START_TYPE_NONE))
1201
// {
1202
// if (iPeriod <= 0)
1203
// {
1204
// if (messageException == null)
1205
// {
1206
// messageException = new OSSInvalidDataException();
1207
// }
1208
// messageException.getErrorMessages().addMessage(
1209
// PERIOD_TYPE_OBJ,
1210
// "You have to set valid period length for " + strPeriodName + " type."
1211
// );
1212
// }
1213
// else if ((iPeriodType == TIMING_NONE) || (iPeriodType == TIMING_NEVER))
1214
// {
1215
// if (messageException == null)
1216
// {
1217
// messageException = new OSSInvalidDataException();
1218
// }
1219
// messageException.getErrorMessages().addMessage(
1220
// PERIOD_TYPE_OBJ,
1221
// "You have to set valid period type for " + strPeriodName + " type."
1222
// );
1223
// }
1224
// else if ((bAdvancePeriodType) && (iPeriodStartType == PERIOD_START_TYPE_NONE))
1225
// {
1226
// if (messageException == null)
1227
// {
1228
// messageException = new OSSInvalidDataException();
1229
// }
1230
// messageException.getErrorMessages().addMessage(
1231
// PERIOD_TYPE_OBJ,
1232
// "You have to set valid period start type for " + strPeriodName + " type."
1233
// );
1234
// }
1235
// else if ((bAdvancePeriodType)
1236
// && (iPeriodStartType == PERIOD_START_TYPE_DYNAMIC)
1237
// && (iAttributeId == DataObject.NEW_ID))
1238
// {
1239
// if (messageException == null)
1240
// {
1241
// messageException = new OSSInvalidDataException();
1242
// }
1243
// messageException.getErrorMessages().addMessage(
1244
// PERIOD_TYPE_OBJ,
1245
// "You have to set valid period dynamic start attribute for "
1246
// + strPeriodName + " type."
1247
// );
1248
// }
1249
// }
1250
// }
1251
}
1252
Popular Tags