Java Code Examples for org.apache.jena.graph.Triple#getSubject()

The following examples show how to use org.apache.jena.graph.Triple#getSubject() . 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: OWLQLCompiler.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
protected String getKey(Triple t) {
	Node subj = t.getSubject();
	Node obj = t.getObject();
	Node pred = t.getPredicate();
	if (!pred.isURI()) {
		return null;
	}
	if (!subj.isVariable() && !obj.isVariable()) {
		return null;
	}
	if (pred.getURI().equals(RDFConstants.RDF_TYPE)) {
		return obj.isURI()? obj.getURI() : null;
	} else {
		return pred.getURI();
	}
	
}
 
Example 2
Source File: QueryIterTripleStarPattern.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
static public QueryIterator create( QueryIterator input,
                                       Triple tp,
                                       ExecutionContext cxt )
{
	if (   tp.getSubject() instanceof Node_Triple
	    || tp.getObject()  instanceof Node_Triple
		|| tp.getSubject().isVariable()
		|| tp.getObject().isVariable() )
	{
		return new QueryIterTripleStarPattern(input, tp, cxt);
	}
	else
	{
		return new QueryIterTriplePattern(input, tp, cxt);
	}
}
 
Example 3
Source File: Node_TripleStarPattern.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
static public Triple asTripleWithNode_TripleStarPatterns( Triple t )
{
	final Node s = t.getSubject();
	final Node s2;
	if ( s instanceof Node_Triple )
		s2 = asNode_TripleStarPattern( (Node_Triple) s );
	else
		s2 = s;

	final Node o = t.getObject();
	final Node o2;
	if ( o instanceof Node_Triple )
		o2 = asNode_TripleStarPattern( (Node_Triple) o );
	else
		o2 = o;

	if ( s == s2 && o == o2 )
		return t;
	else
		return new Triple(s2, t.getPredicate(), o2);
}
 
Example 4
Source File: SpdxSnippet.java    From tools with Apache License 2.0 6 votes vote down vote up
@Override
public Resource findDuplicateResource(IModelContainer modelContainer, String uri) throws InvalidSPDXAnalysisException {
	if (this.snippetFromFile == null) {
		return null;
	}
	if (this.byteRange == null) {
		return null;
	}
	Resource snippetFromFileResource = SpdxFile.findFileResource(modelContainer, this.snippetFromFile);
	if (snippetFromFileResource == null) {
		return null;
	}
	Model model = modelContainer.getModel();
	Node snippetFromFileProperty = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_SNIPPET_FROM_FILE).asNode();
	Triple fileMatch = Triple.createMatch(null, snippetFromFileProperty, snippetFromFileResource.asNode());
	
	ExtendedIterator<Triple> fileMatchIter = model.getGraph().find(fileMatch);	
	while (fileMatchIter.hasNext()) {
		Triple fileMatchTriple = fileMatchIter.next();
		SpdxSnippet localSnippet = new SpdxSnippet(modelContainer, fileMatchTriple.getSubject());
		if (this.byteRange.equivalent(localSnippet.getByteRange())) {
			return model.asRDFNode(fileMatchTriple.getSubject()).asResource();
		}
	}
	return null;
}
 
Example 5
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 6
Source File: LicenseException.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * Searches the model for a exception with the ID
 * @param model
 * @param id
 * @return Node containing the exception or Null if none found
 */
public static Node findException(Model model, String id) {
	Property idProperty = model.createProperty(SpdxRdfConstants.SPDX_NAMESPACE, 
			SpdxRdfConstants.PROP_LICENSE_EXCEPTION_ID);
	Property typeProperty = model.getProperty(SpdxRdfConstants.RDF_NAMESPACE, 
			SpdxRdfConstants.RDF_PROP_TYPE);
	Property exceptionTypeProperty = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE,
			SpdxRdfConstants.CLASS_SPDX_LICENSE_EXCEPTION);
	Triple m = Triple.createMatch(null, idProperty.asNode(), null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		if (t.getObject().toString(false).equals(id)) {
			Triple typeMatch = Triple.createMatch(t.getSubject(), typeProperty.asNode(), exceptionTypeProperty.asNode());
			ExtendedIterator<Triple> typeTripleIter = model.getGraph().find(typeMatch);
			if (typeTripleIter.hasNext()) {
				return t.getSubject();
			}
		}
	}
	return null;
}
 
Example 7
Source File: ElementTransformSPARQLStar.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
protected void unNestBindClause( Triple tp, ElementPathBlock epb, Var var )
{
	Node s = tp.getSubject();
	Node p = tp.getPredicate();
	Node o = tp.getObject();

	if ( s instanceof Node_Triple )
	{
		final Triple sTP = ( (Node_Triple) s ).get();
		s = unNestTriplePattern(sTP, epb, true);
	}

	if ( o instanceof Node_Triple )
	{
		final Triple oTP = ( (Node_Triple) o ).get();
		o = unNestTriplePattern(oTP, epb, true);
	}

	final Triple nonnestedTP = new Triple(s, p, o);

	if ( ! doneNested.containsKey(nonnestedTP) )
	{
		epb.addTriple(nonnestedTP);
		epb.addTriple( new Triple(var, RDF.Nodes.type,      RDF.Nodes.Statement) );
		epb.addTriple( new Triple(var, RDF.Nodes.subject,   s) );
		epb.addTriple( new Triple(var, RDF.Nodes.predicate, p) );
		epb.addTriple( new Triple(var, RDF.Nodes.object,    o) );
		doneNested.put(nonnestedTP, var);
	}
}
 
Example 8
Source File: SpdxFile.java    From tools with Apache License 2.0 5 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(IModelContainer modelContainer, SpdxFile spdxFile) throws InvalidSPDXAnalysisException {
	// find any matching file names
	Model model = modelContainer.getModel();
	Node fileNameProperty = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_FILE_NAME).asNode();
	if (spdxFile.getName() == null) {
		return null;	// Can't match without a name
	}
	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();
			Checksum cksum = new Checksum(modelContainer, checksumMatchTriple.getObject());
			if (cksum.getAlgorithm().equals(ChecksumAlgorithm.checksumAlgorithm_sha1) &&
					cksum.getValue().compareToIgnoreCase(spdxFile.getSha1()) == 0) {
				return RdfParserHelper.convertToResource(model, fileNode);
			}
		}
	}
	// if we get to here, we did not find a match
	return null;
}
 
Example 9
Source File: SPDXDocument.java    From tools with Apache License 2.0 5 votes vote down vote up
/**
 * @return the spdx doc node from the model
 */
private Node getSpdxDocNode() {
	Node spdxDocNode = null;
	Node rdfTypePredicate = this.model.getProperty(RDF_NAMESPACE, RDF_PROP_TYPE).asNode();
	Node spdxDocObject = this.model.getProperty(SPDX_NAMESPACE, CLASS_SPDX_DOCUMENT).asNode();
	Triple m = Triple.createMatch(null, rdfTypePredicate, spdxDocObject);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	// find the document
	while (tripleIter.hasNext()) {
		Triple docTriple = tripleIter.next();
		spdxDocNode = docTriple.getSubject();
	}
	return spdxDocNode;
}
 
Example 10
Source File: SPDXChecksum.java    From tools with Apache License 2.0 5 votes vote down vote up
protected static Resource findSpdxChecksum(Model model, SPDXChecksum checksum) throws InvalidSPDXAnalysisException {
	// find any matching checksum values
	Node checksumValueProperty = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CHECKSUM_VALUE).asNode();
	Triple checksumValueMatch = Triple.createMatch(null, checksumValueProperty, NodeFactory.createLiteral(checksum.getValue()));
	ExtendedIterator<Triple> checksumMatchIter = model.getGraph().find(checksumValueMatch);	
	while (checksumMatchIter.hasNext()) {
		Triple checksumMatchTriple = checksumMatchIter.next();
		Node checksumNode = checksumMatchTriple.getSubject();
		// check the algorithm
		Node algorithmProperty = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_CHECKSUM_ALGORITHM).asNode();
		Triple algorithmMatch = Triple.createMatch(checksumNode, algorithmProperty, null);
		ExtendedIterator<Triple> algorithmMatchIterator = model.getGraph().find(algorithmMatch);
		if (algorithmMatchIterator.hasNext()) {
			String algorithm = "UNKNOWN";
			Triple algorithmMatchTriple = algorithmMatchIterator.next();
			if (algorithmMatchTriple.getObject().isLiteral()) {
				// The following is for compatibility with rdf generated with older
				// versions of the tool
				algorithm = algorithmMatchTriple.getObject().toString(false);
			} else if (algorithmMatchTriple.getObject().isURI()) {
				algorithm = URI_TO_ALGORITHM.get(algorithmMatchTriple.getObject().getURI());
				if (algorithm == null) {
					algorithm = "UNKNOWN";
				}
			}
			if (algorithm.equals(checksum.getAlgorithm())) {
				return RdfParserHelper.convertToResource(model, checksumNode);
			}
		}
	}
	// if we get to here, we did not find a match
	return null;
}
 
Example 11
Source File: RDFStarUtils.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
/**
 * If the given triple is a nested triple that has another triple in its
 * subject position, return that subject triple; otherwise return null.
 */
static public Triple getSubjectTriple( Triple t )
{
	final Node s = t.getSubject();
	if ( s instanceof Node_Triple )
		return ( (Node_Triple) s ).get();
	else
		return null;
}
 
Example 12
Source File: OWLQLCompiler.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
protected Set<String> getAllVariables(Triple t) {
	Set<String> ret = new HashSet<String>();
	Node s = t.getSubject();
	Node o = t.getObject();
	if (s.isVariable()) {
		ret.add(s.getName());
	}
	if (o.isVariable()) {
		ret.add(o.getName());
	}
	return ret;
}
 
Example 13
Source File: TextOutputStar.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
protected String getAsString( Triple t ) {
	//String result = "<< ";
	String result = "";

	final Node s = t.getSubject();
	if ( s instanceof Node_Triple ) {
    	final Triple st = ( (Node_Triple) s ).get();
		//result += getAsString(st) + " ";
		result += "<< " + getAsString(st) + ">> ";
	}
	else
		result += FmtUtils.stringForNode(s, context) + " ";

	result += FmtUtils.stringForNode(t.getPredicate(), context) + " ";

	final Node o = t.getObject();
	if ( o instanceof Node_Triple ) {
    	final Triple ot = ( (Node_Triple) o ).get();
		//result += getAsString(ot) + " ";
		result += "<< " + getAsString(ot) + ">> ";
	}
	else
		result += FmtUtils.stringForNode(o, context) + " ";

	//result += ">>";
	return result;
}
 
Example 14
Source File: SPARQLExtFormatterElement.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(ElementPathBlock el) {
    // Write path block - don't put in a final trailing "." 
    if (el.isEmpty()) {
        out.println("# Empty BGP");
        return;
    }

    // Split into BGP-path-BGP-...
    // where the BGPs may be empty.
    PathBlock pBlk = el.getPattern();
    BasicPattern bgp = new BasicPattern();
    boolean first = true;      // Has anything been output?
    for (TriplePath tp : pBlk) {
        if (tp.isTriple()) {
            Triple t = tp.asTriple();
            Node s = t.getSubject();
            if(s.isVariable()) {
                s = Var.alloc(Var.canonical(((Var)s).getVarName()));
            }
            Node p = t.getPredicate();
            Node o = t.getObject();
            if(o.isVariable()) {
                o = Var.alloc(Var.canonical(((Var)o).getVarName()));
            }
            bgp.add(new Triple(s, p, o));
            continue;
        }

        if (!bgp.isEmpty()) {
            if (!first) {
                out.println(" .");
            }
            flush(bgp);
            first = false;
        }
        if (!first) {
            out.println(" .");
        }
        // Path
        printSubject(tp.getSubject());
        out.print(" ");
        SPARQLExtPathWriter.write(out, tp.getPath(), context);
        out.print(" ");
        printObject(tp.getObject());
        first = false;
    }
    // Flush any stored triple patterns.
    if (!bgp.isEmpty()) {
        if (!first) {
            out.println(" .");
        }
        flush(bgp);
        first = false;
    }
}
 
Example 15
Source File: SPARQLExtFormatterElement.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
@Override
protected void formatTriples(BasicPattern triples) {
    if (!PRETTY_PRINT) {
        super.formatTriples(triples);
        return;
    }

    // TODO RDF Collections - spot the parsers pattern
    if (triples.isEmpty()) {
        return;
    }

    setWidths(triples);
    if (subjectWidth > TRIPLES_SUBJECT_COLUMN) {
        subjectWidth = TRIPLES_SUBJECT_COLUMN;
    }
    if (predicateWidth > TRIPLES_PROPERTY_COLUMN) {
        predicateWidth = TRIPLES_PROPERTY_COLUMN;
    }

    // Loops:
    List<Triple> subjAcc = new ArrayList<>(); // Accumulate all triples
    // with the same subject.
    Node subj = null; // Subject being accumulated

    boolean first = true; // Print newlines between blocks.

    int indent = -1;
    for (Triple t : triples) {
        if (subj != null && t.getSubject().equals(subj)) {
            subjAcc.add(t);
            continue;
        }

        if (subj != null) {
            if (!first) {
                out.println(" .");
            }
            formatSameSubject(subj, subjAcc);
            first = false;
            // At end of line of a block of triples with same subject.
            // Drop through and start new block of same subject triples.
        }

        // New subject
        subj = t.getSubject();
        subjAcc.clear();
        subjAcc.add(t);
    }

    // Flush accumulator
    if (subj != null && subjAcc.size() != 0) {
        if (!first) {
            out.println(" .");
        }
        first = false;
        formatSameSubject(subj, subjAcc);
    }
}
 
Example 16
Source File: LogUtils.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
public static Triple compress(Triple t) {
    Node o = compress(t.getObject());
    return new Triple(t.getSubject(), t.getPredicate(), o);
}
 
Example 17
Source File: RDFStar2RDFTest.java    From RDFstarTools with Apache License 2.0 4 votes vote down vote up
@Test
public void doubleNestedObject()
{
	final String filename = "doubleNestedObject.ttls";
       final Graph g = convertAndLoadIntoGraph(filename);

       assertEquals( 11, g.size() );

       verifyNoNesting(g);

       int cntTypeStmt = 0;
       int cntSubjectStmt = 0;
       int cntPredicateStmt1 = 0;
       int cntPredicateStmt2 = 0;
       int cntObjectStmt = 0;
       int cntReifiedStmt1 = 0;
       int cntReifiedStmt2 = 0;
       int cntMetaStmt = 0;

       final Iterator<Triple> it = g.find();
       while ( it.hasNext() )
       {
       	final Triple t = it.next();
       	final Node s = t.getSubject();
       	final Node p = t.getPredicate();
       	final Node o = t.getObject();

       	if ( p.equals(RDF.type.asNode()) && o.equals(RDF.Statement.asNode()) )
       		cntTypeStmt++;
       	else if ( p.equals(RDF.subject.asNode()) )
       		cntSubjectStmt++;
       	else if ( p.equals(RDF.predicate.asNode()) && o.equals(FOAF.knows.asNode()) )
       		cntPredicateStmt1++;
       	else if ( p.equals(RDF.predicate.asNode()) && o.equals(DCTerms.created.asNode()) )
       		cntPredicateStmt2++;
       	else if ( p.equals(RDF.object.asNode()) )
       		cntObjectStmt++;
       	else if ( p.equals(FOAF.knows.asNode()) && s.getURI().contains("alice") )
       		cntReifiedStmt1++;
       	else if ( p.equals(DCTerms.created.asNode()) )
       		cntReifiedStmt2++;
       	else if ( p.equals(FOAF.knows.asNode()) )
       		cntMetaStmt++;
       }

       assertEquals( 2, cntTypeStmt );
       assertEquals( 2, cntSubjectStmt );
       assertEquals( 1, cntPredicateStmt1 );
       assertEquals( 1, cntPredicateStmt2 );
       assertEquals( 2, cntObjectStmt );
       assertEquals( 1, cntReifiedStmt1 );
       assertEquals( 1, cntReifiedStmt2 );
       assertEquals( 1, cntMetaStmt );
}
 
Example 18
Source File: RDFStarUtils.java    From RDFstarTools with Apache License 2.0 4 votes vote down vote up
/**
 * Return true if the given triple is a nested triple, that is,
 * it has another triple in its subject or its object position. 
 */
static public boolean isNested( Triple t )
{
	return ( t.getSubject() instanceof Node_Triple ) && ( t.getObject() instanceof Node_Triple );
}
 
Example 19
Source File: SpdxPackage.java    From tools with Apache License 2.0 4 votes vote down vote up
@Override
public Resource findDuplicateResource(IModelContainer modelContainer, String uri) throws InvalidSPDXAnalysisException {
	// A duplicate package has the same name and verification code
	if (this.name == null || this.name.isEmpty()) {
		return null;
	}
	if (this.packageVerificationCode == null) {
		return null;
	}
	if (this.packageVerificationCode.getValue() == null || this.packageVerificationCode.getValue().isEmpty()) {
		return null;
	}
	Model localModel = modelContainer.getModel();
	// look for a matching name
	Node nameProperty = localModel.getProperty(SPDX_NAMESPACE, this.getNamePropertyName()).asNode();
	Node verificationCodeProperty = localModel.getProperty(SPDX_NAMESPACE, PROP_PACKAGE_VERIFICATION_CODE).asNode();
	Node verificationCodeValueProperty = localModel.getProperty(SPDX_NAMESPACE, PROP_VERIFICATIONCODE_VALUE).asNode();

	Triple nameMatch = Triple.createMatch(null, nameProperty, NodeFactory.createLiteral(this.name));
	ExtendedIterator<Triple> nameleIter = localModel.getGraph().find(nameMatch);
	while (nameleIter.hasNext()) {
		Triple t = nameleIter.next();
		// Check for the package verification code
		Node packageNode = t.getSubject();
		Triple verifcationMatch = Triple.createMatch(packageNode, verificationCodeProperty, null);
		ExtendedIterator<Triple> verificationIter = localModel.getGraph().find(verifcationMatch);
		while (verificationIter.hasNext()) {
			Triple vt = verificationIter.next();
			Triple valueMatch = Triple.createMatch(vt.getObject(), verificationCodeValueProperty, null);
			ExtendedIterator<Triple> valueIter = localModel.getGraph().find(valueMatch);
			while (valueIter.hasNext()) {
				Triple valuetrip = valueIter.next();
				String verificationCodeValue = valuetrip.getObject().toString(false);
				if (this.packageVerificationCode.getValue().equals(verificationCodeValue)) {
					return RdfParserHelper.convertToResource(localModel, packageNode);
				}
			}
		}
	}
	return null;	// if we got here, we didn't find a duplicate
}
 
Example 20
Source File: ElementTransformSPARQLStar.java    From RDFstarTools with Apache License 2.0 4 votes vote down vote up
protected Node unNestTriplePattern( Triple tp, ElementPathBlock epb, boolean hasParent )
{	
	Node s = tp.getSubject();
	Node p = tp.getPredicate();
	Node o = tp.getObject();

	if ( s instanceof Node_Triple )
	{
		final Triple sTP = ( (Node_Triple) s ).get();
		s = unNestTriplePattern(sTP, epb, true);
	}

	if ( o instanceof Node_Triple )
	{
		final Triple oTP = ( (Node_Triple) o ).get();
		o = unNestTriplePattern(oTP, epb, true);
	}

	final Triple nonnestedTP = new Triple(s, p, o);
	final boolean seenBefore = doneNested.containsKey(nonnestedTP);

	final Node var;
	if ( seenBefore ) {
		var = doneNested.get(nonnestedTP);
	}
	else
	{
		var = createFreshAnonVarForReifiedTriple();
		epb.addTriple(nonnestedTP);

		if ( hasParent ) {
			epb.addTriple( new Triple(var, RDF.Nodes.type,      RDF.Nodes.Statement) );
			epb.addTriple( new Triple(var, RDF.Nodes.subject,   s) );
			epb.addTriple( new Triple(var, RDF.Nodes.predicate, p) );
			epb.addTriple( new Triple(var, RDF.Nodes.object,    o) );
			doneNested.put(nonnestedTP, var);
		}
	}

	return var;
}