Statistics
| Revision:

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 @ 44136

History | View | Annotate | Download (2.41 KB)

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