Statistics
| Revision:

gvsig-tools / org.gvsig.tools / library / trunk / org.gvsig.tools / org.gvsig.tools.lib / src / main / java / org / gvsig / tools / dataTypes / impl / coercion / CoerceToLong.java @ 2080

History | View | Annotate | Download (2.26 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 2 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.tools.dataTypes.impl.coercion;
24

    
25
import java.util.Date;
26
import org.gvsig.tools.dataTypes.AbstractCoercion;
27
import org.gvsig.tools.dataTypes.CoercionException;
28
import org.gvsig.tools.dataTypes.CoercionContext;
29

    
30
@SuppressWarnings("UseSpecificCatch")
31
public class CoerceToLong extends AbstractCoercion {
32

    
33
  @Override
34
  public Object coerce(Object value, CoercionContext context) throws CoercionException {
35
    if (value == null || value instanceof Long) {
36
      return value;
37
    }
38
    Long num;
39
    try {
40
      if (value instanceof Number) {
41
        num = ((Number) value).longValue();
42

    
43
      } else if (value instanceof Boolean) {
44
        num = ((boolean) value ? 1l : 0l);
45

    
46
      } else if (value instanceof Date) {
47
        num = ((Date) value).getTime();
48

    
49
      } else {
50
        String s = value.toString();
51
        if (s == null) {
52
          return null;
53
        }
54
        s = s.trim().toLowerCase();
55
        if (s.length() == 0) {
56
          return null;
57
        }
58
        if (s.startsWith("0x")) {
59
          num = Long.valueOf(s.substring(2), 16);
60

    
61
        } else {
62
          if (s.startsWith("+")) {
63
            s = s.substring(1);
64
          }
65
          num = Long.valueOf(s);
66
        }
67
      }
68
      return num;
69
    } catch (Exception e) {
70
      throw new CoercionException("Can't coerce '" + value.toString() + "' to long.", e);
71
    }
72
  }
73
}