org.apache.jena.vocabulary.RDF Java Examples

The following examples show how to use org.apache.jena.vocabulary.RDF. 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: ModelWrapper.java    From FCA-Map with GNU General Public License v3.0 6 votes vote down vote up
private void acquireInstances() {
  // XXX: remove instances of DBkWik:Image and SKOS:Concept, Template. Under consideration.
  ResIterator it = null;

  if (m_inferred) {
    it = m_inferred_model.listSubjects();
  } else {
    it = m_raw_model.listSubjects();
  }

  while (it.hasNext()) {
    Resource r = it.nextResource();
    if (DBkWik.ownAsResource(r) && !DBkWik.ownAsTemplate(r) &&
        !r.hasProperty(RDF.type, SKOS.Concept) &&
        !r.hasProperty(RDF.type, DBkWik.Image)) {
      m_instances.add(r);
    }
  }
}
 
Example #2
Source File: BatchTestCaseReader.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
public Collection<GenericTestCase> getTestCasesFromModel(Model model) {
    ConcurrentLinkedQueue<TestCase> testCases = new ConcurrentLinkedQueue<>();

    model.listResourcesWithProperty(RDF.type, RDFUNITv.ManualTestCase).toList()
            .parallelStream()
            .forEach(resource -> testCases.add(ManualTestCaseReader.create().read(resource)));


    model.listResourcesWithProperty(RDF.type, RDFUNITv.PatternBasedTestCase)
            .toList()
            .parallelStream()
            .forEach(resource -> {
                try {
                    testCases.add(PatternBasedTestCaseReader.create().read(resource));
                } catch (IllegalArgumentException ex) {
                    log.warn("Cannot create PatternBasedTestCase {}", resource.toString(), ex);
                }
            });

    return ImmutableList.copyOf(testCases);

}
 
Example #3
Source File: AnnotationTemplateTest.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddTemplateMax() {
    AnnotationTemplate at = AnnotationTemplate.create();

    assertThat(at.existsInTemplate(sa1)).isFalse();
    at.addTemplateMax(RDF.type, 1);
    assertThat(at.existsInTemplate(sa1)).isTrue();
    assertThat(at.isValidAccordingToTemplate(sa1)).isTrue();


    assertThat(at.existsInTemplate(sa2)).isFalse();
    assertThat(at.isValidAccordingToTemplate(sa2)).isFalse();
    at.addTemplateMax(RDF.predicate, 1);
    assertThat(at.existsInTemplate(sa2)).isTrue();
    assertThat(at.isValidAccordingToTemplate(sa2)).isFalse();

}
 
Example #4
Source File: SolidContactsImport.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String createIndex(String url, String slug, SolidUtilities utilities) throws Exception {
  Model model = ModelFactory.createDefaultModel();
  Resource containerResource = model.createResource("#this");
  containerResource.addProperty(RDF.type, model.getResource(VCARD4.NS + "AddressBook"));
  containerResource.addProperty(
      model.createProperty(VCARD4.NS + "nameEmailIndex"),
      model.createResource("people.ttl"));
  containerResource.addProperty(
      model.createProperty(VCARD4.NS + "groupIndex"),
      model.createResource("groups.ttl"));
  containerResource.addProperty(DC_11.title, slug);
  return utilities.postContent(
      url,
      "index",
      BASIC_RESOURCE_TYPE,
      model);
}
 
Example #5
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 #6
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 #7
Source File: Distribution.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private Resource addValues(Model model, Resource distribution) {
    distribution.addProperty(RDF.type, DCAT.Distribution);
    addTitleAndDescription(model, distribution);

    for (AccessURL accessURL : getAccessURLs()) {
        accessURL.addToResource(model, distribution);
    }

    for (DownloadURL downloadURL : getDownloadURLs()) {
        downloadURL.addToResource(model, distribution);
    }

    if (getFormat() != null) {
        getFormat().addToResource(model, distribution);
    }

    if (getLicense() != null) {
        getLicense().addToResource(model, distribution);
    }

    return distribution;
}
 
Example #8
Source File: ComponentParameterWriter.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
@Override
public Resource write(Model model) {
    Resource resource = ElementWriter.copyElementResourceInModel(componentParameter, model);

    // rdf:type sh:ComponentParameter
    resource.addProperty(RDF.type, SHACL.ParameterCls);

    // sh:path sh:argX
    resource.addProperty(SHACL.path, componentParameter.getPredicate()) ;

    //Optional
    if (componentParameter.isOptional()) {
        resource.addProperty(SHACL.optional, ResourceFactory.createTypedLiteral("true", XSDDatatype.XSDboolean)) ;
    }
    return resource;
}
 
Example #9
Source File: SimpleSubClassInferencerTest.java    From gerbil with GNU Affero General Public License v3.0 6 votes vote down vote up
private static Model createModel() {
    Model classModel = ModelFactory.createDefaultModel();
    Resource A = classModel.createResource("http://example.org/A");
    Resource B = classModel.createResource("http://example.org/B");
    Resource C = classModel.createResource("http://example.org/C");
    Resource C2 = classModel.createResource("http://example2.org/C");
    Resource C3 = classModel.createResource("http://example3.org/C");
    Resource D2 = classModel.createResource("http://example2.org/D");
    Resource D3 = classModel.createResource("http://example3.org/D");
    classModel.add(A, RDF.type, RDFS.Class);
    classModel.add(B, RDF.type, RDFS.Class);
    classModel.add(C, RDF.type, RDFS.Class);
    classModel.add(C2, RDF.type, RDFS.Class);
    classModel.add(C3, RDF.type, RDFS.Class);
    classModel.add(D2, RDF.type, RDFS.Class);
    classModel.add(D3, RDF.type, RDFS.Class);
    classModel.add(B, RDFS.subClassOf, A);
    classModel.add(C, RDFS.subClassOf, B);
    classModel.add(C, OWL.sameAs, C2);
    classModel.add(C3, OWL.equivalentClass, C);
    classModel.add(D2, RDFS.subClassOf, C2);
    classModel.add(D3, RDFS.subClassOf, C3);
    return classModel;
}
 
Example #10
Source File: PatternBasedTestCaseWriter.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
@Override
public Resource write(Model model) {
    Resource resource = ElementWriter.copyElementResourceInModel(patternBasedTestCase, model);

    resource
            //.addProperty(RDFS.comment, "FOR DEBUGGING ONLY: SPARQL Query: \n" + new QueryGenerationSelectFactory().getSparqlQueryAsString(this) + "\n Prevalence SPARQL Query :\n" + getSparqlPrevalence());
            .addProperty(RDF.type, RDFUNITv.PatternBasedTestCase)
            .addProperty(RDFUNITv.basedOnPattern,  ElementWriter.copyElementResourceInModel(patternBasedTestCase.getPattern(), model));

    for (Binding binding : patternBasedTestCase.getBindings()) {
        Resource bindingResource = BindingWriter.create(binding).write(model);
        resource.addProperty(RDFUNITv.binding, bindingResource);
    }

    TestAnnotationWriter.create(patternBasedTestCase.getTestCaseAnnotation()).write(model);


    return resource;
}
 
Example #11
Source File: JenaTransformationRepairSwitchMonitored.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void activate(final Collection<JenaSwitchMonitoredMatch> matches) throws Exception {
	final Model model = driver.getModel();
	final Property sensorEdge = model.getProperty(BASE_PREFIX + MONITORED_BY);
	final Resource sensorType = model.getResource(BASE_PREFIX + SENSOR);

	for (final JenaSwitchMonitoredMatch match : matches) {
		final Resource sw = match.getSw();
		final Long newVertexId = driver.generateNewVertexId();
		final Resource sensor = model.createResource(BASE_PREFIX + ID_PREFIX + newVertexId);

		model.add(model.createStatement(sw, sensorEdge, sensor));
		model.add(model.createStatement(sensor, RDF.type, sensorType));
	}

}
 
Example #12
Source File: W3CTestRunner.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void collectItems(File manifestFile, String baseURI) throws IOException {
	
	String filePath = manifestFile.getAbsolutePath().replaceAll("\\\\", "/");
	int coreIndex = filePath.indexOf("core/");
	if(coreIndex > 0 && !filePath.contains("sparql/core")) {
		filePath = filePath.substring(coreIndex);
	}
	else {
		int sindex = filePath.indexOf("sparql/");
		if(sindex > 0) {
			filePath = filePath.substring(sindex);
		}
	}
	
	Model model = JenaUtil.createMemoryModel();
	model.read(new FileInputStream(manifestFile), baseURI, FileUtils.langTurtle);
	
	for(Resource manifest : model.listSubjectsWithProperty(RDF.type, MF.Manifest).toList()) {
		for(Resource include : JenaUtil.getResourceProperties(manifest, MF.include)) {
			String path = include.getURI().substring(baseURI.length());
			File includeFile = new File(manifestFile.getParentFile(), path);
			if(path.contains("/")) {
				String addURI = path.substring(0, path.indexOf('/'));
				collectItems(includeFile, baseURI + addURI + "/");
			}
			else {
				collectItems(includeFile, baseURI + path);
			}
		}
		for(Resource entries : JenaUtil.getResourceProperties(manifest, MF.entries)) {
			for(RDFNode entry : entries.as(RDFList.class).iterator().toList()) {
				items.add(new Item(entry.asResource(), filePath, manifestFile));
			}
		}
	}
}
 
Example #13
Source File: TemplateCall.java    From Processor with Apache License 2.0 5 votes vote down vote up
public Statement getArgumentProperty(Property predicate)
{
    Resource arg = getArgument(predicate);
    if (arg != null) return arg.getRequiredProperty(RDF.value);
    
    return null;
}
 
Example #14
Source File: ExceptionMapperBase.java    From Processor with Apache License 2.0 5 votes vote down vote up
public Resource toResource(Exception ex, Response.StatusType status, Resource statusResource)
{
    if (ex == null) throw new IllegalArgumentException("Exception cannot be null");
    if (status == null) throw new IllegalArgumentException("Response.Status cannot be null");

    Resource resource = ModelFactory.createDefaultModel().createResource().
            addProperty(RDF.type, HTTP.Response).
            addLiteral(HTTP.statusCodeValue, status.getStatusCode()).
            addLiteral(HTTP.reasonPhrase, status.getReasonPhrase());

    if (statusResource != null) resource.addProperty(HTTP.sc, statusResource);
    if (ex.getMessage() != null) resource.addLiteral(DCTerms.title, ex.getMessage());
    
    return resource;
}
 
Example #15
Source File: Skolemizer.java    From Processor with Apache License 2.0 5 votes vote down vote up
public URI build(Resource resource)
{
    SortedSet<ClassPrecedence> matchedClasses = match(getOntology(), resource, RDF.type, 0);
    if (!matchedClasses.isEmpty())
    {
        OntClass typeClass = matchedClasses.first().getOntClass();
        if (log.isDebugEnabled()) log.debug("Skolemizing resource {} using ontology class {}", resource, typeClass);
        
        return build(resource, typeClass);
    }
    
    return null;
}
 
Example #16
Source File: EliminateEJVar.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
protected static URI getRDFType() {
	try {
		return new URI(RDF.type.getURI());
	} catch (URISyntaxException e) {
		throw new RuntimeException(e);
	}
}
 
Example #17
Source File: VerifyEarlReporter.java    From teamengine with Apache License 2.0 5 votes vote down vote up
@Test
public void initializeModel() {
    String testSubject = "http://www.example.org/test/subject";
    Map<String, String> params = new HashMap<String, String>();
    params.put("iut", testSubject);
    params.put("uuid", UUID.randomUUID().toString());
    when(xmlSuite.getAllParameters()).thenReturn(params);
    EarlReporter iut = new EarlReporter();
    Model model = iut.initializeModel(suite);
    assertNotNull(model);
    ResIterator itr = model.listSubjectsWithProperty(RDF.type, EARL.TestSubject);
    assertEquals("Unexpected URI for earl:TestSubject", testSubject, itr.next().getURI());
}
 
Example #18
Source File: RuleRenaming.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
protected static URI getRDFType() {
	try {
		return new URI(RDF.type.getURI());
	} catch (URISyntaxException e) {
		throw new RuntimeException(e);
	}
}
 
Example #19
Source File: AdditionalPropertyMatcherImpl.java    From FCA-Map with GNU General Public License v3.0 5 votes vote down vote up
private static final void deriveClassMappingsFromResource(Resource r, Map<Resource, Set<MappingCell>> m, Set<MappingCell> s) {
  for (StmtIterator it = r.listProperties(RDF.type); it.hasNext(); ) {
    Statement stmt = it.nextStatement();
    if (stmt.getObject().isResource()) {
      Set<MappingCell> v = m.get(stmt.getObject());
      if (v != null) {
        s.addAll(s);
      }
    }
  }
}
 
Example #20
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 #21
Source File: W3CTestRunner.java    From shacl with Apache License 2.0 5 votes vote down vote up
public W3CTestRunner(File rootManifest) throws IOException {
	
	earl = JenaUtil.createMemoryModel();
	JenaUtil.initNamespaces(earl.getGraph());
	earl.setNsPrefix("doap", DOAP.NS);
	earl.setNsPrefix("earl", EARL.NS);
	
	earl.add(EARL_SUBJECT, RDF.type, DOAP.Project);
	earl.add(EARL_SUBJECT, RDF.type, EARL.Software);
	earl.add(EARL_SUBJECT, RDF.type, EARL.TestSubject);
	earl.add(EARL_SUBJECT, DOAP.developer, EARL_AUTHOR);
	earl.add(EARL_SUBJECT, DOAP.name, "TopBraid SHACL API");
	
	collectItems(rootManifest, "urn:x:root/");
}
 
Example #22
Source File: ValidationUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static Model ensureToshTriplesExist(Model shapesModel) {
	// Ensure that the SHACL, DASH and TOSH graphs are present in the shapes Model
	if(!shapesModel.contains(TOSH.hasShape, RDF.type, (RDFNode)null)) { // Heuristic
		Model unionModel = SHACLSystemModel.getSHACLModel();
		MultiUnion unionGraph = new MultiUnion(new Graph[] {
			unionModel.getGraph(),
			shapesModel.getGraph()
		});
		shapesModel = ModelFactory.createModelForGraph(unionGraph);
	}
	return shapesModel;
}
 
Example #23
Source File: JenaTransformationInjectConnectedSegments.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<JenaConnectedSegmentsInjectMatch> matches) throws Exception {
	final Model model = driver.getModel();

	final Property length = model.getProperty(BASE_PREFIX + ModelConstants.LENGTH);
	final Property connectsTo = model.getProperty(BASE_PREFIX + ModelConstants.CONNECTS_TO);
	final Property monitoredBy = model.getProperty(BASE_PREFIX + ModelConstants.MONITORED_BY);
	final Property segmentType = model.getProperty(BASE_PREFIX + ModelConstants.SEGMENT);

	for (final JenaConnectedSegmentsInjectMatch match : matches) {
		// create (segment2) node
		final Long newVertexId = driver.generateNewVertexId();
		final Resource segment2 = model.createResource(BASE_PREFIX + ID_PREFIX + newVertexId);
		model.add(model.createStatement(segment2, RDF.type, segmentType));
		model.add(model.createLiteralStatement(segment2, length, TrainBenchmarkConstants.DEFAULT_SEGMENT_LENGTH));

		// (segment1)-[:connectsTo]->(segment2)
		model.add(match.getSegment1(), connectsTo, segment2);
		// (segment2)-[:connectsTo]->(segment3)
		model.add(segment2, connectsTo, match.getSegment3());
		// (segment2)-[:monitoredBy]->(sensor)
		model.add(segment2, monitoredBy, match.getSensor());

		// remove (segment1)-[:connectsTo]->(segment3)
		model.remove(match.getSegment1(), connectsTo, match.getSegment3());
	}
}
 
Example #24
Source File: ClassesCache.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(Resource instance) {
	StmtIterator it = instance.listProperties(RDF.type);
	while(it.hasNext()) {
		if(classes.contains(it.next().getObject())) {
			it.close();
			return true;
		}
	}
	return false;
}
 
Example #25
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the usual default namespaces for rdf, rdfs, owl and xsd.
 * @param prefixMapping  the Model to modify
 */
public static void initNamespaces(PrefixMapping prefixMapping) {
    ensurePrefix(prefixMapping, "rdf",  RDF.getURI());
    ensurePrefix(prefixMapping, "rdfs", RDFS.getURI());
    ensurePrefix(prefixMapping, "owl",  OWL.getURI());
    ensurePrefix(prefixMapping, "xsd",  XSD.getURI());
}
 
Example #26
Source File: BindingWriter.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Override
public Resource write(Model model) {
    Resource resource = ElementWriter.copyElementResourceInModel(binding, model);

    resource.addProperty(RDF.type, RDFUNITv.Binding);
    resource.addProperty(RDFUNITv.parameter, ElementWriter.copyElementResourceInModel(binding.getParameter(), model));
    resource.addProperty(RDFUNITv.bindingValue, binding.getValue());

    return resource;
}
 
Example #27
Source File: HierarchicalMatchingsCounterTest.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Resource[] createResources(int numberOfResources, Model classModel) {
    Resource resources[] = new Resource[numberOfResources];
    int startChar = (int) 'A';
    for (int i = 0; i < resources.length; ++i) {
        resources[i] = classModel.createResource(KNOWN_KB_URIS[0] + ((char) (startChar + i)));
        classModel.add(resources[i], RDF.type, RDFS.Class);
    }
    return resources;
}
 
Example #28
Source File: RouteIT.java    From fcrepo-camel-toolbox with Apache License 2.0 5 votes vote down vote up
@Test
public void testFixityOnBinary() throws Exception {
    final String webPort = System.getProperty("fcrepo.dynamic.test.port", "8080");
    final String jmsPort = System.getProperty("fcrepo.dynamic.jms.port", "61616");
    final String path = fullPath.replaceFirst("http://localhost:[0-9]+/fcrepo/rest", "");
    final String fcrepoEndpoint = "mock:fcrepo:http://localhost:8080/fcrepo/rest";
    final Namespaces ns = new Namespaces("rdf", RDF.uri);
    ns.add("fedora", REPOSITORY);
    ns.add("premis", "http://www.loc.gov/premis/rdf/v1#");

    context.getRouteDefinition("FcrepoFixity").adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            mockEndpoints("*");
        }
    });
    context.start();

    getMockEndpoint(fcrepoEndpoint).expectedMessageCount(2);
    getMockEndpoint("mock:success").expectedMessageCount(1);
    template.sendBodyAndHeader("direct:start", "", FCREPO_URI,
            "http://localhost:" + webPort + "/fcrepo/rest" + path);

    assertMockEndpointsSatisfied();

    final String body = getMockEndpoint("mock:success").assertExchangeReceived(0).getIn().getBody(String.class);
    assertTrue(body.contains(
            "<premis:hasSize rdf:datatype=\"http://www.w3.org/2001/XMLSchema#long\">74</premis:hasSize>"));
    assertTrue(body.contains(
            "<premis:hasMessageDigest rdf:resource=\"urn:sha1:" + digest + "\"/>"));
}
 
Example #29
Source File: BatchComponentReader.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
public Set<Component> getComponentsFromModel(Model model) {

        ComponentReader cr = ComponentReader.create();

        // get all instances of SHACL.ConstraintComponent and return then as Component instances
        return model.listResourcesWithProperty(RDF.type, SHACL.ConstraintComponent)
                .toSet().stream()
                .distinct()
                .map(cr::read)
                .collect(Collectors.toSet());
    }
 
Example #30
Source File: RdfResultsWriterFactoryTest.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void testOutputWellFormed() throws RdfWriterException, IOException, SAXException {

    assertThat(inputModel.isEmpty()).isFalse();

    for (Resource testExecutionResource: inputModel.listResourcesWithProperty(RDF.type, RDFUNITv.TestExecution).toList()) {
        TestExecution testExecution = TestExecutionReader.create().read(testExecutionResource);

        validateHtml(getHtmlForExecution(testExecution));
        validateXml(getXmlForExecution(testExecution));
    }
}