1 package org.apache.jcs.auxiliary.disk.jdbc.mysql.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.Calendar;
23 import java.util.Date;
24 import java.util.StringTokenizer;
25
26 /***
27 * Parses the very simple schedule format.
28 * <p>
29 * @author Aaron Smuts
30 */
31 public class ScheduleParser
32 {
33 /***
34 * For each date time that is separated by a comma in the
35 * OptimizationSchedule, create a date and add it to an array of dates.
36 * <p>
37 * @param schedule
38 * @return Date[]
39 * @throws ScheduleFormatException
40 */
41 public static Date[] createDatesForSchedule( String schedule )
42 throws ScheduleFormatException
43 {
44 if ( schedule == null )
45 {
46 throw new ScheduleFormatException( "Cannot create schedules for a null String." );
47 }
48
49 StringTokenizer toker = new StringTokenizer( schedule, "," );
50 Date[] dates = new Date[toker.countTokens()];
51 int cnt = 0;
52 while ( toker.hasMoreTokens() )
53 {
54 String time = toker.nextToken();
55 dates[cnt] = getDateForSchedule( time );
56 cnt++;
57 }
58 return dates;
59 }
60
61 /***
62 * For a single string it creates a date that is the next time this hh:mm:ss
63 * combo will be seen.
64 * <p>
65 * @param startTime
66 * @return
67 * @throws ScheduleFormatException
68 */
69 public static Date getDateForSchedule( String startTime )
70 throws ScheduleFormatException
71 {
72 if ( startTime == null )
73 {
74 throw new ScheduleFormatException( "Cannot create date for a null String." );
75 }
76
77 int firstColon = startTime.indexOf( ":" );
78 int lastColon = startTime.lastIndexOf( ":" );
79 int len = startTime.length();
80 if ( firstColon == -1 || lastColon == -1 || firstColon == lastColon || lastColon == len )
81 {
82 String message = "StartTime [" + startTime + "] is deformed. Unable to schedule optimizaiton.";
83 throw new ScheduleFormatException( message );
84 }
85
86 Calendar cal = Calendar.getInstance();
87 try
88 {
89 int hour = Integer.parseInt( startTime.substring( 0, firstColon ) );
90 cal.set( Calendar.HOUR_OF_DAY, hour );
91 int minute = Integer.parseInt( startTime.substring( firstColon + 1, lastColon ) );
92 cal.set( Calendar.MINUTE, minute );
93 int second = Integer.parseInt( startTime.substring( lastColon + 1, len ) );
94 cal.set( Calendar.SECOND, second );
95 }
96 catch ( NumberFormatException e )
97 {
98 String message = "Problem parsing start time [" + startTime + "]. It should be in HH:MM:SS format.";
99 throw new ScheduleFormatException( message );
100 }
101
102
103 Date now = new Date();
104 if ( cal.getTime().before( now ) )
105 {
106 cal.add( Calendar.DAY_OF_MONTH, 1 );
107 }
108
109 return cal.getTime();
110 }
111 }