01: /*
02: * Copyright Aduna (http://www.aduna-software.com/) (c) 2007.
03: *
04: * Licensed under the Aduna BSD-style license.
05: */
06: package org.openrdf.query.algebra.evaluation.function;
07:
08: import org.openrdf.model.Literal;
09: import org.openrdf.model.URI;
10: import org.openrdf.model.Value;
11: import org.openrdf.model.ValueFactory;
12: import org.openrdf.model.datatypes.XMLDatatypeUtil;
13: import org.openrdf.model.vocabulary.XMLSchema;
14: import org.openrdf.query.algebra.evaluation.ValueExprEvaluationException;
15: import org.openrdf.query.algebra.evaluation.util.QueryEvaluationUtil;
16:
17: /**
18: * A {@link Function} that tries to cast its argument to an
19: * <tt>xsd:dateTime</tt>.
20: *
21: * @author Arjohn Kampman
22: */
23: public class DateTimeCast implements Function {
24:
25: public String getURI() {
26: return XMLSchema.DATETIME.toString();
27: }
28:
29: public Literal evaluate(ValueFactory valueFactory, Value... args)
30: throws ValueExprEvaluationException {
31: if (args.length != 1) {
32: throw new ValueExprEvaluationException(
33: "xsd:dateTime cast requires exactly 1 argument, got "
34: + args.length);
35: }
36:
37: if (args[0] instanceof Literal) {
38: Literal literal = (Literal) args[0];
39: URI datatype = literal.getDatatype();
40:
41: if (QueryEvaluationUtil.isStringLiteral(literal)) {
42: String dateTimeValue = XMLDatatypeUtil
43: .collapseWhiteSpace(literal.getLabel());
44: if (XMLDatatypeUtil.isValidDateTime(dateTimeValue)) {
45: return valueFactory.createLiteral(dateTimeValue,
46: XMLSchema.DATETIME);
47: }
48: } else if (datatype != null) {
49: if (datatype.equals(XMLSchema.DATETIME)) {
50: return literal;
51: }
52: }
53: }
54:
55: throw new ValueExprEvaluationException(
56: "Invalid argument for xsd:dateTime cast: " + args[0]);
57: }
58: }
|