1 package org.apache.commons.jcs3.auxiliary.disk.jdbc.mysql.util;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 import java.text.ParseException;
23 import java.text.SimpleDateFormat;
24 import java.util.Calendar;
25 import java.util.Date;
26
27 /**
28 * Parses the very simple schedule format.
29 */
30 public class ScheduleParser
31 {
32 /**
33 * For each date time that is separated by a comma in the
34 * OptimizationSchedule, create a date and add it to an array of dates.
35 * <p>
36 * @param schedule
37 * @return Date[]
38 * @throws ParseException
39 */
40 public static Date[] createDatesForSchedule( final String schedule )
41 throws ParseException
42 {
43 if (schedule == null || schedule.isEmpty())
44 {
45 throw new ParseException( "Cannot create schedules for a null or empty String.", 0 );
46 }
47
48 final String timeStrings[] = schedule.split("\\s*,\\s*");
49 final Date[] dates = new Date[timeStrings.length];
50 int cnt = 0;
51 for (String time : timeStrings)
52 {
53 dates[cnt++] = getDateForSchedule(time);
54 }
55 return dates;
56 }
57
58 /**
59 * For a single string it creates a date that is the next time this hh:mm:ss
60 * combo will be seen.
61 * <p>
62 * @param startTime
63 * @return Date
64 * @throws ParseException
65 */
66 public static Date getDateForSchedule( final String startTime )
67 throws ParseException
68 {
69 if ( startTime == null )
70 {
71 throw new ParseException( "Cannot create date for a null String.", 0 );
72 }
73
74 final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
75 final Date date = sdf.parse(startTime);
76 final Calendar cal = Calendar.getInstance();
77 // This will result in a date of 1/1/1970
78 cal.setTime(date);
79
80 final Calendar now = Calendar.getInstance();
81 cal.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
82
83 // if the date is less than now, add a day.
84 if ( cal.before( now ) )
85 {
86 cal.add( Calendar.DAY_OF_MONTH, 1 );
87 }
88
89 return cal.getTime();
90 }
91 }