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