org.apache.jena.rdf.model.Statement Java Examples

The following examples show how to use org.apache.jena.rdf.model.Statement. 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: JenaUtil.java    From shacl with Apache License 2.0 8 votes vote down vote up
public static String getStringProperty(Resource subject, Property predicate) {
	Statement s = subject.getProperty(predicate);
	if(s != null && s.getObject().isLiteral()) {
		return s.getString();
	}
	else {
		return null;
	}
}
 
Example #2
Source File: ReasoningOntology.java    From Heracles with GNU General Public License v3.0 6 votes vote down vote up
public HashSet<String> test(String literal){
		
		StmtIterator iter = ontology.listStatements(new SimpleSelector(null, ontology.getProperty("lex"),ontology.createLiteral(literal)));
		
		
		HashSet<String> ontoConcepts=new HashSet<String>();
//		System.out.println(literal);
		while (iter.hasNext()) {
			
			Statement stmt = iter.nextStatement();
			Resource  subject   = stmt.getSubject();     // get the subject
//			StmtIterator iter2 = ontology.listStatements(new SimpleSelector(
//					subject, 
//					ontology.getProperty("http://www.w3.org/2000/01/rdf-schema#subClassOf"),
//					ontology.getResource(NS+"#Mention")));
//			if (iter2.hasNext())
				ontoConcepts.add(subject.getURI());
			
//			System.out.println(subject.toString());
		}
		return ontoConcepts;
	}
 
Example #3
Source File: ClosedConstraintExecutor.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();
	if(closed) {
		for(RDFNode focusNode : focusNodes) {
			if(focusNode instanceof Resource) {
				Iterator<Statement> it = ((Resource)focusNode).listProperties();
				while(it.hasNext()) {
					Statement s = it.next();
					if(!allowedProperties.contains(s.getPredicate())) {
						Resource result = engine.createValidationResult(constraint, focusNode, s.getObject(), () -> "Predicate " + engine.getLabelFunction().apply(s.getPredicate()) + " is not allowed (closed shape)");
						result.removeAll(SH.resultPath);
						result.addProperty(SH.resultPath, s.getPredicate());
					}
				}
			}
			engine.checkCanceled();
		}
	}
	addStatistics(constraint, startTime);
}
 
Example #4
Source File: SHACLUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a shapes Model for a given input Model.
 * The shapes Model is the union of the input Model with all graphs referenced via
 * the sh:shapesGraph property (and transitive includes or shapesGraphs of those).
 * @param model  the Model to create the shapes Model for
 * @return a shapes graph Model
 */
private static Model createShapesModel(Dataset dataset) {
	
	Model model = dataset.getDefaultModel();
	Set<Graph> graphs = new HashSet<Graph>();
	Graph baseGraph = model.getGraph();
	graphs.add(baseGraph);
	
	for(Statement s : model.listStatements(null, SH.shapesGraph, (RDFNode)null).toList()) {
		if(s.getObject().isURIResource()) {
			String graphURI = s.getResource().getURI();
			Model sm = dataset.getNamedModel(graphURI);
			graphs.add(sm.getGraph());
			// TODO: Include includes of sm
		}
	}
	
	if(graphs.size() > 1) {
		MultiUnion union = new MultiUnion(graphs.iterator());
		union.setBaseGraph(baseGraph);
		return ModelFactory.createModelForGraph(union);
	}
	else {
		return model;
	}
}
 
Example #5
Source File: SHParameterizableInstanceImpl.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, RDFNode> getParameterMapByVarNames() {
	Map<String,RDFNode> map = new HashMap<String,RDFNode>();
	SHParameterizable template = getParameterizable();
	if(template != null) {
		for(SHParameter arg : template.getParameters()) {
			Property argProperty = arg.getPredicate();
			if(argProperty != null) {
				String varName = arg.getVarName();
				Statement valueS = getProperty(argProperty);
				if(valueS != null) {
					map.put(varName, valueS.getObject());
				}
			}
		}
	}
	return map;
}
 
Example #6
Source File: GtRDFReader.java    From JedAIToolkit with Apache License 2.0 6 votes vote down vote up
protected void performReading() {
    final Model model = RDFDataMgr.loadModel(inputFilePath);
    final StmtIterator iter = model.listStatements();
    while (iter.hasNext()) {
        Statement stmt = iter.nextStatement();

        final String pred = stmt.getPredicate().toString();
        if (!(pred.contains("sameAs"))) {
            continue;
        }

        final String sub = stmt.getSubject().toString();
        final String obj = stmt.getObject().toString();

        // add a new edge for every pair of duplicate entities
        int entityId1 = urlToEntityId1.get(sub);
        int entityId2 = urlToEntityId1.get(obj) + datasetLimit;

        duplicatesGraph.addEdge(entityId1, entityId2);
    }
}
 
Example #7
Source File: JenaUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
private static <T> T getNearest(Resource cls, java.util.function.Function<Resource,T> function, Set<Resource> reached) {
	reached.add(cls);
	StmtIterator it = cls.listProperties(RDFS.subClassOf);
	while(it.hasNext()) {
		Statement s = it.next();
		if(s.getObject().isResource() && !reached.contains(s.getResource())) {
			T result = function.apply(s.getResource());
			if(result == null) {
				result = getNearest(s.getResource(), function, reached);
			}
			if(result != null) {
				it.close();
				return result;
			}
		}
	}
	return null;
}
 
Example #8
Source File: Importer.java    From fcrepo-import-export with Apache License 2.0 6 votes vote down vote up
/**
 * Removes statements from the provided model that affect triples that need not be (and indeed
 * cannot be) modified directly through PUT, POST or PATCH requests to fedora.
 *
 * Certain triples included in a resource from fedora cannot be explicitly stored, but because
 * they're derived from other content that *can* be stored will still appear identical when the
 * other RDF and content is ingested.  Examples include those properties that reflect innate
 * characteristics of binary resources like file size and message digest,  Or triples that
 * represent characteristics of rdf resources like the number of children, whether it has
 * versions and some of the types.
 *
 * @param model the RDF statements about an exported resource
 * @return the provided model updated to omit statements that may not be updated directly through
 *         the fedora API
 * @throws IOException
 * @throws FcrepoOperationFailedException
 */
private Model sanitize(final Model model) throws IOException, FcrepoOperationFailedException {
    final List<Statement> remove = new ArrayList<>();
    for (final StmtIterator it = model.listStatements(); it.hasNext(); ) {
        final Statement s = it.nextStatement();

        if ((s.getPredicate().getNameSpace().equals(REPOSITORY_NAMESPACE) && !relaxedPredicate(s.getPredicate()))
                || s.getSubject().getURI().endsWith("fcr:export?format=jcr/xml")
                || s.getSubject().getURI().equals(REPOSITORY_NAMESPACE + "jcr/xml")
                || s.getPredicate().equals(DESCRIBEDBY)
                || s.getPredicate().equals(CONTAINS)
                || s.getPredicate().equals(HAS_MESSAGE_DIGEST)
                || (s.getPredicate().equals(RDF_TYPE) && forbiddenType(s.getResource()))) {
            remove.add(s);
        } else if (s.getObject().isResource()) {
            // make sure that referenced repository objects exist
            final String obj = s.getResource().toString();
            if (obj.startsWith(repositoryRoot.toString())) {
                ensureExists(URI.create(obj));
            }
        }
    }
    return model.remove(remove);
}
 
Example #9
Source File: DB2Closure.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
private static void closureNoTest(Resource r, Model closureBlob,
		Collection<Resource> visited, ClosureTest test, Collection<String> resources) {
	visited.add(r);
	String gid = ((DB2Graph) r.getModel().getGraph()).getGraphID();
	String key = null;
	if (r.isAnon()) {
		key = gid + ":" + r.getId();
	} else {
		key = gid + ":" + r.getURI();
	}
	if (resources.contains(key)) {
		return;
	}
	resources.add(key);

	StmtIterator sIter = r.listProperties();

	for (; sIter.hasNext();) {
		Statement stmt = sIter.nextStatement();
		closure(stmt, closureBlob, visited, test, resources);
	}
}
 
Example #10
Source File: SurveyServiceMapper.java    From SDA with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public List<Statement> from() {
	Type type = new TypeToken<List<SurveyInfoDTO>>() {
	}.getType();
	Gson gson = new Gson();
	List<SurveyInfoDTO> surveyList = gson.fromJson(content, type);

	Iterator<SurveyInfoDTO> it = surveyList.iterator();
	
	while (it.hasNext()) {
		Resource _surveury = model.createResource(baseuri+"/Survey_"+UUID.randomUUID());
		List<Statement> _slist = getStatementList( it.next(), _surveury);
		slist.addAll(_slist);
	}
	
	return slist;
}
 
Example #11
Source File: ShaclTestCaseResultReader.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
@Override
public ShaclTestCaseResult read(final Resource resource) {
    checkNotNull(resource);

    ShaclLiteTestCaseResult test = ShaclLiteTestCaseResultReader.create().read(resource);

    PropertyValuePairSet.PropertyValuePairSetBuilder annotationSetBuilder = PropertyValuePairSet.builder();


    for (Statement smt: resource.listProperties().toList()) {
        if (excludesProperties.contains(smt.getPredicate())) {
            continue;
        }
        if (RDF.type.equals(smt.getPredicate()) && excludesTypes.contains(smt.getObject().asResource())) {
            continue;
        }
        annotationSetBuilder.annotation(PropertyValuePair.create(smt.getPredicate(), smt.getObject()));
    }

    return new ShaclTestCaseResultImpl(resource, test.getTestCaseUri(), test.getSeverity(), test.getMessage(), test.getTimestamp(), test.getFailingNode(), annotationSetBuilder.build().getAnnotations());
}
 
Example #12
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void writeExtraStatements(IndentedWriter out, Resource subject, Set<Property> specialProperties, boolean wrapped) {
	List<Statement> extras = getExtraStatements(subject, specialProperties);
	if(!extras.isEmpty()) {
		if(wrapped) {
			out.print("( ");
		}
		for(Statement s : extras) {
			out.print(" " + getPredicateName(s.getPredicate()));
			out.print("=");
			out.print(node(s.getObject()));
		}
		if(wrapped) {
			out.print(" )");
		}
	}
}
 
Example #13
Source File: TemplateImpl.java    From Processor with Apache License 2.0 6 votes vote down vote up
@Override
public UriTemplate getMatch()
{
    Statement path = getProperty(LDT.match);
    if (path != null)
    {
        if (!path.getObject().isLiteral() ||
                path.getObject().asLiteral().getDatatype() == null ||
                !path.getObject().asLiteral().getDatatype().equals(XSDDatatype.XSDstring))
        {
            if (log.isErrorEnabled()) log.error("Class {} property {} is not an xsd:string literal", getURI(), LDT.match);
            throw new OntologyException("Class '" + getURI() + "' property '" + LDT.match + "' is not an xsd:string literal");
        }
        
        return new UriTemplate(path.getString());
    }
    
    return null;
}
 
Example #14
Source File: ExpressionConstraintExecutor.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) {
	// TODO: optimize, currently produces a new NodeExpression each time
	NodeExpression expr = NodeExpressionFactory.get().create(constraint.getParameterValue());
	for(RDFNode focusNode : focusNodes) {
		engine.checkCanceled();
		for(RDFNode valueNode : engine.getValueNodes(constraint, focusNode)) {
			List<RDFNode> results = expr.eval(valueNode, engine).toList();
			if(results.size() != 1 || !JenaDatatypes.TRUE.equals(results.get(0))) {
				Resource result = engine.createValidationResult(constraint, focusNode, valueNode, () -> "Expression does not evaluate to true");
				result.addProperty(SH.sourceConstraint, constraint.getParameterValue());
				if(constraint.getParameterValue() instanceof Resource && ((Resource)constraint.getParameterValue()).hasProperty(SH.message)) {
					for(Statement s : ((Resource)constraint.getParameterValue()).listProperties(SH.message).toList()) {
						result.addProperty(SH.resultMessage, s.getObject());
					}
				}
			}
		}
	}
}
 
Example #15
Source File: FactIterator.java    From Stargraph with MIT License 6 votes vote down vote up
@Override
protected Indexable buildNext(Statement statement) {
    InstanceEntity instanceEntity = createInstance(applyNS(statement.getSubject().getURI()));
    PropertyEntity propertyEntity = createProperty(applyNS(statement.getPredicate().getURI()));

    LabeledEntity labeledEntity;

    if (!statement.getObject().isLiteral()) {
        //Is created as an instance but can be changed to a class down on the workflow in EntityClassifierProcessor.
        labeledEntity = createInstance(applyNS(statement.getObject().asResource().getURI()));
    } else {
        Literal literal = statement.getObject().asLiteral();
        String dataType = literal.getDatatypeURI();
        String langTag = literal.getLanguage();
        String value = literal.getLexicalForm();
        labeledEntity = new ValueEntity(value, dataType, langTag);
    }


    return new Indexable(new Fact(kbId, instanceEntity, propertyEntity, labeledEntity), kbId);
}
 
Example #16
Source File: AbstractDataGenerator.java    From IGUANA with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Will send a {@link org.apache.jena.rdf.model.Model} 
 */
public void sendData(Model m) throws Exception {
	int sendedSize=0;
	//split Model into small parts
	StmtIterator sti = m.listStatements();
	while(sti.hasNext()){
		Model send = ModelFactory.createDefaultModel();
		send.setNsPrefixes(m.getNsPrefixMap());
		while(sendedSize < maxSize){
			Statement stmt = sti.next();
			send.add(stmt);
			sendedSize+=1;
		}
		sendDataSnippet(RabbitMQUtils.getData(send));
	}
	
}
 
Example #17
Source File: RdfModelObject.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * Find a property value with a subject of this object
 * @param namespace Namespace for the property name
 * @param propertyName Name of the property
 * @return The string value of the property or null if no property exists
 */
public String findSinglePropertyValue(String namespace, String propertyName) {
	if (this.model == null || this.node == null) {
		return null;
	}
	
	Statement stmt = resource.getProperty(new PropertyImpl(namespace, propertyName));
	if (stmt == null) return null;
	else if (stmt.getObject().isLiteral()){
		return stmt.getObject().asLiteral().getString();
	} else if (stmt.getObject().isResource()){
		return PRE_DEFINED_URI_VALUE.get(stmt.getObject().asResource().getURI());
	} else {
		return stmt.getObject().toString();
	}
}
 
Example #18
Source File: ValidationEngine.java    From shacl with Apache License 2.0 6 votes vote down vote up
public void updateConforms() {
	boolean conforms = true;
	StmtIterator it = report.listProperties(SH.result);
	while(it.hasNext()) {
		Statement s = it.next();
		if(s.getResource().hasProperty(RDF.type, SH.ValidationResult)) {
			conforms = false;
			it.close();
			break;
		}
	}
	if(report.hasProperty(SH.conforms)) {
		report.removeAll(SH.conforms);
	}
	report.addProperty(SH.conforms, conforms ? JenaDatatypes.TRUE : JenaDatatypes.FALSE);
}
 
Example #19
Source File: AdditionalPropertyMatcherImpl.java    From FCA-Map with GNU General Public License v3.0 6 votes vote down vote up
private <T extends Resource> void addContext(Set<T> properties,
                                             int from_id,
                                             Map<Resource, Set<MappingCell>> m,
                                             Map<ResourceWrapper<T>, Set<SubjectObject>> context) {
  for (final T p : properties) {

    StmtIterator it = p.getModel().listStatements(
          new SimpleSelector(null, null, (RDFNode) null) {
            @Override
            public boolean selects(Statement s) {
              return s.getPredicate().getURI().equals(p.getURI()) && s.getObject().isResource();
            }
          }
        );

    while (it.hasNext()) {
      Statement stmt = it.nextStatement();

      Resource subject = stmt.getSubject();
      Resource object  = stmt.getObject().asResource();

      ResourceWrapper<T> rw = new ResourceWrapper<T>(p, from_id);
      addContextFromSO(context, rw, m, subject, object);
    }
  }
}
 
Example #20
Source File: AttendanceServiceMapper.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
	AttendanceServiceMapper map = new AttendanceServiceMapper("http://www.pineone.com/campus/cm001","2015-12-12T00:00:00","absent","http://www.pineone.com/campus/u00001");
	List<Statement> result = map.from();
	Iterator it = result.iterator();
	while (it.hasNext()) {
		System.out.println(it.next());
		
	}
}
 
Example #21
Source File: AttendanceServiceMapper.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public List<Statement> from() {
	List<Statement> slist = new ArrayList<Statement>();
	initResource();
	slist.add(model.createStatement(this.attendance, RDF.type, model.createResource(baseuri + "/Attendance")));
	slist.add(model.createStatement(this.attendance, model.createProperty(baseuri+"/isAttendanceOf"), this.lecture));
	slist.add(model.createStatement(this.attendance, model.createProperty(baseuri+"/hasCreateDate"), this.createDate));
	slist.add(model.createStatement(this.attendance, model.createProperty(baseuri+"/hasCondition"), this.condition));
	slist.add(model.createStatement(this.attendance, model.createProperty("http://www.loa-cnr.it/ontologies/DUL.owl#hasMember"), this.user));
	return slist;
}
 
Example #22
Source File: StatusTestCaseResultReader.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Override
public StatusTestCaseResult read(final Resource resource) {
    checkNotNull(resource);

    TestCaseResult test = TestCaseResultReader.create(DCTerms.description, RDFUNITv.testCaseLogLevel).read(resource);

    TestCaseResultStatus status = null;
    for (Statement smt : resource.listProperties(RDFUNITv.resultStatus).toList()) {
        status = TestCaseResultStatus.resolve(smt.getObject().asResource().getURI());
    }
    checkNotNull(status);

    return new StatusTestCaseResultImpl(resource, test.getTestCaseUri(), test.getSeverity(), test.getMessage(), test.getTimestamp(), status);
}
 
Example #23
Source File: OneM2MContentInstanceDTO.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public TripleMap<Statement> getTriples() {
	TripleMap<Statement> map = new TripleMap<Statement>();
	OneM2MContentInstanceMapper mapper = new OneM2MContentInstanceMapper(this);
	map.add(mapper.from());
	
	//gooper2
	mapper.close();
	
	return map;

}
 
Example #24
Source File: AttendanceServiceMapper.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public List<Statement> from() {
	List<Statement> slist = new ArrayList<Statement>();
	initResource();
	slist.add(model.createStatement(this.attendance, RDF.type, model.createResource(baseuri + "/campus/Attendance")));
	slist.add(model.createStatement(this.attendance, model.createProperty(baseuri+"/campus/isAttendanceOf"), this.lecture));
	slist.add(model.createStatement(this.attendance, model.createProperty(baseuri+"/m2m/hasCreateDate"), this.createDate));
	slist.add(model.createStatement(this.attendance, model.createProperty(baseuri+"/campus/hasCondition"), this.condition));
	slist.add(model.createStatement(this.attendance, model.createProperty("http://www.loa-cnr.it/ontologies/DUL.owl#hasMember"), this.user));
	return slist;
}
 
Example #25
Source File: OneM2MCSEBaseDTO.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public TripleMap<Statement> getTriples() {
	TripleMap<Statement> map = new TripleMap<Statement>();
	OneM2MCSEBaseMapper mapper = new OneM2MCSEBaseMapper(this);
	map.add(mapper.from());
	return map;

}
 
Example #26
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void writeProperty(IndentedWriter out, Resource property) {
	out.print(getPathString(property));
	out.print(" ");
	
	out.print(getPropertyTypes(property));
	
	// Count block
	out.print(" ");
	out.print("[");
	Statement minCountS = property.getProperty(SH.minCount);
	if(minCountS != null) {
		out.print("" + minCountS.getInt());
	}
	else {
		out.print("0");
	}
	out.print("..");
	Statement maxCountS = property.getProperty(SH.maxCount);
	if(maxCountS != null) {
		out.print("" + maxCountS.getInt());
	}
	else {
		out.print("*");
	}
	out.print("]");
	
	writeExtraStatements(out, property, specialPropertyProperties, false);
	
	writeNestedShapes(out, property);
	
	out.println(" .");
}
 
Example #27
Source File: OneM2MCSEBaseDTO.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public TripleMap<Statement> getTriples() {
	TripleMap<Statement> map = new TripleMap<Statement>();
	OneM2MCSEBaseMapper mapper = new OneM2MCSEBaseMapper(this);
	map.add(mapper.from());
	return map;

}
 
Example #28
Source File: UserInOutServiceMapper.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public List<Statement> from() {
	initResource();
	// type
	Statement typestmt = model.createStatement(this.userinout, RDF.type,
			model.createResource(baseuri + "/GoInOut"));
	slist.add(typestmt);

	if (this.direction == null || this.user == null || this.location == null
			|| this.direction.toString() == "null" || this.user.toString()=="null" || this.location.toString()=="null") {
		slist.clear();
		return slist;
	}

	// direction
	Statement directionstmt = model.createStatement(this.userinout,
			model.createProperty(baseuri + "/hasDirection"), this.direction);
	slist.add(directionstmt);

	// userid
	Statement userstmt = model.createStatement(this.userinout,
			model.createProperty("http://www.loa-cnr.it/ontologies/DUL.owl#hasComponent"), this.user);
	slist.add(userstmt);

	// location
	Statement locationstmt = model.createStatement(this.userinout,
			model.createProperty("http://www.loa-cnr.it/ontologies/DUL.owl#hasLocation"), this.location);
	slist.add(locationstmt);

	return slist;
}
 
Example #29
Source File: TripleRule.java    From shacl with Apache License 2.0 5 votes vote down vote up
private NodeExpression createNodeExpression(Resource resource, Property predicate) {
	Statement s = resource.getProperty(predicate);
	if(s == null) {
		throw new IllegalArgumentException("Triple rule without " + predicate.getLocalName());
	}
	return NodeExpressionFactory.get().create(s.getObject());
}
 
Example #30
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static Resource getURIResourceProperty(Resource subject, Property predicate) {
	Statement s = subject.getProperty(predicate);
	if(s != null && s.getObject().isURIResource()) {
		return s.getResource();
	}
	else {
		return null;
	}
}