Java Code Examples for org.eclipse.rdf4j.model.Literal#getDatatype()
The following examples show how to use
org.eclipse.rdf4j.model.Literal#getDatatype() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TriXWriter.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Writes out the XML-representation for the supplied value. */ private void writeValue(Value value) throws IOException, RDFHandlerException { if (value instanceof IRI) { IRI uri = (IRI) value; xmlWriter.textElement(URI_TAG, uri.toString()); } else if (value instanceof BNode) { BNode bNode = (BNode) value; xmlWriter.textElement(BNODE_TAG, bNode.getID()); } else if (value instanceof Literal) { Literal literal = (Literal) value; IRI datatype = literal.getDatatype(); if (Literals.isLanguageLiteral(literal)) { xmlWriter.setAttribute(LANGUAGE_ATT, literal.getLanguage().get()); xmlWriter.textElement(PLAIN_LITERAL_TAG, literal.getLabel()); } else { xmlWriter.setAttribute(DATATYPE_ATT, datatype.toString()); xmlWriter.textElement(TYPED_LITERAL_TAG, literal.getLabel()); } } else { throw new RDFHandlerException("Unknown value type: " + value.getClass()); } }
Example 2
Source File: RdfToRyaConversions.java From rya with Apache License 2.0 | 6 votes |
/** * Converts a {@link Literal} into a {@link RyaType} representation of the * {@code literal}. * @param literal the {@link Literal} to convert. * @return the {@link RyaType} representation of the {@code literal}. */ public static RyaType convertLiteral(final Literal literal) { if (literal == null) { return null; } if (literal.getDatatype() != null) { if (Literals.isLanguageLiteral(literal)) { final String language = literal.getLanguage().get(); if (Literals.isValidLanguageTag(language)) { return new RyaType(literal.getDatatype(), literal.stringValue(), language); } else { log.warn("Invalid language (" + LogUtils.clean(language) + ") found in Literal. Defaulting to: " + UNDETERMINED_LANGUAGE); // Replace invalid language with "und" return new RyaType(literal.getDatatype(), literal.stringValue(), UNDETERMINED_LANGUAGE); } } return new RyaType(literal.getDatatype(), literal.stringValue()); } return new RyaType(literal.stringValue()); }
Example 3
Source File: AbstractSPARQLXMLWriter.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
private void writeLiteral(Literal literal) throws IOException { if (Literals.isLanguageLiteral(literal)) { xmlWriter.setAttribute(LITERAL_LANG_ATT, literal.getLanguage().get()); } // Only enter this section for non-language literals now, as the // rdf:langString datatype is handled implicitly above else { IRI datatype = literal.getDatatype(); boolean ignoreDatatype = datatype.equals(XMLSchema.STRING) && xsdStringToPlainLiteral(); if (!ignoreDatatype) { if (isQName(datatype)) { writeQName(datatype); } xmlWriter.setAttribute(LITERAL_DATATYPE_ATT, datatype.stringValue()); } } xmlWriter.textElement(LITERAL_TAG, literal.getLabel()); }
Example 4
Source File: AbstractSearchIndex.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
private Iterable<? extends DocumentDistance> evaluateQuery(DistanceQuerySpec query) { Iterable<? extends DocumentDistance> hits = null; Literal from = query.getFrom(); double distance = query.getDistance(); IRI units = query.getUnits(); IRI geoProperty = query.getGeoProperty(); try { if (!GEO.WKT_LITERAL.equals(from.getDatatype())) { throw new MalformedQueryException("Unsupported datatype: " + from.getDatatype()); } Shape shape = parseQueryShape(SearchFields.getPropertyField(geoProperty), from.getLabel()); if (!(shape instanceof Point)) { throw new MalformedQueryException("Geometry literal is not a point: " + from.getLabel()); } Point p = (Point) shape; hits = geoQuery(geoProperty, p, units, distance, query.getDistanceVar(), query.getContextVar()); } catch (Exception e) { logger.error("There was a problem evaluating distance query 'within " + distance + getUnitSymbol(units) + " of " + from.getLabel() + "'!", e); } return hits; }
Example 5
Source File: SparqlToPigTransformVisitor.java From rya with Apache License 2.0 | 6 votes |
protected String getVarValue(Var var) { if (var == null) { return ""; } else { Value value = var.getValue(); if (value == null) { return ""; } if (value instanceof IRI) { return "<" + value.stringValue() + ">"; } if (value instanceof Literal) { Literal lit = (Literal) value; if (lit.getDatatype() == null) { //string return "\\'" + value.stringValue() + "\\'"; } } return value.stringValue(); } }
Example 6
Source File: NTriplesUtil.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Appends the N-Triples representation of the given {@link Literal} to the given {@link Appendable}, optionally * ignoring the xsd:string datatype as it is implied for RDF-1.1. * * @param lit The literal to write. * @param appendable The object to append to. * @param xsdStringToPlainLiteral True to omit serializing the xsd:string datatype and false to always serialize the * datatype for literals. * @param escapeUnicode True to escape non-ascii/non-printable characters using Unicode escapes * (<tt>\uxxxx</tt> and <tt>\Uxxxxxxxx</tt>), false to print without * escaping. * @throws IOException */ public static void append(Literal lit, Appendable appendable, boolean xsdStringToPlainLiteral, boolean escapeUnicode) throws IOException { // Do some character escaping on the label: appendable.append("\""); escapeString(lit.getLabel(), appendable, escapeUnicode); appendable.append("\""); if (Literals.isLanguageLiteral(lit)) { // Append the literal's language appendable.append("@"); appendable.append(lit.getLanguage().get()); } else { // SES-1917 : In RDF-1.1, all literals have a type, and if they are not // language literals we display the type for backwards compatibility // Append the literal's datatype IRI datatype = lit.getDatatype(); boolean ignoreDatatype = datatype.equals(XMLSchema.STRING) && xsdStringToPlainLiteral; if (!ignoreDatatype) { appendable.append("^^"); append(lit.getDatatype(), appendable); } } }
Example 7
Source File: StrictEvaluationStrategy.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
public Value evaluate(Datatype node, BindingSet bindings) throws QueryEvaluationException { Value v = evaluate(node.getArg(), bindings); if (v instanceof Literal) { Literal literal = (Literal) v; if (literal.getDatatype() != null) { // literal with datatype return literal.getDatatype(); } else if (literal.getLanguage().isPresent()) { return RDF.LANGSTRING; } else { // simple literal return XMLSchema.STRING; } } throw new ValueExprEvaluationException(); }
Example 8
Source File: Seconds.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("SECONDS requires 1 argument, got " + args.length); } Value argValue = args[0]; if (argValue instanceof Literal) { Literal literal = (Literal) argValue; IRI datatype = literal.getDatatype(); if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { try { XMLGregorianCalendar calValue = literal.calendarValue(); int seconds = calValue.getSecond(); if (DatatypeConstants.FIELD_UNDEFINED != seconds) { BigDecimal fraction = calValue.getFractionalSecond(); String str = (fraction == null) ? String.valueOf(seconds) : String.valueOf(fraction.doubleValue() + seconds); return valueFactory.createLiteral(str, XMLSchema.DECIMAL); } else { throw new ValueExprEvaluationException("can not determine minutes from value: " + argValue); } } catch (IllegalArgumentException e) { throw new ValueExprEvaluationException("illegal calendar value: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } }
Example 9
Source File: DatatypeFilter.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override boolean checkTuple(Tuple t) { if (!(t.line.get(1) instanceof Literal)) { return false; } Literal literal = (Literal) t.line.get(1); return literal.getDatatype() == datatype || literal.getDatatype().equals(datatype); }
Example 10
Source File: StringCast.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override protected Literal convert(ValueFactory valueFactory, Value value) throws ValueExprEvaluationException { if (value instanceof IRI) { return valueFactory.createLiteral(value.toString(), XMLSchema.STRING); } else if (value instanceof Literal) { Literal literal = (Literal) value; IRI datatype = literal.getDatatype(); if (QueryEvaluationUtil.isSimpleLiteral(literal)) { return valueFactory.createLiteral(literal.getLabel(), XMLSchema.STRING); } else if (!Literals.isLanguageLiteral(literal)) { if (XMLDatatypeUtil.isNumericDatatype(datatype) || datatype.equals(XMLSchema.BOOLEAN) || datatype.equals(XMLSchema.DATETIME) || datatype.equals(XMLSchema.DATETIMESTAMP)) { // FIXME Slightly simplified wrt the spec, we just always use the // canonical value of the // source literal as the target lexical value. This is not 100% // compliant with handling of // some date-related datatypes. // // See // http://www.w3.org/TR/xpath-functions/#casting-from-primitive-to-primitive if (XMLDatatypeUtil.isValidValue(literal.getLabel(), datatype)) { String normalizedValue = XMLDatatypeUtil.normalize(literal.getLabel(), datatype); return valueFactory.createLiteral(normalizedValue, XMLSchema.STRING); } else { return valueFactory.createLiteral(literal.getLabel(), XMLSchema.STRING); } } else { // for unknown datatypes, just use the lexical value. return valueFactory.createLiteral(literal.getLabel(), XMLSchema.STRING); } } } throw typeError(value, null); }
Example 11
Source File: PrepareOwnedTupleExpr.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void writeLiteral(StringBuilder builder, Literal lit) { String label = lit.getLabel(); if (label.indexOf('\n') > 0 || label.indexOf('\r') > 0 || label.indexOf('\t') > 0) { // Write label as long string builder.append("\"\"\""); builder.append(TurtleUtil.encodeLongString(label)); builder.append("\"\"\""); } else { // Write label as normal string builder.append("\""); builder.append(TurtleUtil.encodeString(label)); builder.append("\""); } IRI datatype = lit.getDatatype(); if (Literals.isLanguageLiteral(lit)) { // Append the literal's language builder.append("@"); builder.append(lit.getLanguage().get()); } else { // Append the literal's data type (possibly written as an // abbreviated URI) builder.append("^^"); writeURI(builder, datatype); } }
Example 12
Source File: FilterUtils.java From CostFed with GNU Affero General Public License v3.0 | 5 votes |
protected static StringBuilder appendLiteral(StringBuilder sb, Literal lit) { sb.append('"'); sb.append(lit.getLabel().replace("\"", "\\\"")); sb.append('"'); if (lit.getLanguage() != null && lit.getLanguage().isPresent()) { sb.append('@'); sb.append(lit.getLanguage()); } else if (!XMLSchema.STRING.equals(lit.getDatatype()) && lit.getDatatype() != null) { sb.append("^^<"); sb.append(lit.getDatatype().stringValue()); sb.append('>'); } return sb; }
Example 13
Source File: Tz.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("TZ requires 1 argument, got " + args.length); } Value argValue = args[0]; if (argValue instanceof Literal) { Literal literal = (Literal) argValue; IRI datatype = literal.getDatatype(); if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { String lexValue = literal.getLabel(); Pattern pattern = Pattern.compile("Z|[+-]\\d\\d:\\d\\d"); Matcher m = pattern.matcher(lexValue); String timeZone = ""; if (m.find()) { timeZone = m.group(); } return valueFactory.createLiteral(timeZone); } else { throw new ValueExprEvaluationException("unexpected input value for function: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } }
Example 14
Source File: BinaryQueryResultWriter.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void writeLiteral(Literal literal) throws IOException { String label = literal.getLabel(); IRI datatype = literal.getDatatype(); int marker = PLAIN_LITERAL_RECORD_MARKER; if (Literals.isLanguageLiteral(literal)) { marker = LANG_LITERAL_RECORD_MARKER; } else { String namespace = datatype.getNamespace(); if (!namespaceTable.containsKey(namespace)) { // Assign an ID to this new namespace writeNamespace(namespace); } marker = DATATYPE_LITERAL_RECORD_MARKER; } out.writeByte(marker); writeString(label); if (Literals.isLanguageLiteral(literal)) { writeString(literal.getLanguage().get()); } else { writeQName(datatype); } }
Example 15
Source File: Timezone.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("TIMEZONE requires 1 argument, got " + args.length); } Value argValue = args[0]; if (argValue instanceof Literal) { Literal literal = (Literal) argValue; IRI datatype = literal.getDatatype(); if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { try { XMLGregorianCalendar calValue = literal.calendarValue(); int timezoneOffset = calValue.getTimezone(); if (DatatypeConstants.FIELD_UNDEFINED != timezoneOffset) { // TODO creating xsd:dayTimeDuration lexical representation // manually. Surely there is a better way to do this? int minutes = Math.abs(timezoneOffset); int hours = minutes / 60; minutes = minutes - (hours * 60); StringBuilder tzDuration = new StringBuilder(); if (timezoneOffset < 0) { tzDuration.append("-"); } tzDuration.append("PT"); if (hours > 0) { tzDuration.append(hours + "H"); } if (minutes > 0) { tzDuration.append(minutes + "M"); } if (timezoneOffset == 0) { tzDuration.append("0S"); } return valueFactory.createLiteral(tzDuration.toString(), XMLSchema.DAYTIMEDURATION); } else { throw new ValueExprEvaluationException("can not determine timezone from value: " + argValue); } } catch (IllegalArgumentException e) { throw new ValueExprEvaluationException("illegal calendar value: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } }
Example 16
Source File: RDFXMLPrettyWriter.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Write out an empty property element. */ private void writeAbbreviatedPredicate(IRI pred, Value obj) throws IOException, RDFHandlerException { writeStartOfStartTag(pred.getNamespace(), pred.getLocalName()); if (obj instanceof Resource) { Resource objRes = (Resource) obj; if (objRes instanceof IRI) { IRI uri = (IRI) objRes; writeAttribute(RDF.NAMESPACE, "resource", uri.toString()); } else { BNode bNode = (BNode) objRes; writeAttribute(RDF.NAMESPACE, "nodeID", getValidNodeId(bNode)); } writeEndOfEmptyTag(); } else if (obj instanceof Literal) { Literal objLit = (Literal) obj; // datatype attribute IRI datatype = objLit.getDatatype(); // Check if datatype is rdf:XMLLiteral boolean isXmlLiteral = datatype.equals(RDF.XMLLITERAL); // language attribute if (Literals.isLanguageLiteral(objLit)) { writeAttribute("xml:lang", objLit.getLanguage().get()); } else { if (isXmlLiteral) { writeAttribute(RDF.NAMESPACE, "parseType", "Literal"); } else { writeAttribute(RDF.NAMESPACE, "datatype", datatype.toString()); } } writeEndOfStartTag(); // label if (isXmlLiteral) { // Write XML literal as plain XML writer.write(objLit.getLabel()); } else { writeCharacterData(objLit.getLabel()); } writeEndTag(pred.getNamespace(), pred.getLocalName()); } writeNewLine(); }
Example 17
Source File: DateTimeCast.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override protected Literal convert(ValueFactory vf, Value value) throws ValueExprEvaluationException { if (value instanceof Literal) { Literal literal = (Literal) value; IRI datatype = literal.getDatatype(); if (datatype.equals(XMLSchema.DATE)) { // If ST is xs:date, then let SYR be eg:convertYearToString( // fn:year-from-date( SV )), let SMO be eg:convertTo2CharString( // fn:month-from-date( SV )), let SDA be eg:convertTo2CharString( // fn:day-from-date( SV )) and let STZ be eg:convertTZtoString( // fn:timezone-from-date( SV )); TV is xs:dateTime( fn:concat( // SYR , '-', SMO , '-', SDA , 'T00:00:00 ', STZ ) ). try { XMLGregorianCalendar calValue = literal.calendarValue(); int year = calValue.getYear(); int month = calValue.getMonth(); int day = calValue.getDay(); int timezoneOffset = calValue.getTimezone(); if (DatatypeConstants.FIELD_UNDEFINED != year && DatatypeConstants.FIELD_UNDEFINED != month && DatatypeConstants.FIELD_UNDEFINED != day) { StringBuilder dtBuilder = new StringBuilder(); dtBuilder.append(year); dtBuilder.append("-"); if (month < 10) { dtBuilder.append("0"); } dtBuilder.append(month); dtBuilder.append("-"); if (day < 10) { dtBuilder.append("0"); } dtBuilder.append(day); dtBuilder.append("T00:00:00"); if (DatatypeConstants.FIELD_UNDEFINED != timezoneOffset) { int minutes = Math.abs(timezoneOffset); int hours = minutes / 60; minutes = minutes - (hours * 60); if (timezoneOffset > 0) { dtBuilder.append("+"); } else { dtBuilder.append("-"); } if (hours < 10) { dtBuilder.append("0"); } dtBuilder.append(hours); dtBuilder.append(":"); if (minutes < 10) { dtBuilder.append("0"); } dtBuilder.append(minutes); } return vf.createLiteral(dtBuilder.toString(), XMLSchema.DATETIME); } else { throw typeError(literal, null); } } catch (IllegalArgumentException e) { throw typeError(literal, e); } } } throw typeError(value, null); }
Example 18
Source File: SPARQLResultsTSVWriter.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
private void writeLiteral(Literal lit) throws IOException { String label = lit.getLabel(); IRI datatype = lit.getDatatype(); if (XMLSchema.INTEGER.equals(datatype) || XMLSchema.DECIMAL.equals(datatype) || XMLSchema.DOUBLE.equals(datatype)) { try { writer.write(XMLDatatypeUtil.normalize(label, datatype)); return; // done } catch (IllegalArgumentException e) { // not a valid numeric typed literal. ignore error and write as // quoted string instead. } } String encoded = encodeString(label); if (Literals.isLanguageLiteral(lit)) { writer.write("\""); writer.write(encoded); writer.write("\""); // Append the literal's language writer.write("@"); writer.write(lit.getLanguage().get()); } else if (!XMLSchema.STRING.equals(datatype) || !xsdStringToPlainLiteral()) { writer.write("\""); writer.write(encoded); writer.write("\""); // Append the literal's datatype writer.write("^^"); writeURI(datatype); } else if (label.length() > 0 && encoded.equals(label) && label.charAt(0) != '<' && label.charAt(0) != '_' && !label.matches("^[\\+\\-]?[\\d\\.].*")) { // no need to include double quotes writer.write(encoded); } else { writer.write("\""); writer.write(encoded); writer.write("\""); } }
Example 19
Source File: StrBefore.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 2) { throw new ValueExprEvaluationException("Incorrect number of arguments for STRBEFORE: " + args.length); } Value leftArg = args[0]; Value rightArg = args[1]; if (leftArg instanceof Literal && rightArg instanceof Literal) { Literal leftLit = (Literal) leftArg; Literal rightLit = (Literal) rightArg; if (QueryEvaluationUtil.compatibleArguments(leftLit, rightLit)) { Optional<String> leftLanguage = leftLit.getLanguage(); IRI leftDt = leftLit.getDatatype(); String lexicalValue = leftLit.getLabel(); String substring = rightLit.getLabel(); int index = lexicalValue.indexOf(substring); String substringBefore = ""; if (index > -1) { substringBefore = lexicalValue.substring(0, index); } else { // no match, return empty string with no language or datatype leftLanguage = Optional.empty(); leftDt = null; } if (leftLanguage.isPresent()) { return valueFactory.createLiteral(substringBefore, leftLanguage.get()); } else if (leftDt != null) { return valueFactory.createLiteral(substringBefore, leftDt); } else { return valueFactory.createLiteral(substringBefore); } } else { throw new ValueExprEvaluationException( "incompatible operands for STRBEFORE: " + leftArg + ", " + rightArg); } } else { throw new ValueExprEvaluationException("incompatible operands for STRBEFORE: " + leftArg + ", " + rightArg); } }
Example 20
Source File: AccumuloRyaUtils.java From rya with Apache License 2.0 | 4 votes |
/** * Creates a copy tool split time {@link RyaStatement} from the specified {@link Date}. * @param date the copy tool split time {@link Date}. * @return the {@link RyaStatement} for the copy tool split time. */ public static RyaStatement createCopyToolSplitTimeRyaStatement(final Date date) { final Literal literal = VALUE_FACTORY.createLiteral(date != null ? date : DEFAULT_DATE); final RyaType timeObject = new RyaType(literal.getDatatype(), literal.stringValue()); return new RyaStatement(RTS_SUBJECT_RYA, RTS_COPY_TOOL_SPLIT_TIME_PREDICATE_RYA, timeObject); }