-
Notifications
You must be signed in to change notification settings - Fork 2
/
XSDTypeCoercer.java
60 lines (53 loc) · 2.05 KB
/
XSDTypeCoercer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package cz.cvut.kbss.jsonld.deserialization.util;
import cz.cvut.kbss.jopa.vocabulary.XSD;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class XSDTypeCoercer {
private static final Logger LOG = LoggerFactory.getLogger(XSDTypeCoercer.class);
private static DatatypeFactory DATATYPE_FACTORY;
static {
try {
DATATYPE_FACTORY = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
LOG.error("Unable to create XML DatatypeFactory", e);
}
}
public static Object coerceType(String value, String type) {
switch (type) {
case XSD.BOOLEAN:
return Boolean.parseBoolean(value);
case XSD.BYTE:
return Byte.parseByte(value);
case XSD.SHORT:
case XSD.UNSIGNED_BYTE:
return Short.parseShort(value);
case XSD.INT:
case XSD.INTEGER:
case XSD.NON_NEGATIVE_INTEGER:
case XSD.NON_POSITIVE_INTEGER:
case XSD.POSITIVE_INTEGER:
case XSD.NEGATIVE_INTEGER:
case XSD.UNSIGNED_LONG:
return Integer.parseInt(value);
case XSD.LONG:
case XSD.UNSIGNED_INT:
return Long.parseLong(value);
case XSD.FLOAT:
return Float.parseFloat(value);
case XSD.DOUBLE:
return Double.parseDouble(value);
case XSD.DATE:
case XSD.DATETIME:
return ZonedDateTime.from(DateTimeFormatter.ISO_DATE_TIME.parse(value));
case XSD.DURATION:
return DATATYPE_FACTORY != null ? DATATYPE_FACTORY.newDuration(value) : Duration.parse(value);
default:
throw new IllegalArgumentException("Unsupported type for XSD type coercion: " + type);
}
}
}