Java Code Examples for org.eclipse.rdf4j.model.Literal#getLabel()

The following examples show how to use org.eclipse.rdf4j.model.Literal#getLabel() . 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: StrEnds.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length != 2) {
		throw new ValueExprEvaluationException("STRENDS requires 2 arguments, got " + args.length);
	}

	Value leftVal = args[0];
	Value rightVal = args[1];

	if (leftVal instanceof Literal && rightVal instanceof Literal) {
		Literal leftLit = (Literal) leftVal;
		Literal rightLit = (Literal) rightVal;

		if (QueryEvaluationUtil.compatibleArguments(leftLit, rightLit)) {

			String leftLexVal = leftLit.getLabel();
			String rightLexVal = rightLit.getLabel();

			return BooleanLiteral.valueOf(leftLexVal.endsWith(rightLexVal));
		} else {
			throw new ValueExprEvaluationException("incompatible operands for STRENDS function");
		}
	} else {
		throw new ValueExprEvaluationException("STRENDS function expects literal operands");
	}
}
 
Example 2
Source File: SHA384.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length != 1) {
		throw new ValueExprEvaluationException("SHA384 requires exactly 1 argument, got " + args.length);
	}

	if (args[0] instanceof Literal) {
		Literal literal = (Literal) args[0];

		if (QueryEvaluationUtil.isSimpleLiteral(literal) || XMLSchema.STRING.equals(literal.getDatatype())) {
			String lexValue = literal.getLabel();

			try {
				return valueFactory.createLiteral(hash(lexValue, "SHA-384"));
			} catch (NoSuchAlgorithmException e) {
				// SHA384 should always be available.
				throw new RuntimeException(e);
			}
		} else {
			throw new ValueExprEvaluationException("Invalid argument for SHA384: " + literal);
		}
	} else {
		throw new ValueExprEvaluationException("Invalid argument for SHA384: " + args[0]);
	}
}
 
Example 3
Source File: BuildString.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length < 1) {
		throw new ValueExprEvaluationException("Incorrect number of arguments");
	}
	if (!(args[0] instanceof Literal)) {
		throw new ValueExprEvaluationException("First argument must be a string");
	}
	Literal s = (Literal) args[0];
	String tmpl = s.getLabel();
	Map<String, String> mappings = new HashMap<>(args.length);
	for (int i = 1; i < args.length; i++) {
		mappings.put(Integer.toString(i), args[i].stringValue());
	}
	String newValue = StringSubstitutor.replace(tmpl, mappings, "{?", "}");
	return valueFactory.createLiteral(newValue);
}
 
Example 4
Source File: DecimalFormat.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected Value evaluate(ValueFactory valueFactory, Value arg1, Value arg2) throws ValueExprEvaluationException {
	if (!(arg1 instanceof Literal) || !(arg2 instanceof Literal)) {
		throw new ValueExprEvaluationException("Both arguments must be literals");
	}
	Literal number = (Literal) arg1;
	Literal format = (Literal) arg2;

	java.text.DecimalFormat formatter = new java.text.DecimalFormat(format.getLabel());
	String value;
	if (XMLSchema.INT.equals(number.getDatatype()) || XMLSchema.LONG.equals(number.getDatatype())
			|| XMLSchema.SHORT.equals(number.getDatatype()) || XMLSchema.BYTE.equals(number.getDatatype())) {
		value = formatter.format(number.longValue());
	} else if (XMLSchema.DECIMAL.equals(number.getDatatype())) {
		value = formatter.format(number.decimalValue());
	} else if (XMLSchema.INTEGER.equals(number.getDatatype())) {
		value = formatter.format(number.integerValue());
	} else {
		value = formatter.format(number.doubleValue());
	}
	return valueFactory.createLiteral(value);
}
 
Example 5
Source File: MD5.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length != 1) {
		throw new ValueExprEvaluationException("MD5 requires exactly 1 argument, got " + args.length);
	}

	if (args[0] instanceof Literal) {
		Literal literal = (Literal) args[0];

		if (QueryEvaluationUtil.isSimpleLiteral(literal) || XMLSchema.STRING.equals(literal.getDatatype())) {
			String lexValue = literal.getLabel();

			try {
				return valueFactory.createLiteral(hash(lexValue, "MD5"));
			} catch (NoSuchAlgorithmException e) {
				// MD5 should always be available.
				throw new RuntimeException(e);
			}
		} else {
			throw new ValueExprEvaluationException("Invalid argument for MD5: " + literal);
		}
	} else {
		throw new ValueExprEvaluationException("Invalid argument for Md5: " + args[0]);
	}
}
 
Example 6
Source File: FunctionAdapter.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Convert from OpenRDF to rdf4j value used by Geo Functions.
 * 
 * @param value
 *            Must be a URIImpl, Literal or a BooleanLiteralImpl, or throws error. Ignores language.
 * @param rdf4jValueFactory
 * @return an rdf4j Literal copied from the input
 */
public org.eclipse.rdf4j.model.Value adaptValue(Value value, org.eclipse.rdf4j.model.ValueFactory rdf4jValueFactory) {
    if (value instanceof URIImpl) {
        URIImpl uri = (URIImpl) value;
        return rdf4jValueFactory.createIRI(uri.stringValue());
    } else if (!(value instanceof Literal)) {
        throw new UnsupportedOperationException("Not supported, value must be literal type, it was: " + value.getClass() + " value=" + value);
    }
    if (value instanceof BooleanLiteralImpl) {
        BooleanLiteralImpl bl = (BooleanLiteralImpl) value;
        if (bl.booleanValue())
            return org.eclipse.rdf4j.model.impl.BooleanLiteral.TRUE;
        else
            return org.eclipse.rdf4j.model.impl.BooleanLiteral.FALSE;
    }
    final Literal literalValue = (Literal) value;
    org.eclipse.rdf4j.model.ValueFactory vf = org.eclipse.rdf4j.model.impl.SimpleValueFactory.getInstance();
    final String label = literalValue.getLabel();
    final IRI datatype = vf.createIRI(literalValue.getDatatype().stringValue());
    return vf.createLiteral(label, datatype);
}
 
Example 7
Source File: AbstractSearchIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 8
Source File: SHA512.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length != 1) {
		throw new ValueExprEvaluationException("SHA512 requires exactly 1 argument, got " + args.length);
	}

	if (args[0] instanceof Literal) {
		Literal literal = (Literal) args[0];

		if (QueryEvaluationUtil.isSimpleLiteral(literal) || XMLSchema.STRING.equals(literal.getDatatype())) {
			String lexValue = literal.getLabel();

			try {
				return valueFactory.createLiteral(hash(lexValue, "SHA-512"));
			} catch (NoSuchAlgorithmException e) {
				// SHA512 should always be available.
				throw new RuntimeException(e);
			}
		} else {
			throw new ValueExprEvaluationException("Invalid argument for SHA512: " + literal);
		}
	} else {
		throw new ValueExprEvaluationException("Invalid argument for SHA512: " + args[0]);
	}
}
 
Example 9
Source File: SHA256.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length != 1) {
		throw new ValueExprEvaluationException("SHA256 requires exactly 1 argument, got " + args.length);
	}

	if (args[0] instanceof Literal) {
		Literal literal = (Literal) args[0];

		if (QueryEvaluationUtil.isSimpleLiteral(literal) || XMLSchema.STRING.equals(literal.getDatatype())) {
			String lexValue = literal.getLabel();

			try {
				return valueFactory.createLiteral(hash(lexValue, "SHA-256"));
			} catch (NoSuchAlgorithmException e) {
				// SHA256 should always be available.
				throw new RuntimeException(e);
			}
		} else {
			throw new ValueExprEvaluationException("Invalid argument for SHA256: " + literal);
		}
	} else {
		throw new ValueExprEvaluationException("Invalid argument for SHA256: " + args[0]);
	}
}
 
Example 10
Source File: PrepareOwnedTupleExpr.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 11
Source File: JSONLDInternalRDFParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void handleStatement(RDFDataset result, Statement nextStatement) {
	// TODO: from a basic look at the code it seems some of these could be
	// null
	// null values for IRIs will probably break things further down the line
	// and i'm not sure yet if this should be something handled later on, or
	// something that should be checked here
	final String subject = getResourceValue(nextStatement.getSubject());
	final String predicate = getResourceValue(nextStatement.getPredicate());
	final Value object = nextStatement.getObject();
	final String graphName = getResourceValue(nextStatement.getContext());

	if (object instanceof Literal) {
		final Literal literal = (Literal) object;
		final String value = literal.getLabel();

		String datatype = getResourceValue(literal.getDatatype());

		// In RDF-1.1, Language Literals internally have the datatype
		// rdf:langString
		if (literal.getLanguage().isPresent() && datatype == null) {
			datatype = RDF.LANGSTRING.stringValue();
		}

		// In RDF-1.1, RDF-1.0 Plain Literals are now Typed Literals with
		// type xsd:String
		if (!literal.getLanguage().isPresent() && datatype == null) {
			datatype = XMLSchema.STRING.stringValue();
		}

		result.addQuad(subject, predicate, value, datatype, literal.getLanguage().orElse(null), graphName);
	} else {
		result.addQuad(subject, predicate, getResourceValue((Resource) object), graphName);
	}
}
 
Example 12
Source File: DAWGTestResultSetParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Binding getBinding(Resource bindingNode) {
	Literal name = Models.getPropertyLiteral(graph, bindingNode, VARIABLE)
			.orElseThrow(() -> new RDFHandlerException("missing variable name for binding " + bindingNode));
	Value value = Models.getProperty(graph, bindingNode, VALUE)
			.orElseThrow(() -> new RDFHandlerException("missing variable value for binding " + bindingNode));
	return new SimpleBinding(name.getLabel(), value);
}
 
Example 13
Source File: DateTimeWithinPeriod.java    From rya with Apache License 2.0 5 votes vote down vote up
private Instant convertToInstant(Literal literal) {
    String stringVal = literal.getLabel();
    IRI dataType = literal.getDatatype();
    checkArgument(dataType.equals(XMLSchema.DATETIME) || dataType.equals(XMLSchema.DATE),
            String.format("Invalid data type for date time. Data Type must be of type %s or %s .", XMLSchema.DATETIME, XMLSchema.DATE));
    checkArgument(XMLDatatypeUtil.isValidDateTime(stringVal) || XMLDatatypeUtil.isValidDate(stringVal), "Invalid date time value.");
    return literal.calendarValue().toGregorianCalendar().toInstant();
}
 
Example 14
Source File: SpinxFunction.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	Bindings bindings = scriptEngine.createBindings();
	for (int i = 0; i < args.length; i++) {
		Argument argument = arguments.get(i);
		Value arg = args[i];
		Object jsArg;
		if (arg instanceof Literal) {
			Literal argLiteral = (Literal) arg;
			if (XMLSchema.INTEGER.equals(argLiteral.getDatatype())) {
				jsArg = argLiteral.intValue();
			} else if (XMLSchema.DECIMAL.equals(argLiteral.getDatatype())) {
				jsArg = argLiteral.doubleValue();
			} else {
				jsArg = argLiteral.getLabel();
			}
		} else {
			jsArg = arg.stringValue();
		}
		bindings.put(argument.getPredicate().getLocalName(), jsArg);
	}

	Object result;
	try {
		if (compiledScript == null && scriptEngine instanceof Compilable) {
			compiledScript = ((Compilable) scriptEngine).compile(script);
		}
		if (compiledScript != null) {
			result = compiledScript.eval(bindings);
		} else {
			result = scriptEngine.eval(script, bindings);
		}
	} catch (ScriptException e) {
		throw new ValueExprEvaluationException(e);
	}

	ValueFactory vf = ValueFactoryImpl.getInstance();
	return (returnType != null) ? vf.createLiteral(result.toString(), returnType) : vf.createURI(result.toString());
}
 
Example 15
Source File: SpinSailConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String getHighestComment(Resource subj)
		throws QueryEvaluationException {
	String comment = null;
	try (CloseableIteration<? extends Literal, QueryEvaluationException> iter = TripleSources.getObjectLiterals(
			subj, RDFS.COMMENT, tripleSource)) {
		while (iter.hasNext()) {
			Literal l = iter.next();
			String label = l.getLabel();
			if ((comment != null && label.compareTo(comment) > 0) || (comment == null)) {
				comment = label;
			}
		}
	}
	return comment;
}
 
Example 16
Source File: PeriodicQueryUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
private static double parseTemporalDuration(ValueConstant valConst) {
    Value val = valConst.getValue();
    Preconditions.checkArgument(val instanceof Literal);
    Literal literal = (Literal) val;
    String stringVal = literal.getLabel();
    IRI dataType = literal.getDatatype();
    Preconditions.checkArgument(dataType.equals(XMLSchema.DECIMAL) || dataType.equals(XMLSchema.DOUBLE)
            || dataType.equals(XMLSchema.FLOAT) || dataType.equals(XMLSchema.INTEGER) || dataType.equals(XMLSchema.INT));
    return Double.parseDouble(stringVal);
}
 
Example 17
Source File: BinaryRDFWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void writeLiteral(Literal literal) throws IOException {
	String label = literal.getLabel();
	IRI datatype = literal.getDatatype();

	if (Literals.isLanguageLiteral(literal)) {
		out.writeByte(LANG_LITERAL_VALUE);
		writeString(label);
		writeString(literal.getLanguage().get());
	} else {
		out.writeByte(DATATYPE_LITERAL_VALUE);
		writeString(label);
		writeString(datatype.toString());
	}
}
 
Example 18
Source File: StrBefore.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@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 19
Source File: TurtleWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void writeLiteral(Literal lit) throws IOException {
	String label = lit.getLabel();
	IRI datatype = lit.getDatatype();

	if (prettyPrint) {
		if (XMLSchema.INTEGER.equals(datatype) || XMLSchema.DECIMAL.equals(datatype)
				|| XMLSchema.DOUBLE.equals(datatype) || XMLSchema.BOOLEAN.equals(datatype)) {
			try {
				String normalized = XMLDatatypeUtil.normalize(label, datatype);
				if (!normalized.equals(XMLDatatypeUtil.POSITIVE_INFINITY)
						&& !normalized.equals(XMLDatatypeUtil.NEGATIVE_INFINITY)
						&& !normalized.equals(XMLDatatypeUtil.NaN)) {
					writer.write(normalized);
					return; // done
				}
			} catch (IllegalArgumentException e) {
				// not a valid numeric typed literal. ignore error and write
				// as
				// quoted string instead.
			}
		}
	}

	if (label.indexOf('\n') != -1 || label.indexOf('\r') != -1 || label.indexOf('\t') != -1) {
		// Write label as long string
		writer.write("\"\"\"");
		writer.write(TurtleUtil.encodeLongString(label));
		writer.write("\"\"\"");
	} else {
		// Write label as normal string
		writer.write("\"");
		writer.write(TurtleUtil.encodeString(label));
		writer.write("\"");
	}

	if (Literals.isLanguageLiteral(lit)) {
		// Append the literal's language
		writer.write("@");
		writer.write(lit.getLanguage().get());
	} else if (!xsdStringToPlainLiteral || !XMLSchema.STRING.equals(datatype)) {
		// Append the literal's datatype (possibly written as an abbreviated
		// URI)
		writer.write("^^");
		writeURI(datatype);
	}
}
 
Example 20
Source File: ParseDate.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected Value evaluate(ValueFactory valueFactory, Value arg1, Value arg2) throws ValueExprEvaluationException {
	if (!(arg1 instanceof Literal) || !(arg2 instanceof Literal)) {
		throw new ValueExprEvaluationException("Both arguments must be literals");
	}
	Literal value = (Literal) arg1;
	Literal format = (Literal) arg2;

	FieldAwareGregorianCalendar cal = new FieldAwareGregorianCalendar();

	SimpleDateFormat formatter = new SimpleDateFormat(format.getLabel());
	formatter.setCalendar(cal);
	try {
		formatter.parse(value.getLabel());
	} catch (ParseException e) {
		throw new ValueExprEvaluationException(e);
	}

	XMLGregorianCalendar xmlCal = datatypeFactory.newXMLGregorianCalendar(cal);
	if (!cal.isDateSet()) {
		xmlCal.setYear(DatatypeConstants.FIELD_UNDEFINED);
		xmlCal.setMonth(DatatypeConstants.FIELD_UNDEFINED);
		xmlCal.setDay(DatatypeConstants.FIELD_UNDEFINED);
	}
	if (!cal.isTimeSet()) {
		xmlCal.setHour(DatatypeConstants.FIELD_UNDEFINED);
		xmlCal.setMinute(DatatypeConstants.FIELD_UNDEFINED);
		xmlCal.setSecond(DatatypeConstants.FIELD_UNDEFINED);
	}
	if (!cal.isMillisecondSet()) {
		xmlCal.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
	}

	String dateValue = xmlCal.toXMLFormat();
	QName dateType = xmlCal.getXMLSchemaType();
	if (!cal.isTimezoneSet()) {
		int len = dateValue.length();
		if (dateValue.endsWith("Z")) {
			dateValue = dateValue.substring(0, len - 1);
		} else if (dateValue.charAt(len - 6) == '+' || dateValue.charAt(len - 6) == '-') {
			dateValue = dateValue.substring(0, len - 6);
		}
	}

	return valueFactory.createLiteral(dateValue, XMLDatatypeUtil.qnameToURI(dateType));
}