001package com.avaje.ebean.text;
002
003import java.sql.Time;
004
005/**
006 * Parser for TIME types that supports both HH:mm:ss and HH:mm.
007 * 
008 * @author rbygrave
009 */
010public final class TimeStringParser implements StringParser {
011
012  private static final TimeStringParser SHARED = new TimeStringParser();
013
014  /**
015   * Return a shared instance as this is thread safe.
016   */
017  public static TimeStringParser get() {
018    return SHARED;
019  }
020
021  /**
022   * Parse the String supporting both HH:mm:ss and HH:mm formats.
023   */
024  @SuppressWarnings("deprecation")
025  public Object parse(String value) {
026    if (value == null || value.trim().isEmpty()) {
027      return null;
028    }
029
030    String s = value.trim();
031    int minute;
032    int second;
033    int firstColon = s.indexOf(':');
034    int secondColon = s.indexOf(':', firstColon + 1);
035
036    if (firstColon == -1) {
037      throw new java.lang.IllegalArgumentException("No ':' in value [" + s + "]");
038    }
039    try {
040      int hour = Integer.parseInt(s.substring(0, firstColon));
041      if (secondColon == -1) {
042        minute = Integer.parseInt(s.substring(firstColon + 1, s.length()));
043        second = 0;
044      } else {
045        minute = Integer.parseInt(s.substring(firstColon + 1, secondColon));
046        second = Integer.parseInt(s.substring(secondColon + 1));
047      }
048
049      return new Time(hour, minute, second);
050
051    } catch (NumberFormatException e) {
052      throw new java.lang.IllegalArgumentException("Number format Error parsing time [" + s + "] "
053          + e.getMessage(), e);
054    }
055  }
056}