Java Code Examples for com.hp.hpl.jena.graph.Node#isLiteral()

The following examples show how to use com.hp.hpl.jena.graph.Node#isLiteral() . 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: RDFReader.java    From marklogic-contentpump with Apache License 2.0 5 votes vote down vote up
protected String object(Node node) {
    if (node.isLiteral()) {
        String text = node.getLiteralLexicalForm();
        String type = node.getLiteralDatatypeURI();
        String lang = node.getLiteralLanguage();

        if (lang == null || "".equals(lang)) {
            lang = "";
        } else {
            lang = " xml:lang='" + escapeXml(lang) + "'";
        }

        if ("".equals(lang)) {
            if (type == null) {
                type = "http://www.w3.org/2001/XMLSchema#string";
            }
            type = " datatype='" + escapeXml(type) + "'";
        } else {
            type = "";
        }

        return "<sem:object" + type + lang + ">" + escapeXml(text) + "</sem:object>";
    } else if (node.isBlank()) {
        return "<sem:object>http://marklogic.com/semantics/blank/" + Long.toHexString(
                hash64(fuse(scramble(milliSecs),randomValue), node.getBlankNodeLabel()))
                +"</sem:object>";
    } else {
        return "<sem:object>" + escapeXml(node.toString()) + "</sem:object>";
    }
}
 
Example 2
Source File: TypeConversion.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Transforms a Jena node into a java object. Possible node types: uri,
 * variable, literal (datatype, languageTag), blank node
 * 
 * @param n The node to transform
 * @return A specific java object
 * @throws ModelRuntimeException from the underlying model
 */
public static org.ontoware.rdf2go.model.node.Node toRDF2Go(Node n) throws ModelRuntimeException {
	// A return of null indicates that the variable is not present in this
	// solution.
	if(n == null)
		return null;
	
	if(n.isURI())
		return new URIImpl(n.getURI());
	
	if(n.isVariable())
		throw new RuntimeException("Cannot convert a Jena variable to an RDF2Go node");
	
	if(n.isLiteral()) {
		LiteralLabel lit = n.getLiteral();
		// datatype
		if(lit.getDatatypeURI() != null) {
			return new DatatypeLiteralImpl(lit.getLexicalForm(), new URIImpl(
			        lit.getDatatypeURI()));
		}
		
		// language tagged
		if(lit.language() != null && !lit.language().equals(""))
			return new LanguageTagLiteralImpl(lit.getLexicalForm(), lit.language());
		
		// plain
		return new PlainLiteralImpl(lit.getLexicalForm());
	}
	
	if(n.isBlank())
		return new JenaBlankNode(n);
	
	// none of the above - don't know how to transform that
	throw new RuntimeException("no transformation defined from " + n + " to java");
}
 
Example 3
Source File: NTriples.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link String} representation of the given {@link Node}.
 * 
 * @param node the node.
 * @return a {@link String} representation of the given {@link Node}.
 */
public static String asNt(final Node node) {
	if (node.isURI()) {
		return asNtURI(node);
	} else if (node.isBlank()) {
		return asNtBlankNode(node);		
	} else if (node.isLiteral()) {
		return asNtLiteral(node);
	}
	throw new IllegalArgumentException(node.getClass().getName());
}
 
Example 4
Source File: LocalGraph.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
public void performAdd(final Triple triple) {
	updateCommand.clear();
	
	final SolrInputDocument document = new SolrInputDocument();
	this.updateCommand.solrDoc = document;
	document.setField(Field.C, graphNodeStringified);
	document.setField(Field.S, asNt(triple.getSubject()));
	document.setField(Field.P, asNtURI(triple.getPredicate()));
	document.setField(Field.ID, UUID.nameUUIDFromBytes(
			new StringBuilder()
				.append(graphNodeStringified)
				.append(triple.getSubject())
				.append(triple.getPredicate())
				.append(triple.getObject())
				.toString().getBytes()).toString());
	
	final String o = asNt(triple.getObject());
	document.setField(Field.O, o);

	final Node object = triple.getObject();
	if (object.isLiteral()) {
		final String language = object.getLiteralLanguage();
		document.setField(Field.LANG, isNotNullOrEmptyString(language) ? language : NULL_LANGUAGE);				

		final RDFDatatype dataType = object.getLiteralDatatype();
		final Object value = object.getLiteralValue();
		registry.get(dataType != null ? dataType.getURI() : null).inject(document, value);
	} else {
		registry.catchAllFieldInjector.inject(document, o);
	}			

	try {
		updateProcessor.processAdd(updateCommand);
	} catch (final Exception exception) {
		LOGGER.error(MessageCatalog._00113_NWS_FAILURE, exception);
		throw new AddDeniedException(exception.getMessage(), triple);
	}
}
 
Example 5
Source File: CloudGraph.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
public void performAdd(final Triple triple) {
	final SolrInputDocument document = new SolrInputDocument();
	document.setField(Field.C, graphNodeStringified);
	document.setField(Field.S, asNt(triple.getSubject()));
	document.setField(Field.P, asNtURI(triple.getPredicate()));
	document.setField(Field.ID, UUID.nameUUIDFromBytes(
			new StringBuilder()
				.append(graphNodeStringified)
				.append(triple.getSubject())
				.append(triple.getPredicate())
				.append(triple.getObject())
				.toString().getBytes()).toString());
	
	final Node object = triple.getObject();
	final String o = asNt(object);
	document.setField(Field.O, o);

	if (object.isLiteral()) {
		final String language = object.getLiteralLanguage();
		document.setField(Field.LANG, isNotNullOrEmptyString(language) ? language : NULL_LANGUAGE);				

		final RDFDatatype dataType = object.getLiteralDatatype();
		final Object value = object.getLiteralValue();
		registry.get(dataType != null ? dataType.getURI() : null).inject(document, value);
	} else {
		registry.catchAllFieldInjector.inject(document, o);
	}			

	try {
		cloud.add(document);
	} catch (final Exception exception) {
		LOGGER.error(MessageCatalog._00113_NWS_FAILURE, exception);
		throw new AddDeniedException(exception.getMessage(), triple);
	}
}
 
Example 6
Source File: CloudGraph.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a DELETE query.
 * 
 * @param triple the triple (maybe a pattern?) that must be deleted.
 * @return a DELETE query.
 */
String deleteQuery(final Triple triple) {
	final StringBuilder builder = new StringBuilder();
	if (triple.getSubject().isConcrete()) {
		and(builder).append(fq(Field.S, asNt(triple.getSubject()))); 
	}
	
	if (triple.getPredicate().isConcrete()) {
		and(builder).append(fq(Field.P, asNtURI(triple.getPredicate())));
	}
		
	if (triple.getObject().isConcrete()) {
		and(builder);
		
		final Node o = triple.getObject();
		if (o.isLiteral()) {
			final String language = o.getLiteralLanguage();
			if (Strings.isNotNullOrEmptyString(language)) {
				builder
					.append(fq(Field.LANG, language))
					.append(" AND ");
			}
			
			final String literalValue = o.getLiteralLexicalForm(); 
			final RDFDatatype dataType = o.getLiteralDatatype();
			registry.get(dataType != null ? dataType.getURI() : null).addConstraint(builder, literalValue);
		} else {
			registry.catchAllInjector().addConstraint(builder, asNt(o));
		}
	}
	
	return and(builder).append(fq(Field.C, graphNodeStringified)).toString();
}
 
Example 7
Source File: TypedNodeMaker.java    From GeoTriples with Apache License 2.0 4 votes vote down vote up
public boolean matches(Node node) { 
	return node.isLiteral()
			&& this.language.equals(node.getLiteralLanguage())
			&& ((this.datatype == null && node.getLiteralDatatype() == null)
					|| (this.datatype != null && this.datatype.equals(node.getLiteralDatatype())));
}
 
Example 8
Source File: LocalGraph.java    From SolRDF with Apache License 2.0 4 votes vote down vote up
/**
 * Builds a DELETE query.
 * 
 * @param triple the triple (maybe a pattern?) that must be deleted.
 * @return a DELETE query.
 */
String deleteQuery(final Triple triple) {
	final StringBuilder builder = new StringBuilder();
	if (triple.getSubject().isConcrete()) {
		builder
			.append(Field.S)
			.append(":\"")
			.append(asNt(triple.getSubject()))
			.append("\"");
	}
	
	if (triple.getPredicate().isConcrete()) {
		if (builder.length() != 0) {
			builder.append(" AND ");
		}
		
		builder
			.append(Field.P)
			.append(":\"")
			.append(asNtURI(triple.getPredicate()))
			.append("\"");
	}
		
	if (triple.getObject().isConcrete()) {
		if (builder.length() != 0) {
			builder.append(" AND ");
		}
		
		final Node o = triple.getObject();
		if (o.isLiteral()) {
			final String language = o.getLiteralLanguage();
			builder
				.append(Field.LANG)
				.append(":")
				.append(isNotNullOrEmptyString(language) ? language : NULL_LANGUAGE)
				.append(" AND ");
			
			final String literalValue = o.getLiteralLexicalForm(); 
			final RDFDatatype dataType = o.getLiteralDatatype();
			registry.get(dataType != null ? dataType.getURI() : null).addConstraint(builder, literalValue);
		} else {
			registry.catchAllInjector().addConstraint(builder, asNt(o));
		}
	}
		
	
	return builder
		.append(" AND ")
		.append(Field.C)
		.append(":\"")
		.append(graphNodeStringified)
		.append("\"")
		.toString();
}
 
Example 9
Source File: LocalGraph.java    From SolRDF with Apache License 2.0 4 votes vote down vote up
SolrIndexSearcher.QueryCommand queryCommand(final Triple pattern, final SortSpec sortSpec) throws SyntaxError {
    final SolrIndexSearcher.QueryCommand cmd = new SolrIndexSearcher.QueryCommand();
    cmd.setQuery(new MatchAllDocsQuery());
    cmd.setSort(sortSpec.getSort());
    cmd.setLen(queryFetchSize);
    cmd.setFlags(cmd.getFlags() | SolrIndexSearcher.GET_DOCSET);
    
    final List<Query> filters = new ArrayList<Query>();
    
	final Node s = pattern.getMatchSubject();
	final Node p = pattern.getMatchPredicate();
	final Node o = pattern.getMatchObject();
	
	if (s != null) {
		filters.add(new TermQuery(new Term(Field.S, asNt(s))));
	}
	
	if (p != null) {
		filters.add(new TermQuery(new Term(Field.P, asNtURI(p))));
	}
	
	if (o != null) {
		if (o.isLiteral()) {
			final String language = o.getLiteralLanguage();
			filters.add(
					isNotNullOrEmptyString(language) 
						? languageTermQuery(language) 
						: NULL_LANGUAGE_TERM_QUERY);
			
			final String literalValue = o.getLiteralLexicalForm(); 
			final RDFDatatype dataType = o.getLiteralDatatype();
			registry.get(
					dataType != null 
						? dataType.getURI() 
						: null).addFilterConstraint(filters, literalValue, request);
		} else {
			filters.add(new TermQuery(new Term(Field.TEXT_OBJECT, asNt(o))));		
		}
	}
	
	filters.add(graphTermQuery);				
	
	cmd.setFilterList(filters);
	return cmd;
}
 
Example 10
Source File: SPARQLEndPoint.java    From LodView with MIT License 4 votes vote down vote up
private List<TripleBean> moreThenOneQuery(QueryExecution qe, List<TripleBean> results, int retry, String overrideProperty) throws Exception {

		try {
			ResultSet rs = qe.execSelect();
			while (rs.hasNext()) {
				TripleBean rb = new TripleBean();
				QuerySolution qs = rs.next();
				String property = "";
				if (overrideProperty != null) {
					property = overrideProperty;
				} else if (qs.get("p") != null) {
					property = qs.get("p").asNode().toString();
				}

				try {
					if (qs.get("s") != null && !qs.get("s").asNode().toString().startsWith("http://")) { // probably
																											// a
																											// bn
						rb.setIRI(qs.get("s").asNode().toString());
						rb.setNsIRI("_:" + rb.getIRI());
					} else if (qs.get("s") != null && qs.get("s").asNode().toString().startsWith("http://")) {
						rb.setIRI(qs.get("s").asNode().toString());
						rb.setNsIRI(Misc.toNsResource(rb.getIRI(), conf));
						rb.setUrl(Misc.toBrowsableUrl(rb.getIRI(), conf));
					}

					PropertyBean p = new PropertyBean();
					p.setNsProperty(Misc.toNsResource(property, conf));
					p.setProperty(property);
					if (ontoBean != null) {
						p.setLabel(ontoBean.getEscapedValue("label", locale, property));
						p.setComment(ontoBean.getEscapedValue("comment", locale, property));
					}
					p.setPropertyUrl(Misc.toBrowsableUrl(property, conf));
					rb.setProperty(p);
					if (qs.get("o") != null) {
						Node object = qs.get("o").asNode();
						if (object.isURI()) {
							rb.setType("iri");
							rb.setValue(object.toString(false));
						} else if (object.isLiteral()) {
							rb.setType("literal");
							rb.setDataType(object.getLiteralDatatypeURI());
							rb.setNsDataType(Misc.toNsResource(object.getLiteralDatatypeURI(), conf));
							rb.setLang(object.getLiteralLanguage());
							rb.setValue(object.getLiteralLexicalForm());
						} else if (object.isBlank()) {
							rb.setType("bnode");
							rb.setValue(object.toString(false));
						}
					} else {
						rb.setType("literal");
						rb.setValue("");
					}
					results.add(rb);
				} catch (Exception e) {
					System.err.println("error? " + e.getMessage());
					// e.printStackTrace();
				}
			}
		} catch (Exception ez) {
			if (retry < 3) {
				retry++;
				// System.out.println("query failed (" + ez.getMessage() +
				// "), I'm giving another chance (" + retry + "/3)");
				return moreThenOneQuery(qe, results, retry, overrideProperty);
			}
			ez.printStackTrace();
			throw new Exception("connection refused");
		}

		return results;
	}