org.apache.jena.graph.Triple Java Examples

The following examples show how to use org.apache.jena.graph.Triple. 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: NtripleUtil.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
public static List<String[]> getSubjectAndObjectsFromNTriple(String filename, String replacePrefix) {

		List<String[]> results = new ArrayList<String[]>();

		PipedRDFIterator<Triple> iter = fileToStreamIterator(filename);

		while (iter.hasNext()) {
			Triple statement = iter.next();
			results.add(new String[] {
					replacePrefix == null || "".equals(replacePrefix) ? statement.getSubject().getURI()
							: statement.getSubject().getURI().replace(replacePrefix, ""),
					replacePrefix == null || "".equals(replacePrefix) ? statement.getObject().getURI()
							: statement.getObject().getURI().replace(replacePrefix, ""), });

		}

		iter.close();
		return null;

		// return results;
	}
 
Example #2
Source File: SPDXDocument.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @return the sha1
 * @throws InvalidSPDXAnalysisException 
 */
public String getSha1() throws InvalidSPDXAnalysisException {
	
	String retval = null;
	Node p = model.getProperty(SPDX_NAMESPACE, PROP_PACKAGE_CHECKSUM).asNode();
	Triple m = Triple.createMatch(this.node, p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		SPDXChecksum cksum = new SPDXChecksum(model, t.getObject());
		if (cksum.getAlgorithm().equals(SpdxRdfConstants.ALGORITHM_SHA1)) {
			retval = cksum.getValue();
		}
	}
	return retval;
}
 
Example #3
Source File: TraversalBuilder.java    From sparql-gremlin with Apache License 2.0 6 votes vote down vote up
public static GraphTraversal<?, ?> transform(final Triple triple) {
    final GraphTraversal<Vertex, ?> matchTraversal = __.as(triple.getSubject().getName());
    final Node predicate = triple.getPredicate();
    final String uri = predicate.getURI();
    final String uriValue = Prefixes.getURIValue(uri);
    final String prefix = Prefixes.getPrefix(uri);
    switch (prefix) {
        case "edge":
            return matchTraversal.out(uriValue).as(triple.getObject().getName());
        case "property":
            return matchProperty(matchTraversal, uriValue, PropertyType.PROPERTY, triple.getObject());
        case "value":
            return matchProperty(matchTraversal, uriValue, PropertyType.VALUE, triple.getObject());
        default:
            throw new IllegalStateException(String.format("Unexpected predicate: %s", predicate));
    }
}
 
Example #4
Source File: PredicateMappingsDataSet.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public PredicateMappingsDataSet(int numberOfHashFunctions,
		int numberOfColorFunctions) {
	this.numberOfColorFunctions = numberOfColorFunctions;
	this.numberOfHashFunctions = numberOfHashFunctions;

	Model defModel = ModelFactory.createDefaultModel();
	dataset = DatasetFactory.create(defModel);
	dataset.getDefaultModel()
			.getGraph()
			.add(new Triple(NodeFactory.createURI(Constants.ibmns
					+ Constants.NUM_COL_FUNCTION),
					NodeFactory.createURI(Constants.ibmns
							+ Constants.VALUE_PREDICATE), intToNode(numberOfColorFunctions)));

	dataset.getDefaultModel()
			.getGraph()
			.add(new Triple(NodeFactory.createURI(Constants.ibmns
					+ Constants.NUM_HASH_FUNCTION),
					NodeFactory.createURI(Constants.ibmns
							+ Constants.VALUE_PREDICATE), intToNode(numberOfHashFunctions)));
}
 
Example #5
Source File: TestSpdxFile.java    From tools with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoassertionCopyright() throws InvalidSPDXAnalysisException {
	model = ModelFactory.createDefaultModel();
	IModelContainer modelContainer = new ModelContainerForTest(model, "http://somethingunique.com/something");
	SpdxFile file = new SpdxFile("filename", null, null, null, 
			COMPLEX_LICENSE, CONJUNCTIVE_LICENSES, SpdxRdfConstants.NOASSERTION_VALUE, null,
			null, new Checksum[] {new Checksum(ChecksumAlgorithm.checksumAlgorithm_sha1,
					"1123456789abcdef0123456789abcdef01234567")}, null, null, null);
	Resource fileResource = file.createResource(modelContainer);
	Node p = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_FILE_COPYRIGHT).asNode();
	Triple m = Triple.createMatch(null, p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		assertTrue(t.getObject().isURI());
		assertEquals(SpdxRdfConstants.URI_VALUE_NOASSERTION, t.getObject().getURI());
	}
	SpdxFile file2 = new SpdxFile(modelContainer, fileResource.asNode());
	assertEquals(SpdxRdfConstants.NOASSERTION_VALUE, file2.getCopyrightText());
}
 
Example #6
Source File: RdfModelObject.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @param nameSpace
 * @param propSpdxExternalDocRef
 * @return
 * @throws InvalidSPDXAnalysisException 
 */
public static ExternalDocumentRef[] findExternalDocRefPropertyValues(
		String nameSpace, String propertyName, IModelContainer extDocModelContainer, 
		Node nodeContainingExternalRefs) throws InvalidSPDXAnalysisException {
	if (extDocModelContainer == null || nodeContainingExternalRefs == null) {
		return new ExternalDocumentRef[0];
	}
	Model model = extDocModelContainer.getModel();
	List<ExternalDocumentRef> retval = Lists.newArrayList();
	Node p = model.getProperty(nameSpace, propertyName).asNode();
	Triple m = Triple.createMatch(nodeContainingExternalRefs, p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		retval.add(new ExternalDocumentRef(extDocModelContainer, t.getObject()));
	}
	return retval.toArray(new ExternalDocumentRef[retval.size()]);
}
 
Example #7
Source File: TraversalBuilder.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
static GraphTraversal<?, ?> transform(final Triple triple) {
    final GraphTraversal<Vertex, ?> matchTraversal = __.as(triple.getSubject().getName());
    
    final Node predicate = triple.getPredicate();
    final String uri = predicate.getURI();
    final String uriValue = Prefixes.getURIValue(uri);
    final String prefix = Prefixes.getPrefix(uri);

    switch (prefix) {
        case "edge":
            return matchTraversal.out(uriValue).as(triple.getObject().getName());
        case "property":
            return matchProperty(matchTraversal, uriValue, PropertyType.PROPERTY, triple.getObject());
        case "value":
            return matchProperty(matchTraversal, uriValue, PropertyType.VALUE, triple.getObject());
        default:
            throw new IllegalStateException(String.format("Unexpected predicate: %s", predicate));
    }
}
 
Example #8
Source File: TestDOAPProject.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @param resource
 * @param resource2
 */
private void copyProperties(Resource resource, Resource resource2) {
	Triple m = Triple.createMatch(resource.asNode(), null, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		Property p = model.createProperty(t.getPredicate().getURI());
		Node value = t.getObject();
		if (value instanceof RDFNode) {
			RDFNode valuen = (RDFNode)value;
			resource2.addProperty(p, valuen);
		} else {
			resource2.addProperty(p, value.toString(false));
		}
	}
}
 
Example #9
Source File: SPDXDocument.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @return the spdxPackage
 * @throws InvalidSPDXAnalysisException 
 */
public SPDXPackage getSpdxPackage() throws InvalidSPDXAnalysisException {
	if (this.spdxPackage != null) {
		return this.spdxPackage;
	}
	Node spdxDocNode = getSpdxDocNode();
	if (spdxDocNode == null) {
		throw(new InvalidSPDXAnalysisException("Must set an SPDX doc before getting an SPDX package"));
	}
	Node p = model.getProperty(SPDX_NAMESPACE, PROP_SPDX_PACKAGE).asNode();
	Triple m = Triple.createMatch(spdxDocNode, p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	SPDXPackage newSpdxPackage = null;
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		newSpdxPackage = new SPDXPackage(t.getObject(), this);
	}
	this.spdxPackage = newSpdxPackage;
	return newSpdxPackage;
}
 
Example #10
Source File: DiffGraph.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public boolean contains(Triple t) {
	if(addedGraph.contains(t)) {
		return true;
	}
	else {
		ExtendedIterator<Triple> it = base.find(t);
		while(it.hasNext()) {
			Triple n = it.next();
			if(!deletedTriples.contains(n)) {
				it.close();
				return true;
			}
		}
		return false;
	}
}
 
Example #11
Source File: ShaclValidator.java    From rdflint with MIT License 6 votes vote down vote up
@Override
public void reportAdditionalProblem(LintProblemSet problems) {
  result.find(Node.ANY, rdfNode("type"), shaclNode("ValidationResult"))
      .mapWith(t -> t.getSubject())
      .forEachRemaining(s -> {
        final Optional<Node> subject = result
            .find(s, shaclNode("focusNode"), Node.ANY)
            .nextOptional().map(Triple::getObject);
        final Optional<Node> predicate = result
            .find(s, shaclNode("resultPath"), Node.ANY)
            .nextOptional().map(Triple::getObject);
        final Optional<Node> object = result
            .find(s, shaclNode("value"), Node.ANY)
            .nextOptional().map(Triple::getObject);
        final Node detail = result
            .find(s, shaclNode("resultMessage"), Node.ANY)
            .next().getObject(); // ValidationResult has only one resultMessage
        final Node constraint = result
            .find(s, shaclNode("sourceConstraintComponent"), Node.ANY)
            .next().getObject(); // ValidationResult has only one sourceConstraintComponent
        final String msg = buildReportMessage(subject, predicate, object, constraint, detail);
        problems.addProblem("SHACL_Additional_Check",
            new LintProblem(ErrorLevel.WARN, this, null, "shaclViolation", msg));
      });
}
 
Example #12
Source File: RDF2RDFStarTest.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
@Test
public void nestedSubject() {
	
	final String filename = "NestedSubject.ttl";
       final Graph g = convertAndLoadIntoGraph(filename);
       
       assertEquals( 1, g.size() );
       
       final Triple t = g.find().next();
       assertTrue( t.getSubject() instanceof Node_Triple );
       assertFalse( t.getPredicate() instanceof Node_Triple );
       assertFalse( t.getObject() instanceof Node_Triple );

       assertEquals( DCTerms.source.asNode(), t.getPredicate() );

       final Triple et = ( (Node_Triple) t.getSubject() ).get();
       assertEquals( DCTerms.creator.asNode(), et.getPredicate() );
}
 
Example #13
Source File: OWLQLSPARQLCompiler.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Element transform(ElementTriplesBlock tb) {
	List<Triple> triples = tb.getPattern().getList();
	// convert set of triples to a rule system
	// here is where all variables in triples are assumed to be distinguished variables
	logger.debug("Triples:\n{}", triples);
	RuleSystem rs = new TriplesToRuleSystem(tbox).toRules(triples, allVars, true);
	logger.debug("Triples as rule system:\n{}", rs);
	//
	RuleSystem outrs = compileToNonRecursiveDatalog(rs);
	logger.debug("RuleSystem:\n{}", outrs );
	if (outrs!=null) {
		Query q = RuleSystemToUnionQuery.toUnionQuery(outrs);
		return q.getQueryPattern();		
	} else {
		/*ElementTriplesBlock ts = new ElementTriplesBlock();
		Node owlNothing =  Node.createURI(OWL.Nothing.getURI());
		Node rdfType  = Node.createURI(RDF.type.getURI());
		ts.addTriple(new Triple(owlNothing, rdfType, owlNothing));
		result = ts;*/
		return tb;
	}
}
 
Example #14
Source File: SpdxDocumentContainer.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @throws InvalidSPDXAnalysisException 
 * 
 */
private void upgradeDescribesToRelationship() throws InvalidSPDXAnalysisException {
	Node p = model.getProperty(SPDX_NAMESPACE, PROP_SPDX_PACKAGE).asNode();
	Triple m = Triple.createMatch(this.documentNode, p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	List<SpdxPackage> describedPackages = Lists.newArrayList();
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		describedPackages.add(new SpdxPackage(this, t.getObject()));
	}
	for (SpdxPackage pkg:describedPackages) {
		Relationship describes = new Relationship(pkg, 
				Relationship.RelationshipType.DESCRIBES, "");
		this.getSpdxDocument().addRelationship(describes);
	}
}
 
Example #15
Source File: RdfModelObject.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * Finds multiple property values 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[] findMultiplePropertyValues(String namespace, String propertyName) {
	if (this.model == null || this.node == null) {
		return null;
	}
	List<String> retval = Lists.newArrayList();
	Node p = model.getProperty(namespace, propertyName).asNode();
	Triple m = Triple.createMatch(node, p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		if (t.getObject().isURI() && PRE_DEFINED_URI_VALUE.containsKey(t.getObject().getURI())) {
			retval.add(PRE_DEFINED_URI_VALUE.get(t.getObject().getURI()));
		} else {
			retval.add(t.getObject().toString(false));
		}
	}
	return retval.toArray(new String[retval.size()]);
}
 
Example #16
Source File: QueryIterTripleStarPatternTest.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
@Test
public void matchObjectRequiresRedundancyAugmentation()
{
	// ex:s ex:p ?V3
	final Triple tp = new Triple( $s(), $p(), $V3() );

	final Binding inputBinding = BindingFactory.binding();
	final ExecutionContext execCxt = createTestExecCxt();
	final QueryIterator input = QueryIterSingleton.create(inputBinding, execCxt);

	final QueryIterator it = QueryIterTripleStarPattern.create( input, tp, execCxt );
	assertTrue( it.hasNext() );

	final Binding outputBinding = it.nextBinding();
	assertEquals( 1, outputBinding.size() );

	assertEquals( $o(), outputBinding.get($V3()) );

	assertFalse( it.hasNext() ); 
	it.close();
}
 
Example #17
Source File: QueryIterTripleStarPatternTest.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
@Test
public void matchNothingWithGivenObjectInObjectTriple()
{
	// ?V1 ?V2 << ex:s ex:p ?V3 >>
	final Triple tp1 = new Triple( $s(), $p(), $V3() );
	final Node nTP1 = new Node_TripleStarPattern( tp1 );
	final Triple tp2 = new Triple( $V1(), $V2(), nTP1 );

	// ?V3 --> ex:x1
	final Binding inputBinding = BindingFactory.binding( $V3(), $x1() );
	final ExecutionContext execCxt = createTestExecCxt();
	final QueryIterator input = QueryIterSingleton.create(inputBinding, execCxt);

	final QueryIterator it = QueryIterTripleStarPattern.create( input, tp2, execCxt );
	assertFalse( it.hasNext() ); 
	it.close();
}
 
Example #18
Source File: SHACLUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
private static void addIncludes(Graph model, String uri, Set<Graph> graphs, Set<String> reachedURIs) {
	
	graphs.add(model);
	reachedURIs.add(uri);
	
	for(Triple t : model.find(null, OWL.imports.asNode(), null).toList()) {
		if(t.getObject().isURI()) {
			String includeURI = t.getObject().getURI();
			if(!reachedURIs.contains(includeURI)) {
				Model includeModel = ARQFactory.getNamedModel(includeURI);
				if(includeModel != null) {
					Graph includeGraph = includeModel.getGraph();
					addIncludes(includeGraph, includeURI, graphs, reachedURIs);
				}
			}
		}
	}
}
 
Example #19
Source File: DiffGraph.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public ExtendedIterator<Triple> find(Node s, Node p, Node o) {

	// First get the underlying base query (without any buffered triples)
	ExtendedIterator<Triple> base = super.find(s, p, o);

	// If deleted triples exist then continue with a filtered iterator
	if(deletedTriples.size() > 0) {
		// base without deleted triples.
		base = base.filterDrop(deletedTriples::contains);
	}

	// If added triples exist then chain the two together
	// this iterator supports remove and removes correctly for this graph
	ExtendedIterator<Triple> added = addedGraph.find(s, p, o);
	if(added.hasNext()) {
		return base.andThen(added);  // base and added are guaranteed disjoint
	}
	else {
		return base;
	}
}
 
Example #20
Source File: SPDXFile.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the resource for an existing file in the model
 * @param spdxFile
 * @return resource of an SPDX file with the same name and checksum.  Null if none found
 * @throws InvalidSPDXAnalysisException 
 */
static protected Resource findFileResource(Model model, SPDXFile spdxFile) throws InvalidSPDXAnalysisException {
	// find any matching file names
	Node fileNameProperty = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_FILE_NAME).asNode();
	Triple fileNameMatch = Triple.createMatch(null, fileNameProperty, NodeFactory.createLiteral(spdxFile.getName()));
	
	ExtendedIterator<Triple> filenameMatchIter = model.getGraph().find(fileNameMatch);	
	if (filenameMatchIter.hasNext()) {
		Triple fileMatchTriple = filenameMatchIter.next();
		Node fileNode = fileMatchTriple.getSubject();
		// check the checksum
		Node checksumProperty = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_FILE_CHECKSUM).asNode();
		Triple checksumMatch = Triple.createMatch(fileNode, checksumProperty, null);
		ExtendedIterator<Triple> checksumMatchIterator = model.getGraph().find(checksumMatch);
		if (checksumMatchIterator.hasNext()) {
			Triple checksumMatchTriple = checksumMatchIterator.next();
			SPDXChecksum cksum = new SPDXChecksum(model, checksumMatchTriple.getObject());
			if (cksum.getValue().compareToIgnoreCase(spdxFile.sha1.getValue()) == 0) {
				return RdfParserHelper.convertToResource(model, fileNode);
			}
		}
	}
	// if we get to here, we did not find a match
	return null;
}
 
Example #21
Source File: SPDXFile.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @return the sha1
 * @throws InvalidSPDXAnalysisException 
 */
public String getSha1()  {
	if (this.model != null && this.resource != null) {
		try {
			Node p = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_FILE_CHECKSUM).asNode();
			Triple m = Triple.createMatch(this.resource.asNode(), p, null);
			ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
			Triple t = null;
			while (tripleIter.hasNext()) {
				t = tripleIter.next();
				if (this.sha1 != null && nodesEquals(this.sha1.getResource().asNode(), t.getObject())) {
					break;
				}
			}
			if (this.sha1 == null || !nodesEquals(this.sha1.getResource().asNode(), t.getObject())) {
				this.sha1 = new SPDXChecksum(model, t.getObject());
			}
		} catch (InvalidSPDXAnalysisException e) {
			// just use the original sha1
		}
	}
	return this.sha1.getValue();
}
 
Example #22
Source File: RdfModelObject.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @param nameSpace
 * @param propertyName
 * @param checksumValue
 * @return
 * @throws InvalidSPDXAnalysisException 
 */
protected DoapProject[] findMultipleDoapPropertyValues(String nameSpace,
		String propertyName) throws InvalidSPDXAnalysisException {
	if (this.model == null || this.node == null) {
		return new DoapProject[0];
	}
	List<DoapProject> retval = Lists.newArrayList();
	Node p = model.getProperty(nameSpace, propertyName).asNode();
	Triple m = Triple.createMatch(node, p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		retval.add(new DoapProject(modelContainer, t.getObject()));
	}
	return retval.toArray(new DoapProject[retval.size()]);
}
 
Example #23
Source File: OWLQLCompiler.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
protected Triple renameTripleToAvoidUnboundVarCapture(Triple triple, Set<String> unboundVarsInConjQ, NewVariableGenerator varGen) {
	//Set<String> unboundVarsInQ = new HashSet<String>(getUnboundVariables(q));
	Set<String> clashingVars = getValidNameForUnboundVariable(getAllVariables(triple));
	clashingVars.retainAll(unboundVarsInConjQ);
	if (clashingVars.isEmpty()) {
		return triple;
	}
	Node subj = triple.getSubject();
	Node obj = triple.getObject();
	Node[] subjObj = new Node[]{subj, obj};
	Node pred = triple.getPredicate();
	assert pred.isURI() : "predicate must be an IRI: "+ triple;
	Node newSubj = subj;
	Node newObj = obj;
	for (int i=0;i<2;i++) {
		Node t = subjObj[i];
		if (t.isVariable()) {
			String var = t.getName();
			if (clashingVars.contains(var)) {
				assert isValidNameForUnboundVariable(var): var;
				String newVar = varGen.createNewVariable();
				if (i==0) {
					newSubj = NodeFactory.createVariable(newVar);
				} else {
					newObj = NodeFactory.createVariable(newVar);
				}
			}
		}
	}
	Triple newTriple = new Triple(newSubj, pred, newObj);
	return newTriple;
}
 
Example #24
Source File: RDFStar2RDFTest.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
protected void verifyNoNesting(Graph g)
{		
	final Iterator<Triple> iter = g.find();
	
	while (iter.hasNext()) {
		final Triple t = iter.next();
		assertFalse( t.getSubject()   instanceof Node_Triple );
		assertFalse( t.getPredicate() instanceof Node_Triple );
		assertFalse( t.getObject()    instanceof Node_Triple );
	}
}
 
Example #25
Source File: SPDXFile.java    From tools with Apache License 2.0 5 votes vote down vote up
public String getComment() {
	if (this.model != null && this.resource != null) {
		Node p = model.getProperty(SpdxRdfConstants.RDFS_NAMESPACE, SpdxRdfConstants.RDFS_PROP_COMMENT).asNode();
		Triple m = Triple.createMatch(this.resource.asNode(), p, null);
		ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
		while (tripleIter.hasNext()) {
			this.comment = tripleIter.next().getObject().toString(false);
		}
	}
	return this.comment;
}
 
Example #26
Source File: HDTStreamRDF.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void triple(Triple t) {
    CharSequence subject = FmtUtils.stringForNode(t.getSubject());
    CharSequence predicate = FmtUtils.stringForNode(t.getPredicate());
    CharSequence object = FmtUtils.stringForNode(t.getObject());
    triples.insert(
            dictionary.insert(subject, TripleComponentRole.SUBJECT),
            dictionary.insert(predicate, TripleComponentRole.PREDICATE),
            dictionary.insert(object, TripleComponentRole.OBJECT)
    );
    num++;
    size += subject.length() + predicate.length() + object.length() + 4;
    listener.notifyProgressCond(t);
}
 
Example #27
Source File: QueryIterTripleStarPattern.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
static protected boolean insert( Node inputNode,
                                 Node outputNode,
                                 BindingMap results,
                                 boolean inputNodeIsTripleWithVars )
{
	if ( inputNodeIsTripleWithVars )
    {
		if ( !(outputNode instanceof Node_Triple) )
			return false;

		final Triple outputTriple = ( (Node_Triple) outputNode ).get();
		final Triple inputTriple  = ( (Node_Triple) inputNode  ).get();

		return insert(outputTriple,
		              inputTriple.getSubject(),
		              inputTriple.getPredicate(),
		              inputTriple.getObject(),
		              results );
    }
    else if ( Var.isVar(inputNode) )
    {
    	final Var v = Var.alloc(inputNode);
        final Node x = results.get(v);
        if ( x != null )
            return outputNode.equals(x);

        results.add(v, outputNode);
        return true;
    }
    else
    	return true;
}
 
Example #28
Source File: SPDXFile.java    From tools with Apache License 2.0 5 votes vote down vote up
/**
 * @return the name
 */
public String getName() {
	if (this.model != null && this.resource != null) {
		Node p = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_FILE_NAME).asNode();
		Triple m = Triple.createMatch(this.resource.asNode(), p, null);
		ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
		while (tripleIter.hasNext()) {
			Triple t = tripleIter.next();
			this.name = t.getObject().toString(false);
		}
	}
	return this.name;
}
 
Example #29
Source File: NormalizedOWLQLTbox.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
/**
 *  returns a query triple corresponding to a left hand side concept.
 *  <ul>
 *   <li> B --> x rdf:type B </li>
 *   <li> some(R, top) --> x R ?y if  </li>
 *   <li> some(inv(R), top) --> ?y R x </li>
 *   </ul>
 * @param lhsConcept
 * @param var
 * @return
 */
protected static Triple toTriple(OWLClassExpression lhsConcept, Node var, NewVariableGenerator varGen, OWLDataFactory fac) {
	if (!lhsConcept.isAnonymous()) {
		return new Triple(
					var,
					NodeFactory.createURI(RDFConstants.RDF_TYPE),
					NodeFactory.createURI(((OWLClass)lhsConcept).getIRI().toString()));
	 } else if (lhsConcept.getClassExpressionType().equals(ClassExpressionType.OBJECT_SOME_VALUES_FROM)
			 || lhsConcept.getClassExpressionType().equals(ClassExpressionType.DATA_SOME_VALUES_FROM)) {
		 OWLQuantifiedRestriction rest = (OWLQuantifiedRestriction) lhsConcept;
		 OWLPropertyExpression prop = rest.getProperty();
		 OWLPropertyRange propRange = rest.getFiller();
		 if (prop.isObjectPropertyExpression()) {
			 prop = ((OWLObjectPropertyExpression)prop).getSimplified();
		 }
		 assert propRange.equals(fac.getOWLThing()) || propRange.equals(fac.getTopDatatype()) : propRange;
		 if (!prop.isAnonymous()) {
			 OWLProperty p = (OWLProperty) prop;
			 return new Triple(
						var,
						NodeFactory.createURI(p.getIRI().toString()),
						NodeFactory.createVariable(varGen.createNewVariable()));
		 } else {
			assert prop instanceof OWLObjectInverseOf : prop;
		 	OWLObjectInverseOf inv = (OWLObjectInverseOf) prop;
		 	assert !inv.getInverse().isAnonymous() : inv+"\n"+ "Property expression simplification failed!";
		 	OWLObjectProperty op = (OWLObjectProperty) inv.getInverse();
		 	return new Triple(
		 			NodeFactory.createVariable(varGen.createNewVariable()),
					NodeFactory.createURI(op.getIRI().toString()),
					var);
		 	
		 }
	 } else {
		 throw new RuntimeException(lhsConcept+" is not a valid concept expression in the left hand side of a subclass axiom in OWL QL");
	 }
	
}
 
Example #30
Source File: HDTStreamRDF.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public void notifyProgressCond(Triple t) {
    long now = System.currentTimeMillis();
    if (now - last > 5_000) {
        notifyProgress(num, FmtUtils.stringForTriple(t));
        reset(now);
    }
}