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

The following examples show how to use org.apache.jena.rdf.model.StmtIterator#next() . 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: 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 2
Source File: Skolemizer.java    From Processor with Apache License 2.0 6 votes vote down vote up
protected Resource getResource(Resource resource, String name)
{
    if (resource == null) throw new IllegalArgumentException("Resource cannot be null");
    
    StmtIterator it = resource.listProperties();
    try
    {
        while (it.hasNext())
        {
            Statement stmt = it.next();
            if (stmt.getObject().isAnon() && stmt.getPredicate().getLocalName().equals(name))
            {
                if (log.isTraceEnabled()) log.trace("Found Resource {} for property name: {} ", stmt.getResource(), name);
                return stmt.getResource();
            }
        }
    }
    finally
    {
        it.close();
    }
    
    return null;
}
 
Example 3
Source File: SimpleSubClassInferencer.java    From gerbil with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void inferSubClasses(String classURI, ClassSet hierarchy, ClassNodeFactory<? extends ClassNode> factory) {
    Resource classResource = new ResourceImpl(classURI);
    Set<String> alreadySeenUris = new HashSet<String>();
    addOrUpdateUri(classResource, hierarchy, factory, alreadySeenUris);

    if (!classModel.containsResource(classResource)) {
        return;
    }

    StmtIterator iterator = classModel.listStatements(null, RDFS.subClassOf, classResource);
    Statement stmt;
    Resource resource;
    while (iterator.hasNext()) {
        stmt = iterator.next();
        resource = stmt.getSubject();
        if (!alreadySeenUris.contains(resource.getURI())) {
            addOrUpdateUri(resource, hierarchy, factory, alreadySeenUris);
        }
    }
}
 
Example 4
Source File: JenaTransformationRepairPosLength.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void activate(final Collection<JenaPosLengthMatch> matches) throws IOException {
	final Model model = driver.getModel();
	final Property lengthProperty = model.getProperty(BASE_PREFIX + LENGTH);

	for (final JenaPosLengthMatch match : matches) {
		final Resource segment = match.getSegment();
		final int length = match.getLength().getInt();
		final int newLength = -length + 1;

		final Selector selector = new SimpleSelector(segment, lengthProperty, (RDFNode) null);
		final StmtIterator statementsToRemove = model.listStatements(selector);
		if (statementsToRemove.hasNext()) {
			final Statement oldStatement = statementsToRemove.next();
			model.remove(oldStatement);
		}
		
		final Statement newStatement = model.createLiteralStatement(segment, lengthProperty, newLength);
		model.add(newStatement);
	}
}
 
Example 5
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 6
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 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: 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 9
Source File: OrConstraintExecutor.java    From shacl with Apache License 2.0 6 votes vote down vote up
private boolean hasOnlyDatatypeConstraints() {
	if(shapes.size() == 0) {
		return false;
	}
	for(Resource shape : shapes) {
		StmtIterator mit = shape.listProperties();
		if(mit.hasNext()) {
			Statement s = mit.next();
			if(!SH.datatype.equals(s.getPredicate()) || mit.hasNext() || !s.getObject().isURIResource()) {
				mit.close();
				return false;
			}
		}
		else {
			return false;
		}
	}
	return true;
}
 
Example 10
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 11
Source File: DeclarativeFunctionDrivers.java    From shacl with Apache License 2.0 5 votes vote down vote up
private DeclarativeFunctionDriver getDirectDriver(Resource spinFunction) {
	if(!spinFunction.hasProperty(SPIN_ABSTRACT, JenaDatatypes.TRUE) &&
		!spinFunction.hasProperty(DASH.abstract_, JenaDatatypes.TRUE)) {
		StmtIterator it = spinFunction.listProperties();
		while(it.hasNext()) {
			Statement s = it.next();
			final DeclarativeFunctionDriver driver = drivers.get(s.getPredicate());
			if(driver != null) {
				it.close();
				return driver;
			}
		}
	}
	return null;
}
 
Example 12
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 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: JenaTransformationInjectSwitchSet.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<JenaSwitchSetInjectMatch> matches) {
	final Model model = driver.getModel();
	final Property currentPositionProperty = model.getProperty(BASE_PREFIX + CURRENTPOSITION);

	for (final JenaSwitchSetInjectMatch match : matches) {
		final Resource sw = match.getSw();
		
		final Selector selector = new SimpleSelector(sw, currentPositionProperty, (RDFNode) null);
		final StmtIterator statementsToRemove = model.listStatements(selector);
		if (!statementsToRemove.hasNext()) {
			continue;

		}

		// delete old statement
		final Statement oldStatement = statementsToRemove.next();
		model.remove(oldStatement);

		// get next enum value
		final Resource currentPositionResource = oldStatement.getObject().asResource();
		final String currentPositionRDFString = currentPositionResource.getLocalName();
		final String currentPositionString = RdfHelper.removePrefix(Position.class, currentPositionRDFString);
		final Position currentPosition = Position.valueOf(currentPositionString);
		final Position newCurrentPosition = Position.values()[(currentPosition.ordinal() + 1) % Position.values().length];
		final String newCurrentPositionString = RdfHelper.addEnumPrefix(newCurrentPosition);
		final Resource newCurrentPositionResource = model.createResource(BASE_PREFIX + newCurrentPositionString);

		// set new value
		final Statement newStatement = model.createLiteralStatement(sw, currentPositionProperty, newCurrentPositionResource);
		model.add(newStatement);

	}
}
 
Example 15
Source File: SimpleSubClassInferencer.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addOrUpdateUri(Resource resource, ClassSet hierarchy, ClassNodeFactory<? extends ClassNode> factory,
        Set<String> alreadySeenUris) {
    String uri = resource.getURI();
    ClassNode node = hierarchy.getNode(uri);
    if (node == null) {
        node = factory.createNode(uri);
        hierarchy.addNode(node);
    } else {
        factory.updateNode(node);
    }
    alreadySeenUris.add(uri);

    StmtIterator iterator = classModel.listStatements(resource, OWL.sameAs, (RDFNode) null);
    Statement stmt;
    while (iterator.hasNext()) {
        stmt = iterator.next();
        uri = stmt.getObject().asResource().getURI();
        hierarchy.addUriToNode(node, uri);
        alreadySeenUris.add(uri);
    }
    iterator = classModel.listStatements(resource, OWL.equivalentClass, (RDFNode) null);
    while (iterator.hasNext()) {
        stmt = iterator.next();
        uri = stmt.getObject().asResource().getURI();
        hierarchy.addUriToNode(node, uri);
        alreadySeenUris.add(uri);
    }
}
 
Example 16
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 17
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 18
Source File: RDFToTopicMapConverter.java    From ontopia with Apache License 2.0 5 votes vote down vote up
private void doConversion(Model model) throws JenaException {
  StatementHandler totm = new ToTMStatementHandler();
  AResourceWrapper subjw = new AResourceWrapper();
  AResourceWrapper propw = new AResourceWrapper();
  AResourceWrapper objtw = new AResourceWrapper();
  ALiteralWrapper litlw = new ALiteralWrapper();

  ResIterator it = model.listSubjects();
  while (it.hasNext()) {
    Resource subject = (Resource) it.next();

    StmtIterator it2 = subject.listProperties(); // get all statements
    while (it2.hasNext()) {
      Statement stmt = (Statement) it2.next();

      subjw.resource = stmt.getSubject();
      propw.resource = stmt.getPredicate();

      RDFNode obj = stmt.getObject();
      if (obj instanceof Resource) {
        objtw.resource = (Resource) obj;
        totm.statement(subjw, propw, objtw);
      } else {
        litlw.literal = (Literal) obj;
        totm.statement(subjw, propw, litlw);
      }
    }
  }
}
 
Example 19
Source File: Exporter.java    From fcrepo-import-export with Apache License 2.0 4 votes vote down vote up
/**
 * Initiates export of versions for the given resource if it is a versioned resourced
 * 
 * @param uri resource uri
 * @throws FcrepoOperationFailedException
 * @throws IOException
 */
private void exportVersions(final URI uri) throws FcrepoOperationFailedException, IOException {
    // Do not check for versions if disabled, already exporting a version, or the repo root
    if (!config.includeVersions() || uri.equals(repositoryRoot)) {
        return;
    }

    // Resolve the timemap endpoint for this resource
    final URI timemapURI;
    try (FcrepoResponse response = client().head(uri).disableRedirects().perform()) {
        checkValidResponse(response, uri, config.getUsername());
        if (response.getLinkHeaders("type").stream()
            .filter(x -> x.toString().equals(MEMENTO.getURI()))
            .count() > 0) {
            logger.trace("Resource {} is a memento and therefore not versioned:  ", uri);
            return;
        } else if (response.getLinkHeaders("type").stream()
            .filter(x -> x.toString().equals(TIMEMAP.getURI()))
            .count() > 0) {
            logger.trace("Resource {} is a timemap and therefore not versioned:  ", uri);
            return;
        }

        timemapURI = response.getLinkHeaders("timemap").stream().findFirst().orElse(null);
        if (timemapURI == null) {
            logger.trace("Resource {} is not versioned:  no rel=\"timemap\" Link header present on {}", uri);
            return;
        }
    }

    export(timemapURI);

    try (FcrepoResponse response = client().get(timemapURI).accept(config.getRdfLanguage()).perform()) {
       // Verify that timemapURI can be accessed, which will fail if the resource is not versioned
        checkValidResponse(response, timemapURI, config.getUsername());
        // Extract uris of mementos for export
        final Model model = createDefaultModel().read(response.getBody(), null, config.getRdfLanguage());
        final StmtIterator versionsIt = model.listStatements();
        while (versionsIt.hasNext()) {
            final Statement versionSt = versionsIt.next();
            if (versionSt.getPredicate().equals(CONTAINS)) {
                final Resource versionResc = versionSt.getResource();
                exportLogger.info("Exporting version: {}", versionResc.getURI());
                logger.info("Exporting version {} for {}", versionResc.getURI(), uri);
                export(URI.create(versionResc.getURI()));
            }
        }
    }
}
 
Example 20
Source File: HtmlTriplePatternFragmentWriterImpl.java    From Server.Java with MIT License 4 votes vote down vote up
/**
 *
 * @param outputStream
 * @param datasource
 * @param fragment
 * @param tpfRequest
 * @throws IOException
 * @throws TemplateException
 */
@Override
public void writeFragment(ServletOutputStream outputStream, IDataSource datasource, ITriplePatternFragment fragment,  ITriplePatternFragmentRequest tpfRequest) throws IOException, TemplateException{
    Map data = new HashMap();
    
    // base.ftl.html
    data.put("assetsPath", "assets/");
    data.put("header", datasource.getTitle());
    data.put("date", new Date());
    
    // fragment.ftl.html
    data.put("datasourceUrl", tpfRequest.getDatasetURL());
    data.put("datasource", datasource);
    
    // Parse controls to template variables
    StmtIterator controls = fragment.getControls();
    while (controls.hasNext()) {
        Statement control = controls.next();
        
        String predicate = control.getPredicate().getURI();
        RDFNode object = control.getObject();
        if (!object.isAnon()) {
            String value = object.isURIResource() ? object.asResource().getURI() : object.asLiteral().getLexicalForm();
            data.put(predicate.replaceFirst(HYDRA, ""), value);
        }
    }
    
    // Add metadata
    data.put("totalEstimate", fragment.getTotalSize());
    data.put("itemsPerPage", fragment.getMaxPageSize());
    
    // Add triples and datasources
    List<Statement> triples = fragment.getTriples().toList();
    data.put("triples", triples);
    data.put("datasources", getDatasources());
    
    // Calculate start and end triple number
    Long start = ((tpfRequest.getPageNumber() - 1) * fragment.getMaxPageSize()) + 1;
    data.put("start", start);
    data.put("end", start + (triples.size() < fragment.getMaxPageSize() ? triples.size() : fragment.getMaxPageSize()));
    
    // Compose query object
    Map query = new HashMap();
    query.put("subject", !tpfRequest.getSubject().isVariable() ? tpfRequest.getSubject().asConstantTerm() : "");
    query.put("predicate", !tpfRequest.getPredicate().isVariable() ? tpfRequest.getPredicate().asConstantTerm() : "");
    query.put("object", !tpfRequest.getObject().isVariable() ? tpfRequest.getObject().asConstantTerm() : "");
    data.put("query", query);
   
    // Get the template (uses cache internally)
    Template temp = datasource instanceof IndexDataSource ? indexTemplate : datasourceTemplate;

    // Merge data-model with template
    temp.process(data, new OutputStreamWriter(outputStream));
}