Java Code Examples for org.apache.jena.graph.NodeFactory#createLiteral()

The following examples show how to use org.apache.jena.graph.NodeFactory#createLiteral() . 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: RuleSystemToQueries.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
protected static Node toNode(Expr e        ) {
	
	Node ret;
	if(e.isVariable()) {
		ret = NodeFactory.createVariable(((VariableExpr)e).getName());
	} else {
		Object v = ((ConstantExpr) e).getValue();
		if (v instanceof URI) {
			ret = NodeFactory.createURI(v.toString());
		} /*else if (predicatePosition) {
			ret = Node.createURI(v.toString());
		}*/ else
		{
			ret = NodeFactory.createLiteral(v.toString());
		}
	}
	return ret;
}
 
Example 2
Source File: JSFactory.java    From shacl with Apache License 2.0 6 votes vote down vote up
public static Node getNodeFlex(Object obj) {
	Node fromTerm = getNode(obj);
	if(fromTerm != null) {
		return fromTerm;
	}
	else if(obj instanceof Integer) {
		return JenaDatatypes.createInteger((Integer)obj).asNode();
	}
	else if(obj instanceof Number) {
		return NodeFactory.createLiteral(obj.toString(), XSDDatatype.XSDdecimal);
	}
	else if(obj instanceof Boolean) {
		return ((Boolean)obj) ? JenaDatatypes.TRUE.asNode() : JenaDatatypes.FALSE.asNode();
	}
	else if(obj != null) {
		return NodeFactory.createLiteral(obj.toString());
	}
	else {
		return null;
	}
}
 
Example 3
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 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: LogUtils.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private static ElementData compress(List<Binding> input) {
    ElementData el = new ElementData();

    if (input.size() < 10) {
        input.forEach((b) -> {
            addCompressedToElementData(el, b);
        });
        return el;
    }
    for (int i = 0; i < 5; i++) {
        addCompressedToElementData(el, input.get(i));
    }
    BindingMap binding = BindingFactory.create();
    Node n = NodeFactory.createLiteral("[ " + (input.size() - 10) + " more ]");
    el.getVars().forEach((v) -> binding.add(v, n));
    el.add(binding);
    for (int i = input.size() - 5; i < input.size(); i++) {
        addCompressedToElementData(el, input.get(i));
    }
    return el;
}
 
Example 6
Source File: LogUtils.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private static ElementData compress(List<Var> variables, List<Binding> input) {
    ElementData el = new ElementData();
    variables.forEach(el::add);
    if (input.size() < 10) {
        input.forEach((b) -> el.add(compress(variables, b)));
        return el;
    }
    for (int i = 0; i < 5; i++) {
        el.add(compress(variables, input.get(i)));
    }
    BindingMap binding = BindingFactory.create();
    Node n = NodeFactory.createLiteral("[ " + (input.size() - 10) + " more ]");
    variables.forEach((v) -> binding.add(v, n));
    el.add(binding);
    for (int i = input.size() - 5; i < input.size(); i++) {
        el.add(compress(variables, input.get(i)));
    }
    return el;
}
 
Example 7
Source File: localname.java    From xcurator with Apache License 2.0 6 votes vote down vote up
private QueryIterator execFixedSubject(Node nodeURI, Node nodeLocalname, Binding binding, ExecutionContext execCxt)
{
    if ( ! nodeURI.isURI() )
        // Subject bound but not a URI
        return QueryIterNullIterator.create(execCxt) ;

    // Subject is bound and a URI - get the localname as a Node 
    Node localname = NodeFactory.createLiteral(nodeURI.getLocalName()) ;
    
    // Object - unbound variable or a value? 
    if ( ! nodeLocalname.isVariable() )
    {
        // Object bound or a query constant.  Is it the same as the calculated value?
        if ( nodeLocalname.equals(localname) )
            // Same
            return QueryIterSingleton.create(binding, execCxt) ;
        // No - different - no match.
        return QueryIterNullIterator.create(execCxt) ;
    }
    
    // Object unbound variable - assign the localname to it.
    return QueryIterSingleton.create(binding, Var.alloc(nodeLocalname), localname, execCxt) ;
}
 
Example 8
Source File: SPDXDocument.java    From tools with Apache License 2.0 5 votes vote down vote up
/**
 * @param id
 * @return true if the license ID is already in the model as an extracted license info
 * @throws InvalidSPDXAnalysisException 
 */
protected boolean extractedLicenseExists(String id) throws InvalidSPDXAnalysisException {
	Node p = model.getProperty(SPDX_NAMESPACE, PROP_LICENSE_ID).asNode();
	Node o = NodeFactory.createLiteral(id);
	Triple m = Triple.createMatch(null, p, o);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	return tripleIter.hasNext();
}
 
Example 9
Source File: uppercase.java    From xcurator with Apache License 2.0 5 votes vote down vote up
@Override
public Node calc(Node node)
{
    if ( ! node.isLiteral() ) 
        return null ;
    String str = node.getLiteralLexicalForm().toUpperCase() ;
    return NodeFactory.createLiteral(str) ;
}
 
Example 10
Source File: FUN_CSSPath.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private NodeValue selectElement(Element element, String selectPath) {
    Elements elements = element.select(selectPath);
    Element e = elements.first();
    if (e == null) {
        throw new ExprEvalException("No evaluation of " + element + ", " + selectPath);
    }
    Node n = NodeFactory.createLiteral(e.outerHtml(), DT);
    return new NodeValueNode(n);
}
 
Example 11
Source File: JSFactory.java    From shacl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static Node getNode(Object obj) {
	if(obj == null) {
		return null;
	}
	else if(obj instanceof JSTerm) {
		return ((JSTerm)obj).getNode();
	}
	else if(obj instanceof Map) {
		Map som = (Map) obj;
		String value = (String) som.get(VALUE);
		if(value == null) {
			throw new IllegalArgumentException("Missing value");
		}
		String termType = (String) som.get(TERM_TYPE);
		if(NAMED_NODE.equals(termType)) {
			return NodeFactory.createURI(value);
		}
		else if(BLANK_NODE.equals(termType)) {
			return NodeFactory.createBlankNode(value);
		}
		else if(LITERAL.equals(termType)) {
			String lang = (String) som.get(LANGUAGE);
			Map dt = (Map)som.get(DATATYPE);
			String dtURI = (String)dt.get(VALUE);
			RDFDatatype datatype = TypeMapper.getInstance().getSafeTypeByName(dtURI);
			return NodeFactory.createLiteral(value, lang, datatype);
		}
		else {
			throw new IllegalArgumentException("Unsupported term type " + termType);
		}
	}
	else {
		return null;
	}
}
 
Example 12
Source File: RdflintParserRdfxml.java    From rdflint with MIT License 5 votes vote down vote up
private static Node convert(ALiteral lit) {
  String dtURI = lit.getDatatypeURI(); // SUPPRESS CHECKSTYLE AbbreviationAsWordInName
  if (dtURI == null) {
    return NodeFactory.createLiteral(lit.toString(), lit.getLang());
  }

  if (lit.isWellFormedXML()) {
    return NodeFactory.createLiteral(lit.toString(), null, true);
  }

  RDFDatatype dt = TypeMapper.getInstance().getSafeTypeByName(dtURI);
  return NodeFactory.createLiteral(lit.toString(), dt);
}
 
Example 13
Source File: PredicateMappingsDataSet.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
public void writeHashingFunctionToDataset(Set<String> predicates,
		boolean isDirect, IHashingFamily family) {

	String type = isDirect ? "direct" : "reverse";
	Node predicateNode = NodeFactory.createURI(Constants.ibmns
			+ Constants.COLUMN_PREDICATE);

		Graph[] hashingGraphs = new Graph[numberOfHashFunctions];
		for (int i = 0; i < numberOfHashFunctions; i++) {
			hashingGraphs[i] = GraphFactory.createPlainGraph();
		}

		Iterator<String> predicateIterator = predicates.iterator();
		while (predicateIterator.hasNext()) {
			String entry = predicateIterator.next();
			family.computeHash(entry);
			int[] hashes = family.getHash(entry);
			for (int i = 0; i < numberOfHashFunctions; i++) {
				Triple triple = new Triple(NodeFactory.createURI(entry),
						predicateNode, intToNode(hashes[i]));
				hashingGraphs[i].add(triple);
			}
		}

		for (int i = 0; i < numberOfHashFunctions; i++) {
			dataset.addNamedModel(Constants.ibmns
					+ Constants.HASHING_FUNCTION + type + (i + 1),
					ModelFactory.createModelForGraph(hashingGraphs[i]));

			Node hashFunction = NodeFactory.createURI(Constants.ibmns
					+ Constants.HASHING_FUNCTION + type + (i + 1));

			Triple deftriple3 = new Triple(hashFunction,
					NodeFactory.createURI(Constants.ibmns
							+ Constants.FUNCTION_TYPE_PREDICATE),
					NodeFactory.createLiteral("hashing"));//, "", ""));
			dataset.getDefaultModel().getGraph().add(deftriple3);

			dataset.getDefaultModel()
					.getGraph()
					.add(new Triple(hashFunction, NodeFactory.createURI(Constants.ibmns
									+ Constants.FUNCTION_PRIORITY),
									intToNode(numberOfColorFunctions
									+ i + 1)));

			dataset.getDefaultModel()
					.getGraph()
					.add(new Triple(
							hashFunction,
							NodeFactory.createURI(Constants.ibmns
									+ Constants.COLORING_FUNCTION_TUPE_PREDICATE),
							NodeFactory.createLiteral(type)));//, "", "")));

		}


}
 
Example 14
Source File: PredicateMappingsDataSet.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
protected Node intToNode(int val) {
	return NodeFactory.createLiteral(Long.toString(val), "", XSDDatatype.XSDinteger) ;
}
 
Example 15
Source File: LogUtils.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
public static Node compress(Node n) {
    if (n.isLiteral()) {
        n = NodeFactory.createLiteral(compress(n.getLiteralLexicalForm()), n.getLiteralLanguage(), n.getLiteralDatatype());
    }
    return n;
}
 
Example 16
Source File: FUN_GeoJSONGeometry.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
public NodeValue getNodeValue(Geometry geom) {
    Node n = NodeFactory.createLiteral(getGeometry(geom), WktLiteral.wktLiteralType);
    return new NodeValueNode(n);
}
 
Example 17
Source File: FUN_CBOR.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
@Override
public NodeValue exec(NodeValue cbor, NodeValue jsonpath) {
    if (cbor.getDatatypeURI() != null
            && !cbor.getDatatypeURI().equals(datatypeUri)
            && !cbor.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>."
        );
    }

    String json = new String(Base64.getDecoder().decode(cbor.asNode().getLiteralLexicalForm().getBytes()));
    try {
        Object value = JsonPath.parse(json)
                .limit(1).read(jsonpath.getString());

        if (value instanceof String) {
            return new NodeValueString((String) value);
        } else if (value instanceof Float) {
            return new NodeValueFloat((Float) value);
        } else if (value instanceof Boolean) {
            return new NodeValueBoolean((Boolean) value);
        } else if (value instanceof Integer) {
            return new NodeValueInteger((Integer) value);
        } else if (value instanceof Double) {
            return new NodeValueDouble((Double) value);
        } else if (value instanceof BigDecimal) {
            return new NodeValueDecimal((BigDecimal) value);
        } else {
            String strValue = String.valueOf(value);

            JsonParser parser = new JsonParser();
            JsonElement valElement = parser.parse(strValue);
            JsonArray list = valElement.getAsJsonArray();

            if (list.size() == 1) {
                String jsonstring = list.get(0).getAsString();
                Node node = NodeFactory.createLiteral(jsonstring);
                NodeValue nodeValue = new NodeValueNode(node);
                return nodeValue;

            } else {
                return new NodeValueString(String.valueOf(value));
            }
        }
    } catch (Exception ex) {
        if(LOG.isDebugEnabled()) {
            LOG.debug("No evaluation of " + jsonpath + "  on " + LogUtils.compress(cbor.asNode()), ex);
        }
        throw new ExprEvalException("FunctionBase: no evaluation", ex);
    }
}
 
Example 18
Source File: ITER_CBOR.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
@Override
public List<List<NodeValue>> exec(NodeValue cbor, NodeValue jsonpath) {
    if (cbor.getDatatypeURI() != null
            && !cbor.getDatatypeURI().equals(datatypeUri)
            && !cbor.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>. Got <"
                + cbor.getDatatypeURI() + ">. Returning null.");
    }

    Configuration conf = Configuration.builder()
            .options(Option.ALWAYS_RETURN_LIST).build();

    String json = new String(Base64.getDecoder().decode(cbor.asNode().getLiteralLexicalForm().getBytes()));

    Gson gson = new Gson();
    RDFDatatype dt = TypeMapper.getInstance().getSafeTypeByName(datatypeUri);
    
    try {
        List<Object> values = JsonPath
                .using(conf)
                .parse(json)
                .read(jsonpath.getString());

        final List<List<NodeValue>> nodeValues = new ArrayList<>();

        Node node;
        NodeValue nodeValue;
        for (Object value : values) {
            String jsonstring = gson.toJson(value);
            node = NodeFactory.createLiteral(jsonstring, dt);
            nodeValue = new NodeValueNode(node);
            nodeValues.add(Collections.singletonList(nodeValue));
        }
        return nodeValues;
    } catch (Exception ex) {
        if(LOG.isDebugEnabled()) {
            Node compressed = LogUtils.compress(cbor.asNode());
            LOG.debug("No evaluation of " + compressed + ", " + jsonpath, ex);
        }
        throw new ExprEvalException("No evaluation of " + jsonpath, ex);
    }
}
 
Example 19
Source File: Id.java    From rdf-delta with Apache License 2.0 4 votes vote down vote up
/** Convert to a Node, as a URI or as a plain string. */
public Node asNode() {
    if ( uuid != null )
        return NodeFactory.createURI(SchemeUuid+uuid.toString());
    return NodeFactory.createLiteral(string);
}
 
Example 20
Source File: FunctionTest.java    From tarql with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected Node stringNode(String s) {
	return NodeFactory.createLiteral(s);
}