1
|
/**
|
2
|
* Copyright (C) 2007 EDIT
|
3
|
* European Distributed Institute of Taxonomy
|
4
|
* http://www.e-taxonomy.eu
|
5
|
*
|
6
|
* The contents of this file are subject to the Mozilla Public License Version 1.1
|
7
|
* See LICENSE.TXT at the top of this package for the full license terms.
|
8
|
*/
|
9
|
|
10
|
package eu.etaxonomy.taxeditor.model;
|
11
|
|
12
|
import eu.etaxonomy.cdm.model.common.TimePeriod;
|
13
|
|
14
|
/**
|
15
|
* <p>TimeHelper class.</p>
|
16
|
*
|
17
|
* @autor p.ciardelli
|
18
|
* @author n.hoffmann
|
19
|
* @created 18.03.2009
|
20
|
* @version 1.0
|
21
|
*/
|
22
|
public class TimeHelper {
|
23
|
/**
|
24
|
* Converts a <code>String</code> whose format is either a valid year
|
25
|
* or two valid years with the format "XXXX-XXXX" into a TimePeriod.
|
26
|
*
|
27
|
* @see #getValidYear(String yearStr)
|
28
|
* @param refYear a {@link java.lang.String} object.
|
29
|
* @throws java.lang.NumberFormatException if any.
|
30
|
* @return a {@link eu.etaxonomy.cdm.model.common.TimePeriod} object.
|
31
|
*/
|
32
|
public static TimePeriod convertTimePeriod(String refYear) throws NumberFormatException {
|
33
|
|
34
|
if (refYear == null || ("").equals(refYear)){
|
35
|
return null;
|
36
|
}
|
37
|
|
38
|
TimePeriod datePublished = TimePeriod.NewInstance();
|
39
|
|
40
|
// In case format is "xxxx-xxxx"
|
41
|
String[] years = refYear.split("-");
|
42
|
|
43
|
// Unlikely case of "xxxx-xxxx-xxxx..."
|
44
|
if (years.length > 2) {
|
45
|
throw new NumberFormatException();
|
46
|
}
|
47
|
|
48
|
// Set startYear
|
49
|
datePublished.setStartYear(getValidYear(years[0]));
|
50
|
|
51
|
// Format is "xxxx-xxxx"
|
52
|
if (years.length == 2) {
|
53
|
datePublished.setEndYear(getValidYear(years[1]));
|
54
|
}
|
55
|
|
56
|
return datePublished;
|
57
|
}
|
58
|
|
59
|
/**
|
60
|
* Checks whether a <code>String</code> is a valid year between
|
61
|
* 1750 and 2030. Throws a <code>NumberFormatException</code> if not.
|
62
|
*
|
63
|
* @param yearStr a {@link java.lang.String} object.
|
64
|
* @throws java.lang.NumberFormatException if any.
|
65
|
* @return a {@link java.lang.Integer} object.
|
66
|
*/
|
67
|
public static Integer getValidYear(String yearStr) throws NumberFormatException {
|
68
|
|
69
|
Integer yearInt = null;
|
70
|
|
71
|
// Try casting string - don't catch number format exception
|
72
|
try {
|
73
|
yearInt = new Integer(yearStr);
|
74
|
} catch (ClassCastException e) {
|
75
|
throw new NumberFormatException();
|
76
|
}
|
77
|
|
78
|
// Is year in valid range?
|
79
|
if (yearInt < 1750 || yearInt > 2030) {
|
80
|
throw new NumberFormatException();
|
81
|
}
|
82
|
|
83
|
return yearInt;
|
84
|
}
|
85
|
}
|