org.apache.jena.graph.Node Java Examples

The following examples show how to use org.apache.jena.graph.Node. 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: RdfModelObject.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * Finds all SPDX elements with a subject of this object
 * @param namespace
 * @param propertyName
 * @return
 * @throws InvalidSPDXAnalysisException 
 */
protected SpdxElement[] findMultipleElementPropertyValues(String namespace,
		String propertyName) throws InvalidSPDXAnalysisException {
	if (this.model == null || this.node == null) {
		return null;
	}
	Node p = model.getProperty(namespace, propertyName).asNode();
	Triple m = Triple.createMatch(node, p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	List<SpdxElement> retval = Lists.newArrayList();
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		retval.add(SpdxElementFactory.createElementFromModel(modelContainer, 
				t.getObject()));
	}
	return retval.toArray(new SpdxElement[retval.size()]);
}
 
Example #2
Source File: PropertyConstraintExecutor.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void executeHelper(ValidationEngine engine, Collection<RDFNode> valueNodes, Node propertyShape) {
	List<RDFNode> doNodes = new LinkedList<>();
	for(RDFNode focusNode : valueNodes) {
		if(!RecursionGuard.start(focusNode.asNode(), propertyShape)) {
			doNodes.add(focusNode);
		}
	}
	try {
		engine.validateNodesAgainstShape(doNodes, propertyShape);
	}
	finally {
		for(RDFNode valueNode : doNodes) {
			RecursionGuard.end(valueNode.asNode(), propertyShape);
		}
	}
}
 
Example #3
Source File: SPDXDocument.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @return the declaredLicenses
 * @throws InvalidSPDXAnalysisException
 */
public SPDXLicenseInfo getDeclaredLicense() throws InvalidSPDXAnalysisException {
	ArrayList<SPDXLicenseInfo> alLic = new ArrayList<SPDXLicenseInfo>();
	Node p = model.getProperty(SPDX_NAMESPACE, PROP_PACKAGE_DECLARED_LICENSE).asNode();
	Triple m = Triple.createMatch(this.node, p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		alLic.add(SPDXLicenseInfoFactory.getLicenseInfoFromModel(model, t.getObject()));
	}
	if (alLic.size() > 1) {
		throw(new InvalidSPDXAnalysisException("Too many declared licenses"));
	}
	if (alLic.size() == 0) {
		return null;
	}
	return alLic.get(0);
}
 
Example #4
Source File: ITER_GeoJSON.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public List<List<NodeValue>> exec(NodeValue json) {
    String s = getString(json);
    List<List<NodeValue>> nodeValues = new ArrayList<>();
    FeatureCollection featureCollection = GSON.fromJson(s, FeatureCollection.class);

    for (Feature feature : featureCollection.features()) {
        List<NodeValue> values = new ArrayList<>();
        NodeValue geometry = geoJSONGeom.getNodeValue(feature.geometry());
        values.add(geometry);
        Node properties = NodeFactory.createLiteral(
                GSON.toJson(feature.properties()),
                TypeMapper.getInstance().getSafeTypeByName("http://www.iana.org/assignments/media-types/application/json"));
        values.add(new NodeValueNode(properties));
        nodeValues.add(values);
    }
    return nodeValues;
}
 
Example #5
Source File: RdfModelObject.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * Find the reference type within a specific property in the model for this node
 * @param nameSpace
 * @param propertyName
 * @return
 * @throws InvalidSPDXAnalysisException 
 */
protected ReferenceType findReferenceTypePropertyValue(String nameSpace,
		String propertyName) throws InvalidSPDXAnalysisException {
	if (this.model == null || this.node == null) {
		return null;
	}
	Node p = model.getProperty(nameSpace, propertyName).asNode();
	Triple m = Triple.createMatch(node, p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	if (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		return new ReferenceType(modelContainer, t.getObject());
	} else {
		return null;
	}
}
 
Example #6
Source File: TrimValidator.java    From rdflint with MIT License 6 votes vote down vote up
@Override
public List<LintProblem> validateTriple(Node subject, Node predicate, Node object,
    int beginLine, int beginCol, int endLine, int endCol) {
  List<LintProblem> rtn = new LinkedList<>();

  if (object.isLiteral()) {
    String s = object.getLiteralValue().toString();
    if (!s.equals(s.trim())) {
      rtn.add(new LintProblem(ErrorLevel.WARN,
          this,
          new LintProblemLocation(beginLine, beginCol, endLine, endCol,
              new Triple(subject, predicate, object)),
          "needTrimLiteral", s));
    }
  }
  return rtn;
}
 
Example #7
Source File: SPDXDocument.java    From tools with Apache License 2.0 6 votes vote down vote up
public SPDXCreatorInformation getCreatorInfo() throws InvalidSPDXAnalysisException {
	Node spdxDocNode = getSpdxDocNode();
	if (spdxDocNode == null) {
		throw(new InvalidSPDXAnalysisException("No SPDX Document was found.  Can not access the creator information"));
	}
	ArrayList<SPDXCreatorInformation> als = new ArrayList<SPDXCreatorInformation>();
	Node p = model.getProperty(SPDX_NAMESPACE, PROP_SPDX_CREATION_INFO).asNode();
	Triple m = Triple.createMatch(spdxDocNode, p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);
	while (tripleIter.hasNext()) {
		Triple t = tripleIter.next();
		als.add(new SPDXCreatorInformation(model, t.getObject()));
	}
	if (als.size() > 1) {
		throw(new InvalidSPDXAnalysisException("Too many creation infos for document.  Only one is allowed."));
	}
	if (als.size() > 0) {
		return als.get(0);
	} else {
		return null;
	}
}
 
Example #8
Source File: RDFChangesWriteUpdate.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
@Override
public void addPrefix(Node gn, String prefix, String uriStr) {
    notHeader();
    out.print("# AddPrefix ");
    if ( gn != null ) {
        outputNode(out, gn);
        out.print(" ");
    }
    out.print(prefix);
    out.print(" <");
    out.print(uriStr);
    out.print(">");
    out.println();
    out.print("PREFIX ");
    out.print(prefix+": ");
    out.print("<");
    out.print(uriStr);
    out.print(">");
    out.println();
    pmap.add(prefix, uriStr);
}
 
Example #9
Source File: FUN_XPath.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
public NodeValue nodeForNode(org.w3c.dom.Node xmlNode) throws TransformerException {
    if(xmlNode == null) {
        return null;
    }
    String nodeValue = xmlNode.getNodeValue();
    if (nodeValue != null) {
        return new NodeValueString(nodeValue);
    } else {
        DOMSource source = new DOMSource(xmlNode);
        StringWriter writer = new StringWriter();
        Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
        transformer.transform(source, new StreamResult(writer));
        Node node = NodeFactory.createLiteral(writer.toString(), DT);
        return new NodeValueNode(node);
    }
}
 
Example #10
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();
	SPDXDocument doc = new SPDXDocument(model);
	doc.createSpdxAnalysis("http://somethingunique");
	SPDXFile file = new SPDXFile("filename", "BINARY", "sha1", COMPLEX_LICENSE, CONJUNCTIVE_LICENSES, "", SpdxRdfConstants.NOASSERTION_VALUE, new DOAPProject[0]);
	Resource fileResource = file.createResource(doc, doc.getDocumentNamespace() + doc.getNextSpdxElementRef());
	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.getCopyright());
}
 
Example #11
Source File: RdfModelObject.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @param nameSpace
 * @param propertyName
 * @return
 * @throws InvalidSPDXAnalysisException 
 */
protected SPDXReview[] findReviewPropertyValues(String nameSpace,
		String propertyName) throws InvalidSPDXAnalysisException {
	if (this.model == null || this.node == null) {
		return new SPDXReview[0];
	}
	List<SPDXReview> 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 SPDXReview(model, t.getObject()));
	}
	return retval.toArray(new SPDXReview[retval.size()]);
}
 
Example #12
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 #13
Source File: ARQFactory.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a list of named graphs (GRAPH elements) mentioned in a given
 * Query.
 * @param query  the Query to traverse
 * @return a List of those GRAPHs
 */
public static List<String> getNamedGraphURIs(Query query) {
	final List<String> results = new LinkedList<String>();
	ElementWalker.walk(query.getQueryPattern(), new ElementVisitorBase() {
		@Override
		public void visit(ElementNamedGraph el) {
			Node node = el.getGraphNameNode();
			if(node != null && node.isURI()) {
				String uri = node.getURI();
				if(!results.contains(uri)) {
					results.add(uri);
				}
			}
		}
	});
	return results;
}
 
Example #14
Source File: TriplesToRuleSystem.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * converts a {@link Node} into an {l@ink Expr}
 * @param n
 * @return
 */
protected Expr	toExpr(Node n) {
	if (n.isVariable()) {
		return new VariableExpr(n.getName());
	} else if (n.isURI()) {
		try {
			return new ConstantExpr(new URI(n.getURI()));
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	} else if (n.isLiteral()) {
		Literal l = (Literal) n;
		return new ConstantExpr(l.getValue());
	} else {
		throw new RuntimeException("Unsuported node type in query : "+n);
	}
}
 
Example #15
Source File: PlanFactory.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
/**
 * Makes the plan for a SPARQL SOURCE clause.
 *
 * @param elementSource the SPARQL SOURCE
 * @return -
 */
private static BindOrSourcePlan makeSourcePlan(
        final ElementSource elementSource) throws SPARQLExtException {
    Objects.requireNonNull(elementSource, "The Source must not be null");

    Node node = elementSource.getSource();
    Node accept = elementSource.getAccept();
    Var var = elementSource.getVar();

    Objects.requireNonNull(node, "The source must not be null");
    checkIsTrue(node.isURI() || node.isVariable(), "The source must be a"
            + " URI or a variable. Got " + node);
    // accept may be null
    checkIsTrue(accept == null || accept.isVariable() || accept.isURI(),
            "The accept must be null, a variable or a URI. Got " + accept);
    Objects.requireNonNull(var, "The variable must not be null.");

    return new SourcePlan(node, accept, var);
}
 
Example #16
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 #17
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 #18
Source File: RdflintParserRdfxml.java    From rdflint with MIT License 5 votes vote down vote up
@Override
public void statement(AResource subj, AResource pred, ALiteral lit) {
  Triple t = convert(subj, pred, lit);
  models.forEach(m -> {
    int line = arp.getLocator().getLineNumber();
    int col = arp.getLocator().getColumnNumber();
    diagnosticList.addAll(m.validateTriple(
        t.getSubject(), t.getPredicate(), t.getObject(), line, 1, line, col));
    for (Node n : new Node[]{t.getSubject(), t.getPredicate()}) {
      diagnosticList.addAll(m.validateNode(n, line, 1, line, col));
    }
  });
  output.triple(convert(subj, pred, lit));
}
 
Example #19
Source File: RDFChangesWriter.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
@Override
public void addPrefix(Node gn, String prefix, String uriStr) {
    tok.startTuple();
    outputWord(ADD_PREFIX);
    tok.sendString(prefix);
    tok.sendString(uriStr);
    if ( gn != null )
        tok.sendNode(gn);
    tok.endTuple();
    tok.flush();
}
 
Example #20
Source File: AbstractFunction3.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeValue exec(Node[] nodes, FunctionEnv env) {
	Node arg1 = nodes.length > 0 ? nodes[0] : null;
	Node arg2 = nodes.length > 1 ? nodes[1] : null;
	Node arg3 = nodes.length > 2 ? nodes[2] : null;
	return exec(arg1, arg2, arg3, env);
}
 
Example #21
Source File: DatasetWrappingDatasetGraph.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public long size() {
	int count = 0;
	Iterator<Node> it = listGraphNodes();
	while(it.hasNext()) {
		it.next();
		count++;
	}
	return count;
}
 
Example #22
Source File: SPDXFile.java    From tools with Apache License 2.0 5 votes vote down vote up
/**
 * @return the type
 * @throws InvalidSPDXAnalysisException 
 */
public String getType() {
	if (this.model != null && this.resource != null) {
		try {
			Node p = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_FILE_TYPE).asNode();
			Triple m = Triple.createMatch(this.resource.asNode(), p, null);
			ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
			while (tripleIter.hasNext()) {
				Triple t = tripleIter.next();
				if (t.getObject().isLiteral()) {
					// the following is for compatibility with previous versions of the tool which used literals for the file type
					this.type = t.getObject().toString(false);
				} else if (t.getObject().isURI()) {
					this.type = RESOURCE_TO_FILE_TYPE.get(t.getObject().getURI());
					if (this.type == null) {
						throw(new InvalidSPDXAnalysisException("Invalid URI for file type resource - must be one of the individual file types in http://spdx.org/rdf/terms"));
					}
				} else {
					throw(new InvalidSPDXAnalysisException("Invalid file type property - must be a URI type specified in http://spdx.org/rdf/terms"));
				}			
			} 
		}catch(InvalidSPDXAnalysisException e) {
			// just use the original
		}
	}
	return this.type;
}
 
Example #23
Source File: EntityIterator.java    From Stargraph with MIT License 5 votes vote down vote up
private Iterator<Node> createIterator() {
    Model model = core.getGraphModel();
    Graph g = model.getGraph();
    ExtendedIterator<Triple> exIt = g.find(Node.ANY, null, null);
    ExtendedIterator<Node> subjIt = exIt.mapWith(Triple::getSubject);
    exIt = g.find(null, null, Node.ANY);
    ExtendedIterator<Node> objIt = exIt.mapWith(Triple::getObject);
    return Iterators.concat(subjIt, objIt);
}
 
Example #24
Source File: ITER_CSVHeaders.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public List<List<NodeValue>> exec(NodeValue csv) {
    if (csv.getDatatypeURI() != null
            && !csv.getDatatypeURI().equals(datatypeUri)
            && !csv.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) {
        LOG.debug("The URI of NodeValue1 MUST be <" + datatypeUri + ">"
                + "or <http://www.w3.org/2001/XMLSchema#string>."
        );
    }
    try {
        String sourceCSV = String.valueOf(csv.asNode().getLiteralLexicalForm());

        InputStream is = new ByteArrayInputStream(sourceCSV.getBytes("UTF-8"));
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        CsvMapReader mapReader = new CsvMapReader(br, CsvPreference.STANDARD_PREFERENCE);
        String headers_str[] = mapReader.getHeader(true);

        final List<List<NodeValue>> listNodeValues = new ArrayList<>();
        Node node;
        NodeValue nodeValue;
        for (String header : headers_str) {
            node = NodeFactory.createLiteral(header);
            nodeValue = new NodeValueNode(node);
            listNodeValues.add(Collections.singletonList(nodeValue));
        }
        return listNodeValues;
    } catch (Exception ex) {
        if(LOG.isDebugEnabled()) {
            Node compressed = LogUtils.compress(csv.asNode());
            LOG.debug("No evaluation for " + compressed, ex);
        }
        throw new ExprEvalException("No evaluation ", ex);
    }
}
 
Example #25
Source File: SimpleImplementation.java    From shacl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public SimpleImplementation(Node type, Class implClass) {
	super(type);
	try {
		constructor = implClass.getConstructor(Node.class, EnhGraph.class);
	}
	catch (Throwable t) {
		t.printStackTrace();
	}
}
 
Example #26
Source File: DatasetWrappingDatasetGraph.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<Node> listGraphNodes() {
	List<Node> results = new LinkedList<Node>();
	Iterator<String> names = dataset.listNames();
	while(names.hasNext()) {
		String name = names.next();
		results.add(NodeFactory.createURI(name));
	}
	return results.iterator();
}
 
Example #27
Source File: ResultSetWritersSPARQLStarTest.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
@Override
public RDFNode asRDFNode( Node n ) {
	if ( n instanceof Node_Triple ) {
		return new ResourceImpl(n, this);
	}
	else
		return super.asRDFNode(n);
}
 
Example #28
Source File: SHACLUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static boolean exists(Graph graph) {
	if(graph instanceof OptimizedMultiUnion) {
		return ((OptimizedMultiUnion)graph).getIncludesSHACL();
	}
	else {
    	return graph != null &&
        		SH.NS.equals(graph.getPrefixMapping().getNsPrefixURI(SH.PREFIX)) && 
        		graph.contains(SH.Shape.asNode(), RDF.type.asNode(), Node.ANY);
	}
}
 
Example #29
Source File: TestRDFChangesDataset.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
@Test public void record_add_graph_1() {
    Txn.executeWrite(dsg, ()->dsg.add(quad1));

    Graph data = GraphFactory.createDefaultGraph();
    Node gn = quad1.getGraph();
    data.add(triple1);
    Txn.executeWrite(dsg, ()-> {
        dsg.addGraph(gn, data);
    });
    DatasetGraph dsg2 = replay();
    check(dsg2, Quad.create(gn, triple1));
}
 
Example #30
Source File: TextOutputStarTest.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
@Test
public void nested1() {
	final MyTextOutput o = new MyTextOutput( getPrefixMappingForTests() );
	
	final Node u = NodeFactory.createURI("http://example.com/i");
	final Node n1 = new Node_Triple(new Triple(u, u, u));
	final Node n2 = new Node_Triple(new Triple(n1, u, u));
	final QuerySolution s = createQuerySolution( "?t", n2 );		
	final String result = o.get(s, "?t");

	assertEquals("<< ex:i ex:i ex:i >> ex:i ex:i ", result);
}