Java Code Examples for org.apache.jena.rdf.model.RDFNode#isLiteral()

The following examples show how to use org.apache.jena.rdf.model.RDFNode#isLiteral() . 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: PathEvaluator.java    From shacl with Apache License 2.0 6 votes vote down vote up
private ExtendedIterator<RDFNode> evalFocusNode(RDFNode focusNode, NodeExpressionContext context) {
	if(jenaPath == null) {
		if(focusNode.isLiteral()) {
			return WrappedIterator.emptyIterator();
		}
		else {
			return context.getDataset().getDefaultModel().listObjectsOfProperty((Resource)focusNode, predicate);
		}
	}
	else if(isInverse) {
		return context.getDataset().getDefaultModel().listSubjectsWithProperty(predicate, focusNode).mapWith(r -> (RDFNode)r);
	}
	else {
		// This ought to do lazy evaluation too
		List<RDFNode> results = new LinkedList<>();
		SHACLPaths.addValueNodes(focusNode.inModel(context.getDataset().getDefaultModel()), jenaPath, results);
		return WrappedIterator.create(results.iterator());
	}
}
 
Example 2
Source File: ModelContainer.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
String getValueOfDataProperty(RDFNode subject, String predicateURI, Map<String, Object> args) {

        final NodeIterator iterator = this.model.listObjectsOfProperty(subject.asResource(), getPropertyFromUri(predicateURI));
        while (iterator.hasNext()) {

            final RDFNode data = iterator.next();
            if (data.isLiteral()) {

                if (args.containsKey("lang")
                        && args.get("lang").toString().equalsIgnoreCase(data.asLiteral().getLanguage())) {
                    return data.asLiteral().getString();
                } else {
                    return data.asLiteral().getString();
                }
            }
        }
        return null;
    }
 
Example 3
Source File: ModelContainer.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
List<String> getValuesOfDataProperty(RDFNode subject, String predicateURI, Map<String, Object> args) {

        final List<String> valList = new ArrayList<>();

        final NodeIterator iterator = model.listObjectsOfProperty(subject.asResource(), getPropertyFromUri(predicateURI));

        while (iterator.hasNext()) {

            RDFNode data = iterator.next();

            if (data.isLiteral()) {
                if (!args.containsKey("lang") || args.get("lang").toString().equalsIgnoreCase(data.asLiteral().getLanguage())) {
                        valList.add(data.asLiteral().getString());
                }
            }
        }
        return valList;
    }
 
Example 4
Source File: NodeFormatter.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
public static String formatNode(RDFNode node) {
    if (node.isURIResource()) {
        return "<" + node.asResource().getURI().trim().replace(" ", "") + ">";
    }
    if (node.isLiteral()){
        Literal value = node.asLiteral();
        String formattedValue = "\"" + value.getLexicalForm() + "\"";
        if (!value.getLanguage().isEmpty()) {
            formattedValue += "@" + value.getLanguage() ;
        }
        if (!value.getDatatypeURI().isEmpty()
                && !value.getDatatypeURI().endsWith("langString")
                && !value.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) {
            formattedValue += "^^<" + value.getDatatypeURI() + ">" ;
        }

        return  formattedValue;
    }
    throw new IllegalArgumentException("cannot support blank nodes as targets");
}
 
Example 5
Source File: GroupConcatExpression.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public ExtendedIterator<RDFNode> eval(RDFNode focusNode, NodeExpressionContext context) {
	StringBuffer sb = new StringBuffer();
	ExtendedIterator<RDFNode> it = evalInput(focusNode, context);
	while(it.hasNext()) {
		RDFNode node = it.next();
		if(node.isLiteral() && XSDDatatype.XSDstring.getURI().equals(node.asNode().getLiteralDatatypeURI())) {
			sb.append(node.asNode().getLiteralLexicalForm());
		}
		else {
			String label = RDFLabels.get().getNodeLabel(node);
			if(label != null) {
				sb.append(label);
			}
		}
		if(separator != null && it.hasNext()) {
			sb.append(separator);
		}
	}
	List<RDFNode> results = Collections.singletonList(ResourceFactory.createTypedLiteral(sb.toString()));
	return WrappedIterator.create(results.iterator());
}
 
Example 6
Source File: ModelContainer.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
List<String> getValuesOfDataProperty(RDFNode subject, String predicateURI, Map<String, Object> args) {

        List<String> valList = new ArrayList<>();

        NodeIterator iterator = this.model.listObjectsOfProperty(subject.asResource(), getPropertyFromUri(predicateURI));

        while (iterator.hasNext()) {

            RDFNode data = iterator.next();

            if (data.isLiteral()) {
                if (args.containsKey("lang")) {
                    if (data.asLiteral().getLanguage().equals(args.get("lang").toString())) {
                        valList.add(data.asLiteral().getString());
                    }
                } else {
                    valList.add(data.asLiteral().getString());
                }
            }
        }
        return valList;
    }
 
Example 7
Source File: DatatypeConstraintExecutor.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void validate(Constraint constraint, ValidationEngine engine, String message, String datatypeURI, RDFDatatype datatype, RDFNode focusNode, RDFNode valueNode) {
	if(!valueNode.isLiteral() || !datatypeURI.equals(valueNode.asNode().getLiteralDatatypeURI()) || !datatype.isValid(valueNode.asNode().getLiteralLexicalForm())) {

		// TBS-1629: Ignore violations of mapped datatypes, e.g. actual literal is xsd:integer and sh:datatype is xsd:nonNegativeInteger
		if(valueNode.isLiteral() && !datatypeURI.equals(valueNode.asNode().getLiteralDatatypeURI()) && datatype.isValid(valueNode.asNode().getLiteralLexicalForm())) {
			if(isTDB1(focusNode.getModel().getGraph())) {
				RDFDatatype tdbType = tdbTypes.get(datatype);
				if(valueNode.asNode().getLiteralDatatype().equals(tdbType)) {
					return; // Do nothing
				}
			}
		}
		
		engine.createValidationResult(constraint, focusNode, valueNode, () -> message);
	}
}
 
Example 8
Source File: LanguageInConstraintExecutor.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public void executeConstraint(Constraint constraint, ValidationEngine engine, Collection<RDFNode> focusNodes) {
	long startTime = System.currentTimeMillis();
	for(RDFNode focusNode : focusNodes) {
		for(RDFNode valueNode : engine.getValueNodes(constraint, focusNode)) {
			if(!valueNode.isLiteral()) {					
				engine.createValidationResult(constraint, focusNode, valueNode, () -> "Not a literal");
			}
			else {
				String lang = valueNode.asLiteral().getLanguage();
				if(lang.isEmpty()) {
					if(!langs.contains(lang)) {							
						engine.createValidationResult(constraint, focusNode, valueNode, () -> "Value without language tag");					
					}
				}
				else if(!langMatches(lang)) {
					engine.createValidationResult(constraint, focusNode, valueNode, () -> "Value does not have a matching language tag");					
				}
			}
		}
		engine.checkCanceled();
	}
	addStatistics(constraint, startTime);
}
 
Example 9
Source File: ClassConstraintExecutor.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void validate(Constraint constraint, ValidationEngine engine, Resource classNode, RDFNode focusNode, RDFNode valueNode) {
	if(valueNode.isLiteral()) {
		engine.createValidationResult(constraint, focusNode, valueNode, () -> "Value must be an instance of " + engine.getLabel(classNode));			
	}
	else {			
		ClassesCache cache = engine.getClassesCache();
		if(cache != null) {
			Predicate<Resource> pred = cache.getPredicate(classNode.inModel(valueNode.getModel()));
			if(!pred.test((Resource)valueNode)) {
				engine.createValidationResult(constraint, focusNode, valueNode, () -> "Value must be an instance of " + engine.getLabel(classNode));
			}
		}
		else if(!JenaUtil.hasIndirectType((Resource)valueNode, classNode)) {
			// No cache: possibly walk superclasses for each call
			engine.createValidationResult(constraint, focusNode, valueNode, () -> "Value must be an instance of " + engine.getLabel(classNode));
		}
	}
}
 
Example 10
Source File: RDFLabels.java    From shacl with Apache License 2.0 5 votes vote down vote up
public String getNodeLabel(RDFNode node) {
	if(node.isLiteral()) {
		return node.asNode().getLiteralLexicalForm();
	}
	else {
		return getLabel((Resource)node);
	}
}
 
Example 11
Source File: FunctionTestCaseType.java    From shacl with Apache License 2.0 5 votes vote down vote up
private Graph parseGraph(RDFNode node) {
	Model model = JenaUtil.createDefaultModel();
	if(node.isLiteral()) {
		String str = node.asLiteral().getLexicalForm();
		model.read(new ByteArrayInputStream(str.getBytes()), "urn:x:dummy", FileUtils.langTurtle);
	}
	return model.getGraph();
}
 
Example 12
Source File: RDFToManifest.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
private List<Agent> getAgents(URI base, Individual in,
		ObjectProperty property) {
	List<Agent> creators = new ArrayList<>();
	for (Individual agent : listObjectProperties(in, property)) {
		Agent a = new Agent();

		// Check for any ORCIDs, note that "orcid" is mapped as
		// prov:alternateOf in our modified bundle.jsonld
		for (Individual alternate : listObjectProperties(agent, prov.alternateOf)) {
			if (alternate.isURIResource() && (
					alternate.getURI().startsWith("https://orcid.org/") ||
					alternate.getURI().startsWith("http://orcid.org/"))) {
				// TODO: Check against https://support.orcid.org/knowledgebase/articles/116780-structure-of-the-orcid-identifier
				a.setOrcid(URI.create(alternate.getURI()));
				break;
			}
		}
		if (agent.isURIResource()) {
			URI agentURI = relativizeFromBase(agent.getURI(), base);
			if ("orcid.org".equals(agentURI.getHost()) && a.getOrcid() == null) {
				a.setOrcid(agentURI);
			} else {
				a.setUri(agentURI);
			}
		}

		RDFNode name = agent.getPropertyValue(foaf.name);
		if (name != null && name.isLiteral())
			a.setName(name.asLiteral().getLexicalForm());
		creators.add(a);
	}
	return creators;
}
 
Example 13
Source File: AbstractLengthConstraintExecutor.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void validate(Constraint constraint, ValidationEngine engine, String message, int length, RDFNode focusNode, RDFNode valueNode) {
	if(valueNode.isAnon() || 
			(valueNode.isURIResource() && isInvalidLength(valueNode.asNode().getURI().length(), length)) || 
			(valueNode.isLiteral() && isInvalidLength(valueNode.asNode().getLiteralLexicalForm().length(), length))) {
		engine.createValidationResult(constraint, focusNode, valueNode, () -> message);
	}
}
 
Example 14
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static Literal getBestStringLiteral(Resource resource, List<String> langs, Iterable<Property> properties, BiFunction<Resource,Property,Iterator<Statement>> getter) {
	Literal label = null;
	int bestLang = -1;
	for(Property predicate : properties) {
		Iterator<Statement> it = getter.apply(resource, predicate);
		while(it.hasNext()) {
			RDFNode object = it.next().getObject();
			if(object.isLiteral()) {
				Literal literal = (Literal)object;
				String lang = literal.getLanguage();
				if(lang.length() == 0 && label == null) {
					label = literal;
				}
				else {
					// 1) Never use a less suitable language
					// 2) Never replace an already existing label (esp: skos:prefLabel) unless new lang is better
					// 3) Fall back to more special languages if no other was found (e.g. use en-GB if only "en" is accepted)
					int startLang = bestLang < 0 ? langs.size() - 1 : (label != null ? bestLang - 1 : bestLang);
					for(int i = startLang; i >= 0; i--) {
						String langi = langs.get(i);
						if(langi.equals(lang)) {
							label = literal;
							bestLang = i;
						}
						else if(lang.contains("-") && NodeFunctions.langMatches(lang, langi) && label == null) {
							label = literal;
						}
					}
				}
			}
		}
	}
	return label;
}
 
Example 15
Source File: LexicalMatcherAlphaImpl.java    From FCA-Map with GNU General Public License v3.0 5 votes vote down vote up
private static Set<String> acquireAllLiteralsLexicalFormsWith(Resource resource, Property property) {
  Set<String> s = new HashSet<>();
  for (StmtIterator it = resource.listProperties(property); it.hasNext(); ) {
    Statement stmt = it.nextStatement();
    RDFNode object = stmt.getObject();

    if (!object.isLiteral()) continue;

    String lb = object.asLiteral().getString();
    if (lb != null && !lb.isEmpty() && !lb.trim().equals("")) {
      s.add(lb);
    }
  }
  return s;
}
 
Example 16
Source File: TemplateImpl.java    From Processor with Apache License 2.0 5 votes vote down vote up
protected List<Locale> getLanguages(Property property)
{
    if (property == null) throw new IllegalArgumentException("Property cannot be null");
    
    List<Locale> languages = new ArrayList<>();
    Resource langs = getPropertyResourceValue(property);
    if (langs != null)
    {
        if (!langs.canAs(RDFList.class))
        {
            if (log.isErrorEnabled()) log.error("ldt:lang value is not an rdf:List on template '{}'", getURI());
            throw new OntologyException("ldt:lang value is not an rdf:List on template  '" + getURI() +"'");
        }

        // could use list order as priority (quality value q=)
        RDFList list = langs.as(RDFList.class);
        ExtendedIterator<RDFNode> it = list.iterator();
        try
        {
            while (it.hasNext())
            {
                RDFNode langTag = it.next();
                if (!langTag.isLiteral())
                {
                    if (log.isErrorEnabled()) log.error("Non-literal language tag (ldt:lang member) on template '{}'", getURI());
                    throw new OntologyException("Non-literal language tag (ldt:lang member) on template '" + getURI() +"'");
                }

                languages.add(Locale.forLanguageTag(langTag.asLiteral().getString()));
            }
        }
        finally
        {
            it.close();
        }
    }
    
    return languages;
}
 
Example 17
Source File: ModelContainer.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
RDFNode getValueOfObjectProperty(RDFNode subject, String predicateURI, String targetURI) {

        NodeIterator iterator = this.model.listObjectsOfProperty(subject.asResource(), getPropertyFromUri(predicateURI));
        while (iterator.hasNext()) {

            RDFNode next = iterator.next();
            if (!next.isLiteral()) {
                if (targetURI != null && this.model.contains(next.asResource(), getPropertyFromUri(HGQLVocabulary.RDF_TYPE), getResourceFromUri(targetURI))) {
                    return next;
                }
            }
        }
        return null;
    }
 
Example 18
Source File: SPARQLDataReader.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void getMetaData(RDFNode rdfNode, IFieldMetaData fieldMeta) {
	if (rdfNode.isLiteral()) {
		Literal literal = (Literal) rdfNode;
		Class classType = getClassType(literal);
		fieldMeta.setType(classType);
		FieldType type = getDefaultFieldType(literal);
		fieldMeta.setFieldType(type);
	} else if (rdfNode.isResource()) {
		fieldMeta.setType(String.class);
		fieldMeta.setFieldType(FieldType.ATTRIBUTE);
	}
}
 
Example 19
Source File: LexicalMatcherImpl.java    From FCA-Map with GNU General Public License v3.0 5 votes vote down vote up
private <T extends Resource> Set<String> getAllLiteralString(T r, Property property) {
  Set<String> literalStrings = new HashSet<>();
  for (StmtIterator it = r.listProperties(property); it.hasNext(); ) {
    Statement stmt = it.nextStatement();
    RDFNode obj = stmt.getObject();
    if (!obj.isLiteral()) continue;
    String ls = obj.asLiteral().getLexicalForm();
    if (null != ls && !ls.isEmpty()) {
      literalStrings.add(ls);
    }
  }
  return literalStrings;
}
 
Example 20
Source File: RDF2CSV.java    From IGUANA with GNU Affero General Public License v3.0 4 votes vote down vote up
private static String getValueOfNode(RDFNode rdfNode) {
	if(rdfNode.isLiteral()) {
		return rdfNode.asLiteral().getValue().toString();
	}
	return rdfNode.asResource().getURI().replace("http://iguana-benchmark.eu/resource/", "").replace("http://iguana-benchmark.eu/properties/", "");
}