svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.timesupport / org.gvsig.timesupport.lib / org.gvsig.timesupport.lib.impl / src / main / java / org / gvsig / timesupport / impl / coercion / CoerceToInstant.java @ 44669
History | View | Annotate | Download (2.41 KB)
1 |
package org.gvsig.timesupport.impl.coercion; |
---|---|
2 |
|
3 |
import java.text.DateFormat; |
4 |
import java.text.ParseException; |
5 |
import java.util.Date; |
6 |
import org.apache.commons.lang3.math.NumberUtils; |
7 |
import org.gvsig.timesupport.RelativeInstant; |
8 |
import org.gvsig.timesupport.TimeSupportLocator; |
9 |
import org.gvsig.timesupport.TimeSupportManager; |
10 |
import org.gvsig.tools.dataTypes.AbstractCoercion; |
11 |
import org.gvsig.tools.dataTypes.CoercionException; |
12 |
import org.gvsig.tools.dataTypes.DataTypeUtils; |
13 |
import org.gvsig.tools.dataTypes.CoercionContext; |
14 |
import org.gvsig.tools.dataTypes.CoercionContextLocale; |
15 |
|
16 |
/**
|
17 |
*
|
18 |
* @author jjdelcerro
|
19 |
*/
|
20 |
public class CoerceToInstant extends AbstractCoercion { |
21 |
|
22 |
public CoerceToInstant() {
|
23 |
|
24 |
} |
25 |
|
26 |
@Override
|
27 |
public Object coerce(Object value, CoercionContext context) throws CoercionException { |
28 |
if (value == null || value instanceof RelativeInstant) { |
29 |
return value;
|
30 |
} |
31 |
TimeSupportManager manager = TimeSupportLocator.getManager(); |
32 |
if (value instanceof Date) { |
33 |
RelativeInstant instant = manager.createRelativeInstant((Date) value);
|
34 |
return instant;
|
35 |
} |
36 |
if (value instanceof Number) { |
37 |
RelativeInstant instant = manager.createRelativeInstant(((Number) value).longValue());
|
38 |
return instant;
|
39 |
} |
40 |
if (value instanceof String) { |
41 |
long milis_l = NumberUtils.toLong((String) value, Long.MIN_VALUE); |
42 |
if (milis_l != Long.MIN_VALUE) { |
43 |
RelativeInstant instant = manager.createRelativeInstant(milis_l); |
44 |
return instant;
|
45 |
} |
46 |
double milis_d = NumberUtils.toDouble((String) value, Double.NaN); |
47 |
if (milis_d != Double.NaN) { |
48 |
RelativeInstant instant = manager.createRelativeInstant((long) milis_d);
|
49 |
return instant;
|
50 |
} |
51 |
CoercionContextLocale theContext; |
52 |
if (context instanceof CoercionContextLocale) { |
53 |
theContext = (CoercionContextLocale) context; |
54 |
} else {
|
55 |
theContext = DataTypeUtils.coerceContextDefaultLocale(); |
56 |
} |
57 |
DateFormat df = DateFormat.getDateTimeInstance( |
58 |
DateFormat.DEFAULT,
|
59 |
DateFormat.DEFAULT,
|
60 |
theContext.locale() |
61 |
); |
62 |
try {
|
63 |
Date date = df.parse((String) value); |
64 |
RelativeInstant instant = manager.createRelativeInstant(date); |
65 |
return instant;
|
66 |
} catch (ParseException ex) { |
67 |
} |
68 |
} |
69 |
throw new CoercionException("Can't coerce (" + value.getClass().getSimpleName() + ") '" + value.toString() + "' to Instant."); |
70 |
} |
71 |
} |