use of org.eclipse.rdf4j.model.Literal in project rdf4j by eclipse.
the class RDFXMLParser method processPropertyElt.
private void processPropertyElt(String namespaceURI, String localName, String qName, Atts atts, boolean isEmptyElt) throws RDFParseException, RDFHandlerException {
if (getParserConfig().get(XMLParserSettings.FAIL_ON_NON_STANDARD_ATTRIBUTES)) {
checkPropertyEltName(namespaceURI, localName, qName, XMLParserSettings.FAIL_ON_NON_STANDARD_ATTRIBUTES);
}
// Get the URI of the property
IRI propURI = null;
if (namespaceURI.equals("")) {
// no namespace URI
reportError("unqualified property element <" + qName + "> not allowed", XMLParserSettings.FAIL_ON_INVALID_QNAME);
// Use base URI as namespace:
propURI = buildResourceFromLocalName(localName);
} else {
propURI = createURI(namespaceURI + localName);
}
// List expansion rule
if (propURI.equals(RDF.LI)) {
NodeElement subject = (NodeElement) peekStack(0);
propURI = createURI(RDF.NAMESPACE + "_" + subject.getNextLiCounter());
}
// Push the property on the stack.
PropertyElement predicate = new PropertyElement(propURI);
elementStack.push(predicate);
// Check if property has a reification ID
Att id = atts.removeAtt(RDF.NAMESPACE, "ID");
if (id != null) {
IRI reifURI = buildURIFromID(id.getValue());
predicate.setReificationURI(reifURI);
}
// Check for presence of rdf:parseType attribute
Att parseType = atts.removeAtt(RDF.NAMESPACE, "parseType");
if (parseType != null) {
if (getParserConfig().get(XMLParserSettings.FAIL_ON_NON_STANDARD_ATTRIBUTES)) {
checkNoMoreAtts(atts);
}
String parseTypeValue = parseType.getValue();
if (parseTypeValue.equals("Resource")) {
Resource objectResource = createNode();
NodeElement subject = (NodeElement) peekStack(1);
reportStatement(subject.getResource(), propURI, objectResource);
if (isEmptyElt) {
handleReification(objectResource);
} else {
NodeElement object = new NodeElement(objectResource);
object.setIsVolatile(true);
elementStack.push(object);
}
} else if (parseTypeValue.equals("Collection")) {
if (isEmptyElt) {
NodeElement subject = (NodeElement) peekStack(1);
reportStatement(subject.getResource(), propURI, RDF.NIL);
handleReification(RDF.NIL);
} else {
predicate.setParseCollection(true);
}
} else {
// other parseType
if (!parseTypeValue.equals("Literal")) {
reportWarning("unknown parseType: " + parseType.getValue());
}
if (isEmptyElt) {
NodeElement subject = (NodeElement) peekStack(1);
Literal lit = createLiteral("", null, RDF.XMLLITERAL);
reportStatement(subject.getResource(), propURI, lit);
handleReification(lit);
} else {
// The next string is an rdf:XMLLiteral
predicate.setDatatype(RDF.XMLLITERAL);
saxFilter.setParseLiteralMode();
}
}
} else // parseType == null
if (isEmptyElt) {
// empty element without an rdf:parseType attribute
// Note: we handle rdf:datatype attributes here to allow datatyped
// empty strings in documents. The current spec does have a
// production rule that matches this, which is likely to be an
// omission on its part.
Att datatype = atts.getAtt(RDF.NAMESPACE, "datatype");
if (atts.size() == 0 || atts.size() == 1 && datatype != null) {
// element had no attributes, or only the optional
// rdf:ID and/or rdf:datatype attributes.
NodeElement subject = (NodeElement) peekStack(1);
IRI dtURI = null;
if (datatype != null) {
dtURI = createURI(datatype.getValue());
}
Literal lit = createLiteral("", xmlLang, dtURI);
reportStatement(subject.getResource(), propURI, lit);
handleReification(lit);
} else {
// Create resource for the statement's object.
Resource resourceRes = getPropertyResource(atts);
// All special rdf attributes have been checked/removed.
if (getParserConfig().get(XMLParserSettings.FAIL_ON_NON_STANDARD_ATTRIBUTES)) {
checkRDFAtts(atts);
}
NodeElement resourceElt = new NodeElement(resourceRes);
NodeElement subject = (NodeElement) peekStack(1);
reportStatement(subject.getResource(), propURI, resourceRes);
handleReification(resourceRes);
Att type = atts.removeAtt(RDF.NAMESPACE, "type");
if (type != null) {
// rdf:type attribute, value is a URI-reference
IRI className = resolveURI(type.getValue());
reportStatement(resourceRes, RDF.TYPE, className);
}
processSubjectAtts(resourceElt, atts);
}
} else {
// Not an empty element, sub elements will follow.
// Check for rdf:datatype attribute
Att datatype = atts.removeAtt(RDF.NAMESPACE, "datatype");
if (datatype != null) {
IRI dtURI = resolveURI(datatype.getValue());
predicate.setDatatype(dtURI);
}
// No more attributes are expected.
if (getParserConfig().get(XMLParserSettings.FAIL_ON_NON_STANDARD_ATTRIBUTES)) {
checkNoMoreAtts(atts);
}
}
if (isEmptyElt) {
// Empty element has been pushed on the stack
// at the start of this method, remove it.
elementStack.pop();
}
}
use of org.eclipse.rdf4j.model.Literal in project rdf4j by eclipse.
the class RDFJSONWriter method writeObject.
/**
* Helper method to reduce complexity of the JSON serialisation algorithm Any null contexts will only be
* serialised to JSON if there are also non-null contexts in the contexts array
*
* @param object
* The RDF value to serialise
* @param contexts
* The set of contexts that are relevant to this object, including null contexts as they are found.
* @param jg
* the {@link JsonGenerator} to write to.
* @throws IOException
* @throws JsonGenerationException
* @throws JSONException
*/
public static void writeObject(final Value object, final Set<Resource> contexts, final JsonGenerator jg) throws JsonGenerationException, IOException {
jg.writeStartObject();
if (object instanceof Literal) {
jg.writeObjectField(RDFJSONUtility.VALUE, object.stringValue());
jg.writeObjectField(RDFJSONUtility.TYPE, RDFJSONUtility.LITERAL);
final Literal l = (Literal) object;
if (Literals.isLanguageLiteral(l)) {
jg.writeObjectField(RDFJSONUtility.LANG, l.getLanguage().orElse(null));
} else {
jg.writeObjectField(RDFJSONUtility.DATATYPE, l.getDatatype().stringValue());
}
} else if (object instanceof BNode) {
jg.writeObjectField(RDFJSONUtility.VALUE, resourceToString((BNode) object));
jg.writeObjectField(RDFJSONUtility.TYPE, RDFJSONUtility.BNODE);
} else if (object instanceof IRI) {
jg.writeObjectField(RDFJSONUtility.VALUE, resourceToString((IRI) object));
jg.writeObjectField(RDFJSONUtility.TYPE, RDFJSONUtility.URI);
}
if (contexts != null && !contexts.isEmpty() && !(contexts.size() == 1 && contexts.iterator().next() == null)) {
jg.writeArrayFieldStart(RDFJSONUtility.GRAPHS);
for (final Resource nextContext : contexts) {
if (nextContext == null) {
jg.writeNull();
} else {
jg.writeString(resourceToString(nextContext));
}
}
jg.writeEndArray();
}
jg.writeEndObject();
}
use of org.eclipse.rdf4j.model.Literal in project rdf4j by eclipse.
the class JSONLDInternalRDFParser method handleStatement.
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());
// rdf:langString
if (literal.getLanguage().isPresent() && datatype == null) {
datatype = RDF.LANGSTRING.stringValue();
}
// 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);
}
}
use of org.eclipse.rdf4j.model.Literal in project rdf4j by eclipse.
the class RDFParserHelper method createLiteral.
/**
* Create a literal using the given parameters, including iterative verification and normalization by any
* {@link DatatypeHandler} or {@link LanguageHandler} implementations that are found in the
* {@link ParserConfig}.
*
* @param label
* The value for {@link Literal#getLabel()}, which may be iteratively normalized.
* @param lang
* If this is not null, and the datatype is either not null, or is equal to {@link RDF#LANGSTRING},
* then a language literal will be created.
* @param datatype
* If datatype is not null, and the datatype is not equal to {@link RDF#LANGSTRING} with a non-null
* lang, then a datatype literal will be created.
* @param parserConfig
* The source of parser settings, including the desired list of {@link DatatypeHandler} and
* {@link LanguageHandler}s to use for verification and normalization of datatype and language
* literals respectively.
* @param errListener
* The {@link ParseErrorListener} to use for signalling errors. This will be called if a setting is
* enabled by setting it to true in the {@link ParserConfig}, after which the error may trigger an
* {@link RDFParseException} if the setting is not present in
* {@link ParserConfig#getNonFatalErrors()}.
* @param valueFactory
* The {@link ValueFactory} to use for creating new {@link Literal}s using this method.
* @param lineNo
* Optional line number, should default to setting this as -1 if not known. Used for
* {@link ParseErrorListener#error(String, long, long)} and for
* {@link RDFParseException#RDFParseException(String, long, long)}.
* @param columnNo
* Optional column number, should default to setting this as -1 if not known. Used for
* {@link ParseErrorListener#error(String, long, long)} and for
* {@link RDFParseException#RDFParseException(String, long, long)}.
* @return A {@link Literal} created based on the given parameters.
* @throws RDFParseException
* If there was an error during the process that could not be recovered from, based on settings in
* the given parser config.
*/
public static final Literal createLiteral(String label, String lang, IRI datatype, ParserConfig parserConfig, ParseErrorListener errListener, ValueFactory valueFactory, long lineNo, long columnNo) throws RDFParseException {
if (label == null) {
throw new NullPointerException("Cannot create a literal using a null label");
}
Literal result = null;
String workingLabel = label;
Optional<String> workingLang = Optional.ofNullable(lang);
IRI workingDatatype = datatype;
// non-null lang
if (workingLang.isPresent() && (workingDatatype == null || RDF.LANGSTRING.equals(workingDatatype))) {
boolean recognisedLanguage = false;
for (LanguageHandler nextHandler : parserConfig.get(BasicParserSettings.LANGUAGE_HANDLERS)) {
if (nextHandler.isRecognizedLanguage(workingLang.get())) {
recognisedLanguage = true;
if (parserConfig.get(BasicParserSettings.VERIFY_LANGUAGE_TAGS)) {
try {
if (!nextHandler.verifyLanguage(workingLabel, workingLang.get())) {
reportError("'" + lang + "' is not a valid language tag ", lineNo, columnNo, BasicParserSettings.VERIFY_LANGUAGE_TAGS, parserConfig, errListener);
}
} catch (LiteralUtilException e) {
reportError("'" + label + " could not be verified by a language handler that recognised it. language was " + lang, lineNo, columnNo, BasicParserSettings.VERIFY_LANGUAGE_TAGS, parserConfig, errListener);
}
}
if (parserConfig.get(BasicParserSettings.NORMALIZE_LANGUAGE_TAGS)) {
try {
result = nextHandler.normalizeLanguage(workingLabel, workingLang.get(), valueFactory);
workingLabel = result.getLabel();
workingLang = result.getLanguage();
workingDatatype = result.getDatatype();
} catch (LiteralUtilException e) {
reportError("'" + label + "' did not have a valid value for language " + lang + ": " + e.getMessage() + " and could not be normalised", lineNo, columnNo, BasicParserSettings.NORMALIZE_LANGUAGE_TAGS, parserConfig, errListener);
}
}
}
}
if (!recognisedLanguage) {
reportError("'" + label + "' was not recognised as a language literal, and could not be verified, with language " + lang, lineNo, columnNo, BasicParserSettings.FAIL_ON_UNKNOWN_LANGUAGES, parserConfig, errListener);
}
} else if (workingDatatype != null) {
boolean recognisedDatatype = false;
for (DatatypeHandler nextHandler : parserConfig.get(BasicParserSettings.DATATYPE_HANDLERS)) {
if (nextHandler.isRecognizedDatatype(workingDatatype)) {
recognisedDatatype = true;
if (parserConfig.get(BasicParserSettings.VERIFY_DATATYPE_VALUES)) {
try {
if (!nextHandler.verifyDatatype(workingLabel, workingDatatype)) {
reportError("'" + label + "' is not a valid value for datatype " + datatype, lineNo, columnNo, BasicParserSettings.VERIFY_DATATYPE_VALUES, parserConfig, errListener);
}
} catch (LiteralUtilException e) {
reportError("'" + label + " could not be verified by a datatype handler that recognised it. datatype was " + datatype, lineNo, columnNo, BasicParserSettings.VERIFY_DATATYPE_VALUES, parserConfig, errListener);
}
}
if (parserConfig.get(BasicParserSettings.NORMALIZE_DATATYPE_VALUES)) {
try {
result = nextHandler.normalizeDatatype(workingLabel, workingDatatype, valueFactory);
workingLabel = result.getLabel();
workingLang = result.getLanguage();
workingDatatype = result.getDatatype();
} catch (LiteralUtilException e) {
reportError("'" + label + "' is not a valid value for datatype " + datatype + ": " + e.getMessage() + " and could not be normalised", lineNo, columnNo, BasicParserSettings.NORMALIZE_DATATYPE_VALUES, parserConfig, errListener);
}
}
}
}
if (!recognisedDatatype) {
reportError("'" + label + "' was not recognised, and could not be verified, with datatype " + datatype, lineNo, columnNo, BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, parserConfig, errListener);
}
}
if (result == null) {
try {
// Backup for unnormalised language literal creation
if (workingLang.isPresent() && (workingDatatype == null || RDF.LANGSTRING.equals(workingDatatype))) {
result = valueFactory.createLiteral(workingLabel, workingLang.get().intern());
} else // Backup for unnormalised datatype literal creation
if (workingDatatype != null) {
result = valueFactory.createLiteral(workingLabel, workingDatatype);
} else {
result = valueFactory.createLiteral(workingLabel, XMLSchema.STRING);
}
} catch (Exception e) {
reportFatalError(e, lineNo, columnNo, errListener);
}
}
return result;
}
use of org.eclipse.rdf4j.model.Literal in project rdf4j by eclipse.
the class QueryStringUtilTest method testLanguageLiteral.
@Test
public void testLanguageLiteral() {
Literal literal = VF.createLiteral("lang \"literal\"", "en");
assertEquals("\"lang \\\"literal\\\"\"@en", QueryStringUtil.valueToString(literal));
assertEquals("\"lang \\\"literal\\\"\"@en", valueToStringWithStringBuilder(literal));
}
Aggregations