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 <tt>xsd:string</tt>.
19: *
20: * @author Arjohn Kampman
21: */
22: public class StringCast implements Function {
23:
24: public String getURI() {
25: return XMLSchema.STRING.toString();
26: }
27:
28: public Literal evaluate(ValueFactory valueFactory, Value... args)
29: throws ValueExprEvaluationException {
30: if (args.length != 1) {
31: throw new ValueExprEvaluationException(
32: "xsd:string cast requires exactly 1 argument, got "
33: + args.length);
34: }
35:
36: Value value = args[0];
37: if (value instanceof URI) {
38: return valueFactory.createLiteral(value.toString(),
39: XMLSchema.STRING);
40: } else if (value instanceof Literal) {
41: Literal literal = (Literal) value;
42: URI datatype = literal.getDatatype();
43:
44: if (QueryEvaluationUtil.isSimpleLiteral(literal)) {
45: return valueFactory.createLiteral(literal.getLabel(),
46: XMLSchema.STRING);
47: } else if (datatype != null) {
48: if (datatype.equals(XMLSchema.STRING)) {
49: return literal;
50: } else if (XMLDatatypeUtil.isNumericDatatype(datatype)
51: || datatype.equals(XMLSchema.BOOLEAN)
52: || datatype.equals(XMLSchema.DATETIME)) {
53: // FIXME: conversion to xsd:string is much more complex than
54: // this, see
55: // http://www.w3.org/TR/xpath-functions/#casting-from-primitive-to-primitive
56: return valueFactory.createLiteral(literal
57: .getLabel(), XMLSchema.STRING);
58: }
59: }
60: }
61:
62: throw new ValueExprEvaluationException(
63: "Invalid argument for xsd:string cast: " + value);
64: }
65: }
|