Java Code Examples for com.hp.hpl.jena.rdf.model.Property

The following are top voted examples for showing how to use com.hp.hpl.jena.rdf.model.Property. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: r2rml-kit   File: Message.java   Source Code and License 6 votes vote down vote up
/**
 * @param problem
 * @param subject May be null
 * @param predicates May be null
 * @param objects May be null
 */
public Message(Problem problem, Resource subject,
		Property[] predicates, RDFNode[] objects) {
	this.problem = problem;
	this.subject = subject;
	this.predicates = 
		predicates == null 
				? Collections.<Property>emptyList() 
				: Arrays.asList(predicates);
	Collections.sort(this.predicates, RDFComparator.getRDFNodeComparator());
	this.objects = 
		objects == null 
				? Collections.<RDFNode>emptyList() 
				: Arrays.asList(objects);
	Collections.sort(this.objects, RDFComparator.getRDFNodeComparator());
	this.detailCode = null;
	this.details = null;
	this.cause = null;
}
 
Example 2
Project: r2rml-kit   File: Message.java   Source Code and License 6 votes vote down vote up
/**
 * @param problem
 * @param term
 * @param detailCode Optional error code; indicates a subclass of problems
 * @param details Optional string containing error details
 * @param contextResource May be null
 * @param contextProperty May be null
 */
public Message(Problem problem, MappingTerm term, 
		String detailCode, String details, 
		Resource contextResource, Property contextProperty) {
	this.problem = problem;
	this.subject = contextResource; 
	this.predicates = 
		contextProperty == null 
				? Collections.<Property>emptyList() 
				: Collections.singletonList(contextProperty);
	this.objects = 
		term == null
				? Collections.<RDFNode>emptyList()
				: Collections.<RDFNode>singletonList(ResourceFactory.createPlainLiteral(term.toString()));
	this.detailCode = detailCode;
	this.details = details;
	this.cause = null;
}
 
Example 3
Project: c4a_data_repository   File: ClassMap.java   Source Code and License 6 votes vote down vote up
public void validate() throws D2RQException {
	assertHasBeenDefined(this.database, D2RQ.dataStorage, D2RQException.CLASSMAP_NO_DATABASE);
	assertHasPrimarySpec(new Property[]{
			D2RQ.uriColumn, D2RQ.uriPattern, D2RQ.uriSqlExpression, D2RQ.bNodeIdColumns, D2RQ.constantValue
	});
	if (this.constantValue != null && this.constantValue.isLiteral()) {
		throw new D2RQException(
				"d2rq:constantValue for class map " + toString() + " must be a URI or blank node", 
				D2RQException.CLASSMAP_INVALID_CONSTANTVALUE);
	}
	if (this.uriPattern != null && new Pattern(uriPattern).attributes().size() == 0) {
		this.log.warn(toString() + " has an uriPattern without any column specifications. This usually happens when no primary keys are defined for a table. If the configuration is left as is, all table rows will be mapped to a single instance. " +
				"If this is not what you want, please define the keys in the database and re-run the mapping generator, or edit the mapping to provide the relevant keys.");
	}
	for (PropertyBridge bridge: propertyBridges) {
		bridge.validate();
	}
	// TODO
}
 
Example 4
Project: r2rml-kit   File: DirectMappingStyle.java   Source Code and License 6 votes vote down vote up
public Property getForeignKeyProperty(TableName tableName, ForeignKey foreignKey) {
	StringBuffer result = new StringBuffer(baseIRI);
	result.append(encodeTableName(tableName));
	int i = 1;
	for (Identifier column: foreignKey.getLocalColumns().getColumns()) {
		String encoded = encodeColumnName(column);
		if (i == 1) {
			result.append("#ref-");
			result.append(encoded);
		} else {
			result.append(";" + encoded);
		}
		i++;
	}
	return model.createProperty(result.toString());
}
 
Example 5
Project: c4a_data_repository   File: VocabularySummarizer.java   Source Code and License 6 votes vote down vote up
public void assertNoUndefinedTerms(Model model, 
		int undefinedPropertyErrorCode, int undefinedClassErrorCode) {
	Collection<Property> unknownProperties = getUndefinedProperties(model);
	if (!unknownProperties.isEmpty()) {
		throw new D2RQException(
				"Unknown property " + PrettyPrinter.toString(
						unknownProperties.iterator().next()) + ", maybe a typo?",
				undefinedPropertyErrorCode);
	}
	Collection<Resource> unknownClasses = getUndefinedClasses(model);
	if (!unknownClasses.isEmpty()) {
		throw new D2RQException(
				"Unknown class " + PrettyPrinter.toString(
						unknownClasses.iterator().next()) + ", maybe a typo?",
				undefinedClassErrorCode);
	}
}
 
Example 6
Project: r2rml-kit   File: D2RQWriter.java   Source Code and License 6 votes vote down vote up
private void printTranslationTable(TranslationTable table) {
	printMapObject(table, D2RQ.TranslationTable);
	out.printURIProperty(D2RQ.href, table.getHref());
	out.printProperty(D2RQ.javaClass, table.getJavaClass());
	Iterator<Translation> it = table.getTranslations().iterator();
	List<Map<Property,RDFNode>> values = new ArrayList<Map<Property,RDFNode>>();
	while (it.hasNext()) {
		Translation translation = it.next();
		Map<Property,RDFNode> r = new LinkedHashMap<Property,RDFNode>();
		r.put(D2RQ.databaseValue, 
				ResourceFactory.createPlainLiteral(translation.dbValue()));
		r.put(D2RQ.rdfValue, 
				ResourceFactory.createPlainLiteral(translation.rdfValue()));
		values.add(r);
	}
	out.printCompactBlankNodeProperties(D2RQ.translation, values);
}
 
Example 7
Project: r2rml-kit   File: D2RQValidator.java   Source Code and License 6 votes vote down vote up
public void visit(DownloadMap downloadMap) {
	visitResourceMap(downloadMap);
	assertHasPrimarySpec(downloadMap, new Property[]{
			D2RQ.uriColumn, D2RQ.uriPattern, D2RQ.uriSqlExpression, D2RQ.constantValue
	});
	if (downloadMap.getDatabase() == null && downloadMap.getBelongsToClassMap() == null) {
		error("Download map " + downloadMap + " needs a d2rq:dataStorage (or d2rq:belongsToClassMap)", 
				D2RQException.DOWNLOADMAP_NO_DATASTORAGE);
	}
	assertNotNull(downloadMap.getContentDownloadColumn(), D2RQ.contentDownloadColumn, 
			D2RQException.DOWNLOADMAP_NO_CONTENTCOLUMN);
	if (downloadMap.getConstantValue() != null && !downloadMap.getConstantValue().isURIResource()) {
		error("d2rq:constantValue for download map " + downloadMap + " must be a URI", 
				D2RQException.RESOURCEMAP_INVALID_CONSTANTVALUE);
	}
	// Validate media type?
}
 
Example 8
Project: r2rml-kit   File: D2RQValidator.java   Source Code and License 6 votes vote down vote up
protected void assertHasPrimarySpec(ResourceMap resourceMap, Property[] allowedSpecs) {
	List<Property> definedSpecs = new ArrayList<Property>();
	for (Property allowedProperty: Arrays.asList(allowedSpecs)) {
		if (hasPrimarySpec(resourceMap, allowedProperty)) {
			definedSpecs.add(allowedProperty);
		}
	}
	if (definedSpecs.isEmpty()) {
		StringBuffer error = new StringBuffer(resourceMap.toString());
		error.append(" needs one of ");
		for (int i = 0; i < allowedSpecs.length; i++) {
			if (i > 0) {
				error.append(", ");
			}
			error.append(PrettyPrinter.toString(allowedSpecs[i]));
		}
		error(error.toString(), D2RQException.RESOURCEMAP_MISSING_PRIMARYSPEC);
	}
	if (definedSpecs.size() > 1) {
		error(resourceMap + " can't have both " +
				PrettyPrinter.toString((Property) definedSpecs.get(0)) +
				" and " +
				PrettyPrinter.toString((Property) definedSpecs.get(1)),
				D2RQException.RESOURCEMAP_DUPLICATE_PRIMARYSPEC);
	}
}
 
Example 9
Project: c4a_data_repository   File: DownloadMap.java   Source Code and License 6 votes vote down vote up
@Override
public void validate() throws D2RQException {
	assertHasPrimarySpec(new Property[]{
			D2RQ.uriColumn, D2RQ.uriPattern, D2RQ.constantValue
	});
	if (database == null && belongsToClassMap == null) {
		throw new D2RQException(
				"Download map " + toString() + " needs a d2rq:dataStorage (or d2rq:belongsToClassMap)", 
				D2RQException.DOWNLOADMAP_NO_DATASTORAGE);
	}
	assertHasBeenDefined(contentDownloadColumn, D2RQ.contentDownloadColumn, 
			D2RQException.DOWNLOADMAP_NO_CONTENTCOLUMN);
	if (this.constantValue != null && !this.constantValue.isURIResource()) {
		throw new D2RQException(
				"d2rq:constantValue for download map " + toString() + " must be a URI", 
				D2RQException.DOWNLOADMAP_INVALID_CONSTANTVALUE);
	}
	if (this.uriPattern != null && new Pattern(uriPattern).attributes().size() == 0) {
		log.warn(toString() + " has an uriPattern without any column specifications. This usually happens when no primary keys are defined for a table. If the configuration is left as is, all table rows will be mapped to a single instance. " +
				"If this is not what you want, please define the keys in the database and re-run the mapping generator, or edit the mapping to provide the relevant keys.");
	}
}
 
Example 10
Project: r2rml-kit   File: D2RQTarget.java   Source Code and License 6 votes vote down vote up
public void generateRefProperty(Property property, 
		TableName table, ForeignKey foreignKey) {
	IdentifierList localColumns = foreignKey.getLocalColumns();
	TableName referencedTable = foreignKey.getReferencedTable();
	PropertyBridge bridge = new PropertyBridge(
			getPropertyBridgeResource(table, localColumns));
	bridge.setBelongsToClassMap(getClassMap(table));
	bridge.addProperty(property);
	bridge.setRefersToClassMap(getClassMap(referencedTable));
	TableName target = referencedTable;
	if (referencedTable.equals(table)) {
		// Same-table join? Then we need to set up an alias for the table and join to that
		target = TableName.create(null, null, 
				Identifier.createDelimited( 
						Microsyntax.toString(referencedTable).replace('.', '_') + "__alias"));
		bridge.addAlias(new AliasDeclaration(referencedTable, target));
		foreignKey = new ForeignKey(foreignKey.getLocalColumns(), foreignKey.getReferencedColumns(), target);
	}
	for (Join join: Join.createFrom(table, foreignKey)) {
		bridge.addJoin(join);
	}
}
 
Example 11
Project: ontonethub   File: IndexingJob.java   Source Code and License 5 votes vote down vote up
private List<Statement> getUsage(Property property, Model model){
	
	List<Statement> stmts = new ArrayList<Statement>();
	String sparql = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
			+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
			+ "SELECT DISTINCT ?concept "
			+ "WHERE{"
			+ "  {<" + property.getURI() + "> rdfs:domain ?concept} "
			+ "  UNION "
			+ "  { "
			+ "    ?concept rdfs:subClassOf|owl:equivalentClass ?restriction . "
			+ "    ?restriction a owl:Restriction; "
			+ "      owl:onProperty <" + property.getURI() + "> "
			+ "  } "
			+ "}";
	Query query = QueryFactory.create(sparql, Syntax.syntaxARQ);
	QueryExecution queryExecution = QueryExecutionFactory.create(query, model);
	
	ResultSet resultSet = queryExecution.execSelect();
	while(resultSet.hasNext()){
		QuerySolution querySolution = resultSet.next();
		Resource concept = querySolution.getResource("concept");
		
		stmts.add(new StatementImpl(property, usage, concept));
	}
	
	return stmts;
	
}
 
Example 12
Project: c4a_data_repository   File: VocabularySummarizer.java   Source Code and License 5 votes vote down vote up
public Collection<Property> getUndefinedProperties(Model model) {
	Set<Property> result = new HashSet<Property>();
	StmtIterator it = model.listStatements();
	while (it.hasNext()) {
		Statement stmt = it.nextStatement();
		if (stmt.getPredicate().getURI().startsWith(namespace)
				&& !properties.contains(stmt.getPredicate())) {
			result.add(stmt.getPredicate());
		}
	}
	return result;
}
 
Example 13
Project: zebra-puzzle-workshop   File: Exercise31Test.java   Source Code and License 5 votes vote down vote up
@Test
public void testOsloHasMainLanguageNorwegian() {
  Individual oslo = exercise31.getIndividual("Oslo");
  Property mainLanguage = ResourceFactory.createProperty(Exercise3.NS, "hasMainLanguage");
  RDFNode norwegian = ResourceFactory.createResource(Exercise3.NS + "Norwegian");
  Assert.assertTrue(oslo.hasProperty(mainLanguage, norwegian));
}
 
Example 14
Project: r2rml-kit   File: PrettyTurtleWriter.java   Source Code and License 5 votes vote down vote up
public void printProperty(Property property, RDFNode term) {
	if (term == null) return;
	if (term.isResource()) {
		printPropertyTurtle(term != null, property, toTurtle(term.asResource()));
	} else {
		printPropertyTurtle(term != null, property, toTurtle(term.asLiteral()));
	}
}
 
Example 15
Project: c4a_data_repository   File: PropertyBridge.java   Source Code and License 5 votes vote down vote up
public void validate() throws D2RQException {
	if (this.refersToClassMap != null) {
		if (!this.refersToClassMap.database().equals(this.belongsToClassMap.database())) {
			throw new D2RQException(toString() + 
					" links two d2rq:ClassMaps with different d2rq:dataStorages",
					D2RQException.PROPERTYBRIDGE_CONFLICTING_DATABASES);
		}
		// TODO refersToClassMap cannot be combined w/ value constraints or translation tables
	}
	if (properties.isEmpty() && dynamicPropertyPatterns.isEmpty()) {
		throw new D2RQException(toString() + " needs a d2rq:property or d2rq:dynamicProperty",
				D2RQException.PROPERTYBRIDGE_MISSING_PREDICATESPEC);
	}
	assertHasPrimarySpec(new Property[]{
			D2RQ.uriColumn, D2RQ.uriPattern, D2RQ.bNodeIdColumns,
			D2RQ.column, D2RQ.pattern, D2RQ.sqlExpression, D2RQ.uriSqlExpression, D2RQ.constantValue,
			D2RQ.refersToClassMap
	});
	if (this.datatype != null && this.lang != null) {
		throw new D2RQException(toString() + " has both d2rq:datatype and d2rq:lang",
				D2RQException.PROPERTYBRIDGE_LANG_AND_DATATYPE);
	}
	if (this.datatype != null && this.column == null && this.pattern == null
			&& this.sqlExpression == null) {
		throw new D2RQException("d2rq:datatype can only be used with d2rq:column, d2rq:pattern " +
				"or d2rq:sqlExpression at " + this,
				D2RQException.PROPERTYBRIDGE_NONLITERAL_WITH_DATATYPE);
	}
	if (this.lang != null && this.column == null && this.pattern == null) {
		throw new D2RQException("d2rq:lang can only be used with d2rq:column, d2rq:pattern " +
				"or d2rq:sqlExpression at " + this,
				D2RQException.PROPERTYBRIDGE_NONLITERAL_WITH_LANG);
	}
}
 
Example 16
Project: r2rml-kit   File: PrettyTurtleWriter.java   Source Code and License 5 votes vote down vote up
public void printPropertyTurtle(boolean writeIt, Property property, String turtleSnippet) {
	if (!writeIt) return;
	printIndent();
	out.print(toTurtle(property));
	out.print(" ");
	out.print(turtleSnippet);
	out.print(";");
}
 
Example 17
Project: r2rml-kit   File: PrettyTurtleWriter.java   Source Code and License 5 votes vote down vote up
private String toTurtleCompact(Map<Property, RDFNode> resource) {
	if (resource.isEmpty()) return "[]";
	StringBuilder result = new StringBuilder("[ ");
	for (Property property: resource.keySet()) {
		result.append(toTurtle(property));
		result.append(" ");
		result.append(toTurtle(resource.get(property)));
		result.append("; ");
	}
	result.append("]");
	return result.toString();
}
 
Example 18
Project: c4a_data_repository   File: MapObject.java   Source Code and License 5 votes vote down vote up
protected void assertHasBeenDefined(Object object, Property property, int errorCode) {
	if (object != null) {
		return;
	}
	throw new D2RQException("Missing " + PrettyPrinter.toString(property) + 
			" for " + this, errorCode);
}
 
Example 19
Project: r2rml-kit   File: VocabularySummarizer.java   Source Code and License 5 votes vote down vote up
public Collection<Property> getUndefinedProperties(Model model) {
	Set<Property> result = new HashSet<Property>();
	StmtIterator it = model.listStatements();
	while (it.hasNext()) {
		Statement stmt = it.nextStatement();
		if (stmt.getPredicate().getURI().startsWith(namespace)
				&& !properties.contains(stmt.getPredicate())) {
			result.add(stmt.getPredicate());
		}
	}
	return result;
}
 
Example 20
Project: r2rml-kit   File: VocabularySummarizerTest.java   Source Code and License 5 votes vote down vote up
public void testFindOneUndefinedProperty() {
	final Model m = D2RQTestUtil.loadTurtle("vocab-summarizer/one-undefined-property.ttl");
	VocabularySummarizer vocab = new VocabularySummarizer(D2RQ.class);
	Collection<Property> expected = new HashSet<Property>() {{ 
		this.add(m.createProperty(D2RQ.NS + "price"));
	}};
	assertEquals(expected, vocab.getUndefinedProperties(m));
}
 
Example 21
Project: c4a_data_repository   File: DatasetDescriptionServlet.java   Source Code and License 5 votes vote down vote up
private static Set<Resource> generatePartitions(Model m, Resource type,
		Property p) {
	Set<Resource> partitions = new HashSet<Resource>();
	ResIterator classIt = m.listResourcesWithProperty(RDF.type, type);
	while (classIt.hasNext()) {
		Resource classMap = classIt.next();
		StmtIterator pIt = classMap.listProperties(p);
		while (pIt.hasNext()) {
			partitions.add((Resource) pIt.next().getObject());
		}
	}
	return partitions;
}
 
Example 22
Project: zebra-puzzle-workshop   File: Exercise2.java   Source Code and License 5 votes vote down vote up
private Model createModel() {
  Model model = ModelFactory.createDefaultModel();
  String NS = "http://www.computas.no/zebra/";
  model.setNsPrefix("", NS);
  model.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema#");
  Resource subject = model.createResource(NS + "Joe");
  Property predicate = model.createProperty(NS + "hasSentMessage");
  String object = "Hello World!";
  subject.addProperty(predicate, object, XSDDatatype.XSDstring);
  return model;
}
 
Example 23
Project: r2rml-kit   File: D2RQValidator.java   Source Code and License 5 votes vote down vote up
private boolean hasPrimarySpec(ResourceMap map, Property property) {
	if (property.equals(D2RQ.bNodeIdColumns)) return !map.getBNodeIdColumnsParsed().isEmpty();
	if (property.equals(D2RQ.uriColumn)) return map.getURIColumn() != null;
	if (property.equals(D2RQ.uriPattern)) return map.getURIPattern() != null;
	if (property.equals(D2RQ.uriSqlExpression)) return map.getUriSQLExpression() != null;
	if (property.equals(D2RQ.column)) return ((PropertyBridge) map).getColumn() != null;
	if (property.equals(D2RQ.pattern)) return ((PropertyBridge) map).getPattern() != null;
	if (property.equals(D2RQ.sqlExpression)) return ((PropertyBridge) map).getSQLExpression() != null;
	if (property.equals(D2RQ.refersToClassMap)) return ((PropertyBridge) map).getRefersToClassMap() != null;
	if (property.equals(D2RQ.constantValue)) return map.getConstantValue() != null;
	throw new IllegalArgumentException("Not a primary spec: " + property);
}
 
Example 24
Project: c4a_data_repository   File: Mapping.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to add definitions from a ResourceMap to its underlying resource
 * @param map
 * @param targetResource
 */
private void addDefinitions(ResourceMap map, Resource targetResource) {
	/* Infer rdfs:Class or rdf:Property type */
	Statement s = vocabularyModel.createStatement(targetResource, RDF.type, map instanceof ClassMap ? RDFS.Class : RDF.Property);
	if (!this.vocabularyModel.contains(s))
		this.vocabularyModel.add(s);
	
	/* Apply labels */
	for (Literal propertyLabel: map.getDefinitionLabels()) {
		s = vocabularyModel.createStatement(targetResource, RDFS.label, propertyLabel);
		if (!this.vocabularyModel.contains(s))
			this.vocabularyModel.add(s);
	}

	/* Apply comments */
	for (Literal propertyComment: map.getDefinitionComments()) {
		s = vocabularyModel.createStatement(targetResource, RDFS.comment, propertyComment);
		if (!this.vocabularyModel.contains(s))
			this.vocabularyModel.add(s);
	}
	
	/* Apply additional properties */
	for (Resource additionalProperty: map.getAdditionalDefinitionProperties()) {
		s = vocabularyModel.createStatement(targetResource, 
					(Property)(additionalProperty.getProperty(D2RQ.propertyName).getResource().as(Property.class)),
					additionalProperty.getProperty(D2RQ.propertyValue).getObject());
		if (!this.vocabularyModel.contains(s))
			this.vocabularyModel.add(s);				
	}
}
 
Example 25
Project: r2rml-kit   File: MapObject.java   Source Code and License 5 votes vote down vote up
protected void assertArgumentNotNull(Object object, Property property, int errorCode) {
	if (object != null) {
		return;
	}
	throw new D2RQException("Object for " + PrettyPrinter.toString(property) + 
			" not found at " + this, errorCode);
}
 
Example 26
Project: r2rml-kit   File: Mapping.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to add definitions from a ResourceMap to its underlying resource
 * @param map
 * @param targetResource
 */
private void addDefinitions(ResourceMap map, Resource targetResource) {
	/* Infer rdfs:Class or rdf:Property type */
	Statement s = vocabularyModel.createStatement(targetResource, RDF.type, map instanceof ClassMap ? RDFS.Class : RDF.Property);
	if (!this.vocabularyModel.contains(s))
		this.vocabularyModel.add(s);

	/* Apply labels */
	for (Literal propertyLabel: map.getDefinitionLabels()) {
		s = vocabularyModel.createStatement(targetResource, RDFS.label, propertyLabel);
		if (!this.vocabularyModel.contains(s))
			this.vocabularyModel.add(s);
	}

	/* Apply comments */
	for (Literal propertyComment: map.getDefinitionComments()) {
		s = vocabularyModel.createStatement(targetResource, RDFS.comment, propertyComment);
		if (!this.vocabularyModel.contains(s))
			this.vocabularyModel.add(s);
	}

	/* Apply additional properties */
	for (Resource additionalProperty: map.getAdditionalDefinitionProperties()) {
		s = vocabularyModel.createStatement(targetResource, 
					(Property)(additionalProperty.getProperty(D2RQ.propertyName).getResource().as(Property.class)),
					additionalProperty.getProperty(D2RQ.propertyValue).getObject());
		if (!this.vocabularyModel.contains(s))
			this.vocabularyModel.add(s);				
	}
}
 
Example 27
Project: r2rml-kit   File: ConflictChecker.java   Source Code and License 5 votes vote down vote up
public void add(Resource resource, Property property) {
	if (properties.get(resource) == null) {
		properties.put(resource, property);
	}
	if (!properties.get(resource).equals(property)) {
		report.report(Problem.CONFLICTING_PROPERTIES, 
				resource, new Property[]{properties.get(resource), property});
	}
}
 
Example 28
Project: r2rml-kit   File: MappingValidator.java   Source Code and License 5 votes vote down vote up
@Override
public void visitComponentProperty(Property property, Resource resource, 
		ComponentType... types) {
	validateComponentType(property, resource, types);
	propertyStack.push(property);
	resourceStack.push(resource);
	super.visitComponentProperty(property, resource, types);
	resourceStack.pop();
	propertyStack.pop();
}
 
Example 29
Project: r2rml-kit   File: MappingValidator.java   Source Code and License 5 votes vote down vote up
@Override
public void visitComponent(TriplesMap triplesMap) {
	require(triplesMap, RR.logicalTable);
	if (triplesMap.getSubject() == null && triplesMap.getSubjectMap() == null) {
		report.report(Problem.REQUIRED_VALUE_MISSING, 
				getContextResource(),
				new Property[]{RR.subject, RR.subjectMap});
	}
	if (triplesMap.getSubject() != null && triplesMap.getSubjectMap() != null) {
		report.report(Problem.CONFLICTING_PROPERTIES, 
				getContextResource(),
				new Property[]{RR.subject, RR.subjectMap});
	}
	contextLogicalTable = getLogicalTable(triplesMap);
}
 
Example 30
Project: c4a_data_repository   File: MapObject.java   Source Code and License 5 votes vote down vote up
protected void assertNotYetDefined(Object object, Property property, int errorCode) {
	if (object == null) {
		return;
	}
	throw new D2RQException("Duplicate " + PrettyPrinter.toString(property) + 
			" for " + this, errorCode);
}
 
Example 31
Project: c4a_data_repository   File: ModelAPITest.java   Source Code and License 5 votes vote down vote up
void dumpStatement(Statement stmt) {
	Resource  subject   = stmt.getSubject();
	Property  predicate = stmt.getPredicate();
	RDFNode   object    = stmt.getObject();
	System.out.print(subject + " " + predicate + " ");
	if (object instanceof Resource) {
		System.out.print(object);
	} else { // object is a literal
		System.out.print(" \"" + object + "\"");
	}
	System.out.println(" .");
}
 
Example 32
Project: r2rml-kit   File: MappingVisitor.java   Source Code and License 5 votes vote down vote up
public void visitTermProperty(Property property, MappingTerm term) {
	if (term == null) return;
	if (RR.subject.equals(property)) {
		((ConstantShortcut) term).acceptAs(this, Position.SUBJECT_MAP);
	} else if (RR.predicate.equals(property)) {
		((ConstantShortcut) term).acceptAs(this, Position.PREDICATE_MAP);
	} else if (RR.object.equals(property)) {
		((ConstantShortcut) term).acceptAs(this, Position.OBJECT_MAP);
	} else if (RR.graph.equals(property)) {
		((ConstantShortcut) term).acceptAs(this, Position.GRAPH_MAP);
	} else {
		term.accept(this);
	}
}
 
Example 33
Project: r2rml-kit   File: R2RMLReader.java   Source Code and License 5 votes vote down vote up
public Set<Resource> listResourcesWith(Property... properties) {
	Set<Resource> result = new HashSet<Resource>();
	for (Property property: properties) {
		ResIterator it = model.listResourcesWithProperty(property);
		while (it.hasNext()) {
			result.add(it.next());
		}
	}
	return result;
}
 
Example 34
Project: zebra-puzzle-workshop   File: Exercise33Jena.java   Source Code and License 5 votes vote down vote up
public Exercise33Jena() {
  ontModel = readModel(MODEL_INPUT_EX33_JENA);
  OntClass norwegianCity = ontModel.getOntClass(NS + "NorwegianCity");
  OntClass city = ontModel.getOntClass(NS + "City");
  RDFList intersectingClasses = ontModel.createList();
  intersectingClasses = intersectingClasses.with(city);
  Property hasMainLanguage = ontModel.getProperty(NS, "hasMainLanguage");
  Restriction hasMainLanguageRestriction = ontModel.createRestriction(hasMainLanguage);
  Resource norwegian = ontModel.getOntResource(NS + "Norwegian");
  hasMainLanguageRestriction.convertToHasValueRestriction(norwegian);
  intersectingClasses.add(hasMainLanguageRestriction);
  norwegianCity.getEquivalentClass().convertToIntersectionClass(intersectingClasses);
  individuals = getIndividuals(ontModel);
}
 
Example 35
Project: r2rml-kit   File: R2RMLReader.java   Source Code and License 5 votes vote down vote up
public List<Resource> getResources(Resource r, Property p, NodeType acceptableNodeTypes) {
	List<Resource> result = new ArrayList<Resource>();
	for (RDFNode node: getRDFNodes(r, p, acceptableNodeTypes)) {
		result.add(node.asResource());
	}
	return result;
}
 
Example 36
Project: phenopacket-reference-implementation   File: RdfReader.java   Source Code and License 5 votes vote down vote up
private static Property getProperty(String localName, Context context) {
	String expanded = null;
	try {
		if (localName.equals("types")) {
			expanded = RDF.type.getURI();
		} else {
			expanded = ContextUtil.expandIdentifierAsPropertyOrType(
					localName, context);
		}
	} catch (JsonLdError e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return ResourceFactory.createProperty(expanded);
}
 
Example 37
Project: r2rml-kit   File: R2RMLReader.java   Source Code and License 5 votes vote down vote up
public List<String> getStrings(Resource r, Property p) {
	List<String> result = new ArrayList<String>();
	for (RDFNode node: getRDFNodes(r, p, NodeType.STRING_LITERAL)) {
		result.add(node.asLiteral().getLexicalForm());
	}
	return result;
}
 
Example 38
Project: c4a_data_repository   File: VocabularySummarizer.java   Source Code and License 5 votes vote down vote up
private Set<Resource> findAllClasses() {
	Set<Resource> results = new HashSet<Resource>();
	for (int i = 0; i < vocabularyJavaClass.getFields().length; i++) {
		Field field = vocabularyJavaClass.getFields()[i];
		if (!Modifier.isStatic(field.getModifiers())) continue;
		if (!Resource.class.isAssignableFrom(field.getType())) continue;
		if (Property.class.isAssignableFrom(field.getType())) continue;
		try {
			results.add((Resource) field.get(null));
		} catch (IllegalAccessException ex) {
			throw new D2RQException(ex);
		}
	}
	return results;
}
 
Example 39
Project: r2rml-kit   File: R2RMLWriter.java   Source Code and License 5 votes vote down vote up
@Override
public void visitTermProperty(Property property, MappingTerm term) {
	if (term == null) return;
	if (term instanceof ConstantShortcut) {
		out.printProperty(property, ((ConstantShortcut) term).asRDFNode()); 
	} else if (term instanceof ConstantIRI) {
		out.printProperty(property, ((ConstantIRI) term).asResource()); 
	} else if (term instanceof SQLQuery) {
		out.printLongStringProperty(property, term.toString());
	} else {
		out.printProperty(property, term.toString());
	}
}
 
Example 40
Project: c4a_data_repository   File: VocabularySummarizer.java   Source Code and License 5 votes vote down vote up
private Set<Property> findAllProperties() {
	Set<Property> results = new HashSet<Property>();
	for (int i = 0; i < vocabularyJavaClass.getFields().length; i++) {
		Field field = vocabularyJavaClass.getFields()[i];
		if (!Modifier.isStatic(field.getModifiers())) continue;
		if (!Property.class.isAssignableFrom(field.getType())) continue;
		try {
			results.add((Property) field.get(null));
		} catch (IllegalAccessException ex) {
			throw new D2RQException(ex);
		}
	}
	return results;
}
 
Example 41
Project: r2rml-kit   File: OntologyTarget.java   Source Code and License 5 votes vote down vote up
public void generateColumnProperty(Property property, TableName table,
		Identifier column, DataType datatype) {
	Property p = property.inModel(model);
	p.addProperty(RDF.type, RDF.Property);
	p.addProperty(RDF.type, OWL.DatatypeProperty);
	p.addProperty(RDFS.label, getLabel(table, column));
	domains.put(p, table);
	if (datatype.rdfType() != null && XSD.xstring.getURI().equals(datatype.rdfType())) {
		p.addProperty(RDFS.range, model.getResource(datatype.rdfType()));
	}
	if (generatedOntology != null) {
		p.addProperty(RDFS.isDefinedBy, generatedOntology);
	}
}
 
Example 42
Project: r2rml-kit   File: OntologyTarget.java   Source Code and License 5 votes vote down vote up
public void generateRefProperty(Property property, TableName table,
		ForeignKey foreignKey) {
	Property p = property.inModel(model);
	p.addProperty(RDF.type, RDF.Property);
	p.addProperty(RDF.type, OWL.ObjectProperty);
	p.addProperty(RDFS.label, getLabel(table, foreignKey.getLocalColumns()));
	domains.put(p, table);
	ranges.put(p, foreignKey.getReferencedTable());
	if (generatedOntology != null) {
		p.addProperty(RDFS.isDefinedBy, generatedOntology);
	}
}
 
Example 43
Project: r2rml-kit   File: OntologyTarget.java   Source Code and License 5 votes vote down vote up
public void generateLinkProperty(Property property, TableName table,
		ForeignKey fk1, ForeignKey fk2) {
	Property p = property.inModel(model);
	p.addProperty(RDF.type, RDF.Property);
	p.addProperty(RDF.type, OWL.ObjectProperty);
	p.addProperty(RDFS.label, getLabel(table));
	domains.put(p, fk1.getReferencedTable());
	ranges.put(p, fk2.getReferencedTable());
	if (generatedOntology != null) {
		p.addProperty(RDFS.isDefinedBy, generatedOntology);
	}
}
 
Example 44
Project: BimSPARQL   File: SPINInferencesWithoutConstructor.java   Source Code and License 5 votes vote down vote up
/**
 * Checks if a given property is a SPIN rule property.
 * This is (currently) defined as a property that has type spin:RuleProperty
 * or is a sub-property of spin:rule.  The latter condition may be removed
 * at some later stage after people have upgraded to SPIN 1.1 conventions.
 * @param property  the property to check
 * @return true if property is a rule property
 */
public static boolean isRuleProperty(Property property) {
	if(SPIN.rule.equals(property)) {
		return true;
	}
	else if(JenaUtil.hasSuperProperty(property, property.getModel().getProperty(SPIN.rule.getURI()))) {
		return true;
	}
	else {
		return JenaUtil.hasIndirectType(property, SPIN.RuleProperty.inModel(property.getModel())); 
	}
}
 
Example 45
Project: r2rml-kit   File: R2RMLTarget.java   Source Code and License 5 votes vote down vote up
public void generateLinkProperty(Property property, TableName tableName,
		ForeignKey fk1, ForeignKey fk2) {
	TemplateValuedTermMap subjects = new TemplateValuedTermMap();
	incompleteLinkMaps.add(new IncompleteLinkMap(tableName, fk1, subjects));
	addTriplesMap(tableName, createBaseTableOrView(tableName), subjects);
	addPredicateObjectMap(tableName, 
			createPredicateObjectMap(property, 
					createRefObjectMap(tableName, fk2)));
}
 
Example 46
Project: zebra-puzzle-workshop   File: Exercise31Test.java   Source Code and License 5 votes vote down vote up
@Test
public void testOsloHasMainLanguageNorwegian() {
  Individual oslo = exercise31.getIndividual("Oslo");
  Property mainLanguage = ResourceFactory.createProperty(Exercise3.NS, "hasMainLanguage");
  RDFNode norwegian = ResourceFactory.createResource(Exercise3.NS + "Norwegian");
  Assert.assertTrue(oslo.hasProperty(mainLanguage, norwegian));
}
 
Example 47
Project: r2rml-kit   File: VocabularySummarizerTest.java   Source Code and License 5 votes vote down vote up
public void testFindTwoUndefinedProperties() {
	final Model m = D2RQTestUtil.loadTurtle("vocab-summarizer/two-undefined-properties.ttl");
	VocabularySummarizer vocab = new VocabularySummarizer(D2RQ.class);
	Collection<Property> expected = new HashSet<Property>() {{ 
		this.add(m.createProperty(D2RQ.NS + "price"));
		this.add(m.createProperty(D2RQ.NS + "parallelUniverse"));
	}};
	assertEquals(expected, vocab.getUndefinedProperties(m));
}
 
Example 48
Project: ontonethub   File: IndexingJob.java   Source Code and License 4 votes vote down vote up
private List<Statement> collapseAnnotations(Property property, Model model){
	
	List<Statement> stmts = new ArrayList<Statement>();
	
	Map<String, Map<String,Statement>> literalMap = new HashMap<String, Map<String,Statement>>();
	StmtIterator stmtIt = model.listStatements(null, property, (RDFNode) null);
	stmtIt.forEachRemaining(stmt -> {
		RDFNode obj = stmt.getObject();
		if(obj.isLiteral()){
			Literal lit = obj.asLiteral();
			String lang = lit.getLanguage();
			if(lang == null){
				lang = "null";
			}
			Map<String, Statement> stmtMap = literalMap.get(lang);
			if(stmtMap == null) {
				stmtMap = new HashMap<String, Statement>();
				literalMap.put(lang, stmtMap);
			}
			
			Statement statement = stmtMap.get(lang);
			boolean insert = false;
			if(statement == null) insert = true;
			else{
				String statementLF = ((Literal)statement.getObject()).getLexicalForm();
				String lexicalForm = lit.getLexicalForm();
				if(lexicalForm.length() > statementLF.length()) insert = true;
			}
				
				
			if(insert) stmtMap.put(lang, statement);
		}
		
	});
	
	model.removeAll(null, property, (RDFNode) null);
	
	literalMap.forEach((subject, stmtMap) -> {
		stmtMap.forEach((lang, stmt) -> {
			model.add(stmt);
		});
	});
	
	return stmts;
	
}
 
Example 49
Project: ontonethub   File: IndexingJob.java   Source Code and License 4 votes vote down vote up
private List<Statement> keepMaxLengthAnnotationsOnly(Property property, Model model){
	
	List<Statement> stmts = new ArrayList<Statement>();
	
	Map<Resource, Map<String,Statement>> literalMap = new HashMap<Resource, Map<String,Statement>>();
	StmtIterator stmtIt = model.listStatements(null, property, (RDFNode) null);
	stmtIt.forEachRemaining(stmt -> {
		Resource subj = stmt.getSubject();
		RDFNode obj = stmt.getObject();
		if(obj.isLiteral()){
			Literal lit = obj.asLiteral();
			String lang = lit.getLanguage();
			if(lang == null){
				lang = "null";
			}
			Map<String, Statement> stmtMap = literalMap.get(subj);
			if(stmtMap == null) {
				stmtMap = new HashMap<String, Statement>();
				literalMap.put(subj, stmtMap);
			}
			
			Statement statement = stmtMap.get(lang);
			boolean insert = false;
			if(statement == null) insert = true;
			else{
				String statementLF = ((Literal)statement.getObject()).getLexicalForm();
				String lexicalForm = lit.getLexicalForm();
				if(lexicalForm.length() > statementLF.length()) insert = true;
			}
				
				
			if(insert) stmtMap.put(lang, stmt);
		}
		
	});
	
	model.removeAll(null, property, (RDFNode) null);
	
	literalMap.forEach((subject, stmtMap) -> {
		stmtMap.forEach((lang, stmt) -> {
			model.add(stmt);
		});
	});
	
	return stmts;
	
}
 
Example 50
Project: ontonethub   File: IndexingJob.java   Source Code and License 4 votes vote down vote up
private List<Statement> getSynonyms(Property property, Model model){
	List<Statement> stmts = new ArrayList<Statement>();
	try{
		
		Site wnSite = siteManager.getSite(Constants.wordNetSiteID);
		
		FieldQuery fieldQuery = DefaultQueryFactory.getInstance().createFieldQuery();
		fieldQuery.addSelectedField(property.getURI());
		fieldQuery.setOffset(0);
		fieldQuery.setLimit(3);
		
		StmtIterator labelIt = model.listStatements(null, property, (RDFNode)null);
		labelIt.forEachRemaining(stmt -> {
			
			Resource subject = stmt.getSubject();
			RDFNode object = stmt.getObject();
			if(object.isLiteral()){
				String label = ((Literal)object).getLexicalForm();
				String lang = ((Literal)object).getLanguage();
				if(lang == null || lang.equals("it")){
					label = lemmatize(label);
					Constraint similarityConstraint = new SimilarityConstraint(label, null);
					fieldQuery.setConstraint(property.getURI(), similarityConstraint);
					
					/* Add label as synonym.
					 * But first we lemmatise the term in order to increase the recall.
					 */
					
					Literal objLiteral = null;
					if(lang != null) objLiteral = ResourceFactory.createLangLiteral(label, lang);
					else objLiteral = ResourceFactory.createPlainLiteral(label);
					
					stmts.add(new StatementImpl(subject, synonym, objLiteral));
					
					final String lab = label;
					
					QueryResultList<Representation> result = wnSite.find(fieldQuery);
					
					result.forEach(representation -> {
						
						float[] score = new float[]{0};
						Iterator<Object> objIt = representation.get(Constants.entityHubScore);
						if(objIt != null){
							objIt.forEachRemaining(obj -> {
								score[0] = (float) obj;
							});
						}
						
						if(score[0] > Constants.wordnetSynonymityConfidence){
							objIt = representation.get(property.getURI());
							if(objIt != null){
								objIt.forEachRemaining(obj -> {
									Text text = (Text) obj;
									String value = text.getText();
									String language = text.getLanguage();
									
									// Add labels of synomyms
									log.debug("Syn {} ({}) - {} : {}", subject, lab, value, score);
									Literal synLabel = ResourceFactory.createLangLiteral(lemmatize(value), language);
									stmts.add(new StatementImpl(subject, synonym, synLabel));
								});
							}
						}
						
					});
					
				}
				
			}
			
		});
	} catch(Exception e){
		log.error(e.getMessage(), e);
	}
	
	return stmts;
}
 
Example 51
Project: ontonethub   File: RDFIndexingJob.java   Source Code and License 4 votes vote down vote up
private List<Statement> collapseAnnotations(Property property, Model model){
	
	List<Statement> stmts = new ArrayList<Statement>();
	
	Map<String, Map<String,Statement>> literalMap = new HashMap<String, Map<String,Statement>>();
	StmtIterator stmtIt = model.listStatements(null, property, (RDFNode) null);
	stmtIt.forEachRemaining(stmt -> {
		RDFNode obj = stmt.getObject();
		if(obj.isLiteral()){
			Literal lit = obj.asLiteral();
			String lang = lit.getLanguage();
			if(lang == null){
				lang = "null";
			}
			Map<String, Statement> stmtMap = literalMap.get(lang);
			if(stmtMap == null) {
				stmtMap = new HashMap<String, Statement>();
				literalMap.put(lang, stmtMap);
			}
			
			Statement statement = stmtMap.get(lang);
			boolean insert = false;
			if(statement == null) insert = true;
			else{
				String statementLF = ((Literal)statement.getObject()).getLexicalForm();
				String lexicalForm = lit.getLexicalForm();
				if(lexicalForm.length() > statementLF.length()) insert = true;
			}
				
				
			if(insert) stmtMap.put(lang, statement);
		}
		
	});
	
	model.removeAll(null, property, (RDFNode) null);
	
	literalMap.forEach((subject, stmtMap) -> {
		stmtMap.forEach((lang, stmt) -> {
			model.add(stmt);
		});
	});
	
	return stmts;
	
}
 
Example 52
Project: ontonethub   File: RDFIndexingJob.java   Source Code and License 4 votes vote down vote up
private List<Statement> keepMaxLengthAnnotationsOnly(Property property, Model model){
	
	List<Statement> stmts = new ArrayList<Statement>();
	
	Map<Resource, Map<String,Statement>> literalMap = new HashMap<Resource, Map<String,Statement>>();
	StmtIterator stmtIt = model.listStatements(null, property, (RDFNode) null);
	stmtIt.forEachRemaining(stmt -> {
		Resource subj = stmt.getSubject();
		RDFNode obj = stmt.getObject();
		if(obj.isLiteral()){
			Literal lit = obj.asLiteral();
			String lang = lit.getLanguage();
			if(lang == null){
				lang = "null";
			}
			Map<String, Statement> stmtMap = literalMap.get(subj);
			if(stmtMap == null) {
				stmtMap = new HashMap<String, Statement>();
				literalMap.put(subj, stmtMap);
			}
			
			Statement statement = stmtMap.get(lang);
			boolean insert = false;
			if(statement == null) insert = true;
			else{
				String statementLF = ((Literal)statement.getObject()).getLexicalForm();
				String lexicalForm = lit.getLexicalForm();
				if(lexicalForm.length() > statementLF.length()) insert = true;
			}
				
				
			if(insert) stmtMap.put(lang, stmt);
		}
		
	});
	
	model.removeAll(null, property, (RDFNode) null);
	
	literalMap.forEach((subject, stmtMap) -> {
		stmtMap.forEach((lang, stmt) -> {
			model.add(stmt);
		});
	});
	
	return stmts;
	
}
 
Example 53
Project: semtool   File: JenaEngine.java   Source Code and License 4 votes vote down vote up
private void copyFromTdb( Dataset dataset ) throws RepositoryException {
	ValueFactory vf = rc.getValueFactory();

	if ( dataset.supportsTransactions() ) {
		dataset.begin( ReadWrite.READ );
	}

	// Get model inside the transaction
	Model model = dataset.getDefaultModel();
	StmtIterator si = model.listStatements();

	try {
		rc.begin();
		while ( si.hasNext() ) {
			Statement stmt = si.next();
			com.hp.hpl.jena.rdf.model.Resource rsr = stmt.getSubject();
			Property pred = stmt.getPredicate();
			RDFNode val = stmt.getObject();
			Node valnode = val.asNode();
			
			Resource sub;
			try {
				sub = ( rsr.isAnon()
						? vf.createBNode( valnode.getBlankNodeLabel() )
						: vf.createURI( rsr.toString() ) );
			}
			catch ( UnsupportedOperationException uoo ) {
				log.warn( uoo, uoo );
				continue;
			}
			
			URI pred2 = vf.createURI( pred.toString() );
			Value val2;

			if ( val.isLiteral() ) {
				Literal lit = val.asLiteral();
				String dtstr = lit.getDatatypeURI();
				URI dt = ( null == dtstr ? null : vf.createURI( dtstr ) );
				String langstr = lit.getLanguage();

				if ( null == dt ) {
					if ( langstr.isEmpty() ) {
						val2 = vf.createLiteral( lit.toString() );
					}
					else {
						val2 = vf.createLiteral( lit.toString(), langstr );
					}
				}
				else {
					val2 = vf.createLiteral( lit.toString(), dt );
				}
			}
			else {
				if ( val.isAnon() ) {
					val2 = vf.createBNode( valnode.getBlankNodeLabel() );
				}
				else {
					val2 = vf.createURI( val.toString() );
				}
			}
			rc.add( sub, pred2, val2 );
		}
		rc.commit();
	}
	catch ( RepositoryException re ) {
		rc.rollback();
		throw re;
	}
	finally {
		if ( dataset.supportsTransactions() ) {
			dataset.end();
		}
	}
}
 
Example 54
Project: phenopacket-reference-implementation   File: RdfReader.java   Source Code and License 4 votes vote down vote up
private static List<RDFNode> getValues(Model model, Resource subject,
		Property property) {
	return model.listObjectsOfProperty(subject, property).toList();
}
 
Example 55
Project: r2rml-kit   File: Report.java   Source Code and License 4 votes vote down vote up
public void report(Problem problem, Resource subject, Property property, MappingTerm term) {
	report(new Message(problem, term, null, null, subject, property));
}
 
Example 56
Project: r2rml-kit   File: Report.java   Source Code and License 4 votes vote down vote up
public void report(Problem problem, Resource subject, Property property, MappingTerm term, String detailCode, String details) {
	report(new Message(problem, term, detailCode, details, subject, property));
}
 
Example 57
Project: r2rml-kit   File: Report.java   Source Code and License 4 votes vote down vote up
public void report(Problem problem, Resource subject, Property[] predicates) {
	report(new Message(problem, subject, predicates, null));
}
 
Example 58
Project: r2rml-kit   File: Report.java   Source Code and License 4 votes vote down vote up
public void report(Problem problem, Resource subject, Property predicate, RDFNode object) {
	report(new Message(problem, subject, 
			predicate == null ? null : new Property[]{predicate}, new RDFNode[]{object}));
}
 
Example 59
Project: r2rml-kit   File: Report.java   Source Code and License 4 votes vote down vote up
public void report(Problem problem, Resource subject, Property predicate, RDFNode[] objects) {
	report(new Message(problem, subject, 
			predicate == null ? null : new Property[]{predicate}, objects));
}
 
Example 60
Project: r2rml-kit   File: PrettyTurtleWriter.java   Source Code and License 4 votes vote down vote up
public void printProperty(Property property, MapObject object) {
	if (object == null) return;
	printProperty(property, object.resource());
}