Java Code Examples for org.apache.jena.rdf.model.StmtIterator#hasNext()

The following examples show how to use org.apache.jena.rdf.model.StmtIterator#hasNext() . 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: 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 2
Source File: JenaUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
private static boolean hasSuperClass(Resource subClass, Resource superClass, Set<Resource> reached) {
	StmtIterator it = subClass.listProperties(RDFS.subClassOf);
	while(it.hasNext()) {
		Statement s = it.next();
		if(superClass.equals(s.getObject())) {
			it.close();
			return true;
		}
		else if(!reached.contains(s.getResource())) {
			reached.add(s.getResource());
			if(hasSuperClass(s.getResource(), superClass, reached)) {
				it.close();
				return true;
			}
		}
	}
	return false;
}
 
Example 3
Source File: JenaUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
private static Resource getFirstRange(Resource property, Set<Resource> reached) {
	Resource directRange = getFirstDirectRange(property);
	if(directRange != null) {
		return directRange;
	}
	StmtIterator it = property.listProperties(RDFS.subPropertyOf);
	while (it.hasNext()) {
		Statement ss = it.next();
		if (ss.getObject().isURIResource()) {
			Resource superProperty = ss.getResource();
			if (!reached.contains(superProperty)) {
				reached.add(superProperty);
				Resource r = getFirstRange(superProperty, reached);
				if (r != null) {
					it.close();
					return r;
				}
			}
		}
	}
	return null;
}
 
Example 4
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 5
Source File: JenaDriver.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
public void deleteOutgoingEdges(final Collection<Resource> vertices, final String edgeType) throws IOException {
	final Property property = model.getProperty(RdfConstants.BASE_PREFIX + edgeType);

	for (final Resource vertex : vertices) {
		final Selector selector = new SimpleSelector(vertex, property, (RDFNode) null);

		final StmtIterator edges = model.listStatements(selector);

		final List<Statement> statementsToRemove = new ArrayList<>();
		while (edges.hasNext()) {
			final Statement edge = edges.next();
			statementsToRemove.add(edge);
		}

		for (final Statement statement : statementsToRemove) {
			model.remove(statement);
		}
	}
}
 
Example 6
Source File: SPARQLConstraintExecutor.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
protected String getSPARQL(Constraint constraint) {
	SHSPARQLConstraint sc = SHFactory.asSPARQLConstraint(constraint.getParameterValue());
	String select = JenaUtil.getStringProperty(sc, SH.select);
	if(select == null) {
		String message = "Missing " + SH.PREFIX + ":" + SH.select.getLocalName() + " of " + RDFLabels.get().getLabel(sc);
		if(sc.isAnon()) {
			StmtIterator it = sc.getModel().listStatements(null, null, sc);
			if(it.hasNext()) {
				Statement s = it.next();
				it.close();
				message += " at " + RDFLabels.get().getLabel(s.getSubject());
				message += " via " + RDFLabels.get().getLabel(s.getPredicate());
			}
		}
		throw new SHACLException(message);
	}
	return SPARQLSubstitutions.withPrefixes(select, sc);
}
 
Example 7
Source File: ExecutionPlatform.java    From shacl with Apache License 2.0 6 votes vote down vote up
public static boolean canExecute(Resource executable) {
	StmtIterator it = executable.listProperties(DASH.requiredExecutionPlatform);
	if(!it.hasNext()) {
		return true;
	}
	else {
		while(it.hasNext()) {
			Statement s = it.next();
			if(s.getObject().isResource() && isCompatibleWith(s.getResource())) {
				it.close();
				return true;
			}
		}
		return false;
	}
}
 
Example 8
Source File: JenaUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
private static void addTransitiveObjects(Set<Resource> resources, Set<Resource> reached,
		Resource subject, Property predicate) {
	resources.add(subject);
	reached.add(subject);
	StmtIterator it = subject.listProperties(predicate);
	try {
		while (it.hasNext()) {
			RDFNode object = it.next().getObject();
			if (object instanceof Resource) {
				if (!reached.contains(object)) {
					addTransitiveObjects(resources, reached, (Resource)object, predicate);
				}
			}
		}
	}
	finally {
		it.close();
	}
}
 
Example 9
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static List<Resource> getURIResourceProperties(Resource subject, Property predicate) {
	List<Resource> results = new LinkedList<>();
	StmtIterator it = subject.listProperties(predicate);
	while(it.hasNext()) {
		Statement s = it.next();
		if(s.getObject().isURIResource()) {
			results.add(s.getResource());
		}
	}
	return results;
}
 
Example 10
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static List<Resource> getResourceProperties(Resource subject, Property predicate) {
	List<Resource> results = new LinkedList<>();
	StmtIterator it = subject.listProperties(predicate);
	while(it.hasNext()) {
		Statement s = it.next();
		if(s.getObject().isResource()) {
			results.add(s.getResource());
		}
	}
	return results;
}
 
Example 11
Source File: Skolemizer.java    From Processor with Apache License 2.0 5 votes vote down vote up
protected Literal getLiteral(Resource resource, String namePath)
{
    if (resource == null) throw new IllegalArgumentException("Resource cannot be null");

    if (namePath.contains("."))
    {
        String name = namePath.substring(0, namePath.indexOf("."));
        String nameSubPath = namePath.substring(namePath.indexOf(".") + 1);
        Resource subResource = getResource(resource, name);
        if (subResource != null) return getLiteral(subResource, nameSubPath);
    }
    
    StmtIterator it = resource.listProperties();
    try
    {
        while (it.hasNext())
        {
            Statement stmt = it.next();
            if (stmt.getObject().isLiteral() && stmt.getPredicate().getLocalName().equals(namePath))
            {
                if (log.isTraceEnabled()) log.trace("Found Literal {} for property name: {} ", stmt.getLiteral(), namePath);
                return stmt.getLiteral();
            }
        }
    }
    finally
    {
        it.close();
    }
    
    return null;
}
 
Example 12
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static List<Literal> getLiteralProperties(Resource subject, Property predicate) {
	List<Literal> results = new LinkedList<>();
	StmtIterator it = subject.listProperties(predicate);
	while(it.hasNext()) {
		Statement s = it.next();
		if(s.getObject().isLiteral()) {
			results.add(s.getLiteral());
		}
	}
	return results;
}
 
Example 13
Source File: TemplateImpl.java    From Processor with Apache License 2.0 5 votes vote down vote up
protected Map<Property, Parameter> addSuperParameters(Template template, Map<Property, Parameter> params)
{
    if (template == null) throw new IllegalArgumentException("Template Set cannot be null");
    if (params == null) throw new IllegalArgumentException("Parameter Map cannot be null");
    
    StmtIterator it = template.listProperties(LDT.extends_);
    try
    {
        while (it.hasNext())
        {
            Statement stmt = it.next();
            if (!stmt.getObject().isResource() || !stmt.getObject().asResource().canAs(Template.class))
            {
                if (log.isErrorEnabled()) log.error("Template's '{}' ldt:extends value '{}' is not an LDT Template", getURI(), stmt.getObject());
                throw new OntologyException("Template's '" + getURI() + "' ldt:extends value '" + stmt.getObject() + "' is not an LDT Template");
            }

            Template superTemplate = stmt.getObject().as(Template.class);
            Map<Property, Parameter> superArgs = superTemplate.getLocalParameters();
            Iterator<Entry<Property, Parameter>> entryIt = superArgs.entrySet().iterator();
            while (entryIt.hasNext())
            {
                Entry<Property, Parameter> entry = entryIt.next();
                params.putIfAbsent(entry.getKey(), entry.getValue()); // reject Parameters for existing predicates
            }

            addSuperParameters(superTemplate, params);  // recursion to super class
        }
    }
    finally
    {
        it.close();
    }
    
    return params;
}
 
Example 14
Source File: RdfEntityGraphConsumerTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testEntityGraphRdf()
    throws AnalysisEngineProcessException, ResourceInitializationException, IOException,
        URISyntaxException {

  processJCas(
      RdfEntityGraphConsumer.PARAM_QUERY_ENDPOINT,
      "http://localhost:3330/ds/query",
      RdfEntityGraphConsumer.PARAM_UPDATE_ENDPOINT,
      "http://localhost:3330/ds/update",
      RdfEntityGraphConsumer.PARAM_STORE_ENDPOINT,
      "http://localhost:3330/ds/data");

  Model expected = RDFDataMgr.loadModel(EXPECTED_DOCUMENT_FILE.toURI().toString());
  Model model = ds.getDefaultModel();
  Resource resource =
      expected.getResource(
          "http://baleen.dstl.gov.uk/8b408a0c7163fdfff06ced3e80d7d2b3acd9db900905c4783c28295b8c996165");
  resource.removeProperties(); // Get rid of the timestamp

  StmtIterator listStatements = expected.listStatements();
  while (listStatements.hasNext()) {
    Statement statement = listStatements.next();
    assertTrue("Missing statement " + statement.toString(), model.contains(statement));
  }
  assertTrue(model.containsAll(expected));
}
 
Example 15
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
private static void listAllProperties(Resource subject, Property predicate, Set<Property> reached,
		List<Statement> results) {
	reached.add(predicate);
	StmtIterator sit;
	Model model;
	if (subject != null) {
		sit = subject.listProperties(predicate);
		model = subject.getModel();
	}
	else {
		model = predicate.getModel();
		sit = model.listStatements(null, predicate, (RDFNode)null);
	}
	while (sit.hasNext()) {
		results.add(sit.next());
	}

	// Iterate into direct subproperties
	StmtIterator it = model.listStatements(null, RDFS.subPropertyOf, predicate);
	while (it.hasNext()) {
		Statement sps = it.next();
		if (!reached.contains(sps.getSubject())) {
			Property subProperty = asProperty(sps.getSubject());
			listAllProperties(subject, subProperty, reached, results);
		}
	}
}
 
Example 16
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 17
Source File: RdfDocumentGraphConsumerTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testDocumentGraphRdf()
    throws AnalysisEngineProcessException, ResourceInitializationException, IOException,
        URISyntaxException {

  processJCas(
      RdfDocumentGraphConsumer.PARAM_QUERY_ENDPOINT,
      "http://localhost:" + port + "/ds/query",
      RdfDocumentGraphConsumer.PARAM_UPDATE_ENDPOINT,
      "http://localhost:" + port + "/ds/update",
      RdfDocumentGraphConsumer.PARAM_STORE_ENDPOINT,
      "http://localhost:" + port + "/ds/data");

  Model expected = RDFDataMgr.loadModel(EXPECTED_DOCUMENT_FILE.toURI().toString());
  Model model = ds.getDefaultModel();
  Resource resource =
      expected.getResource(
          "http://baleen.dstl.gov.uk/8b408a0c7163fdfff06ced3e80d7d2b3acd9db900905c4783c28295b8c996165");
  resource.removeProperties(); // Get rid of the timestamp

  StmtIterator listStatements = expected.listStatements();
  while (listStatements.hasNext()) {
    Statement statement = listStatements.next();
    assertTrue("Missing statement " + statement.toString(), model.contains(statement));
  }
  assertTrue(model.containsAll(expected));
}
 
Example 18
Source File: RDFToTopicMapConverter.java    From ontopia with Apache License 2.0 5 votes vote down vote up
private void buildMappings(Model model) throws MalformedURLException {
  mappings = new HashMap();
  Property mapsTo = model.createProperty(RTM_MAPSTO);
  StmtIterator it = model.listStatements(null, mapsTo, (RDFNode) null);
  while (it.hasNext()) {
    Statement stmt = (Statement) it.next();
    StatementHandler mapper = getMapper(stmt.getSubject(), stmt.getObject(), model);
    mappings.put(stmt.getSubject().getURI(), mapper);
  }
  it.close();
}
 
Example 19
Source File: SHACLPaths.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static void addValueNodes(RDFNode focusNode, Property predicate, Collection<RDFNode> results) {
	if(focusNode instanceof Resource) {
		StmtIterator it = ((Resource)focusNode).listProperties(predicate);
		while(it.hasNext()) {
			results.add(it.next().getObject());
		}
	}
}
 
Example 20
Source File: SystemTest.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
@Test
void integration_test() {

    Model mainModel = ModelFactory.createDefaultModel();
    final URL dbpediaContentUrl = getClass().getClassLoader().getResource("test_services/dbpedia.ttl");
    if(dbpediaContentUrl != null) {
        mainModel.read(dbpediaContentUrl.toString(), "TTL");
    }

    Model citiesModel = ModelFactory.createDefaultModel();
    final URL citiesContentUrl = getClass().getClassLoader().getResource("test_services/cities.ttl");
    if(citiesContentUrl != null) {
        citiesModel.read(citiesContentUrl.toString(), "TTL");
    }

    Model expectedModel = ModelFactory.createDefaultModel();
    expectedModel.add(mainModel).add(citiesModel);

    Dataset ds = DatasetFactory.createTxnMem();
    ds.setDefaultModel(citiesModel);
    FusekiServer server = FusekiServer.create()
            .add("/ds", ds)
            .build()
            .start();

    HGQLConfig externalConfig = HGQLConfig.fromClasspathConfig("test_services/externalconfig.json");

    Controller externalController = new Controller();
    externalController.start(externalConfig);

    HGQLConfig config = HGQLConfig.fromClasspathConfig("test_services/mainconfig.json");

    Controller controller = new Controller();
    controller.start(config);

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode bodyParam = mapper.createObjectNode();

    bodyParam.put("query", "{\n" +
            "  Person_GET {\n" +
            "    _id\n" +
            "    label\n" +
            "    name\n" +
            "    birthPlace {\n" +
            "      _id\n" +
            "      label\n" +
            "    }\n" +
            "    \n" +
            "  }\n" +
            "  City_GET {\n" +
            "    _id\n" +
            "    label}\n" +
            "}");

    Model returnedModel = ModelFactory.createDefaultModel();

    try {
        HttpResponse<InputStream> response = Unirest.post("http://localhost:8080/graphql")
                .header("Accept", "application/rdf+xml")
                .body(bodyParam.toString())
                .asBinary();


        returnedModel.read(response.getBody(), "RDF/XML");

    } catch (UnirestException e) {
        e.printStackTrace();
    }

    Resource res = ResourceFactory.createResource("http://hypergraphql.org/query");
    Selector sel = new SelectorImpl(res, null, (Object) null);
    StmtIterator iterator = returnedModel.listStatements(sel);
    Set<Statement> statements = new HashSet<>();
    while (iterator.hasNext()) {
        statements.add(iterator.nextStatement());
    }

    for (Statement statement : statements) {
        returnedModel.remove(statement);
    }

    StmtIterator iterator2 = expectedModel.listStatements();
    while (iterator2.hasNext()) {
        assertTrue(returnedModel.contains(iterator2.next()));
    }

    assertTrue(expectedModel.isIsomorphicWith(returnedModel));
    externalController.stop();
    controller.stop();
    server.stop();
}