Java Code Examples for org.openrdf.model.URI#stringValue()

The following examples show how to use org.openrdf.model.URI#stringValue() . 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: OwlNormalizer.java    From anno4j with Apache License 2.0 6 votes vote down vote up
private CharSequence getMatchNamespace(URI ontology) {
	StringBuilder sb = new StringBuilder();
	ParsedURI parsed = new ParsedURI(ontology.stringValue());
	if (parsed.getScheme() != null) {
		sb.append(parsed.getScheme());
		sb.append(':');
	}
	if (parsed.isOpaque()) {
		if (parsed.getSchemeSpecificPart() != null) {
			sb.append(parsed.getSchemeSpecificPart());
		}
	} else {
		if (parsed.getAuthority() != null) {
			sb.append("//");
			sb.append(parsed.getAuthority());
		}
		sb.append(parsed.getPath());
		sb.append("#");
	}
	return sb;
}
 
Example 2
Source File: InverseObjectProperties.java    From neo4j-sparql-extension with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Transform a statement pattern according to OWL-2 inverse properties
 * axiom.
 *
 * @param node the node to transform
 * @return list of nodes to visit next
 */
@Override
public List<QueryModelNode> apply(StatementPattern node) {
	List<QueryModelNode> next = newNextList();
	Var s = node.getSubjectVar();
	Var p = node.getPredicateVar();
	Var o = node.getObjectVar();
	Var c = node.getContextVar();
	URI uri = (URI) p.getValue();
	String op = uri.stringValue();
	Var p2;
	// check if need to replace with op1 or op2
	if (op.equals(op1)) {
		p2 = new ConstVar(vf.createURI(op2));
	} else {
		p2 = new ConstVar(vf.createURI(op1));
	}
	StatementPattern left = node.clone();
	// switch subject and object and replace predicate
	StatementPattern right = new StatementPattern(o, p2, s, c);
	node.replaceWith(new Union(left, right));
	next.add(left);
	next.add(right);
	return next;
}
 
Example 3
Source File: NativeCumulusURI.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
/**
 * Loads data associated with this URI.
 */
private synchronized void load() {
	if (_has_data) {
		return;
	}

	// load data ...
	try {
		final URI uri = (URI) _dictionary.getValue(_internalID, _p);
		super.setURIString(uri.stringValue());
	} catch (final Exception exception) {
		_log.error(MessageCatalog._00075_COULDNT_LOAD_NODE, exception, Arrays.toString(_internalID));
		super.setURIString("http://cumulus/internal/" + Arrays.toString(_internalID));
	}

	_has_data = true;
}
 
Example 4
Source File: TestTicket632.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final URI serviceUri, final SailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException, RDFHandlerException {
    try {
        repo.initialize();
        final RepositoryConnection conn = repo.getConnection();
        final ValueFactory vf = conn.getValueFactory();
        conn.setAutoCommit(false);
        try {
            final String query = "SELECT ?x { SERVICE <" + serviceUri.stringValue() + "> { ?x <u:1> ?bool1 } }";
            final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
            q.setBinding("bool1", vf.createLiteral(true));
            final TupleQueryResult tqr = q.evaluate();
            try {
                tqr.hasNext();
            } finally {
                tqr.close();
            }
        } finally {
            conn.close();
        }
    } finally {
        repo.shutDown();
    }
}
 
Example 5
Source File: SimpleBlueprintsValueFactory.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gracefully handle round-tripping the colons.
 */
@Override
public String fromURI(final URI uri) {

    if (uri == null) {
        throw new IllegalArgumentException();
    }

    final String s = uri.stringValue();

    final String id;
    if (s.startsWith(ID)) {
        id = s.substring(ID.length());
    } else {
        id = s;
    }

    try {
        return URLDecoder.decode(id, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

}
 
Example 6
Source File: FilterableTripleHandler.java    From anthelion with Apache License 2.0 6 votes vote down vote up
private void printURI(URI uri) throws IOException {
	final String uriString = uri.stringValue();
	int splitIdx = 0;
	String namespace = null;
	if (namespaceTable != null) {
		splitIdx = uriString.indexOf(':');
		if (splitIdx > 0) {
			String prefix = uriString.substring(0, splitIdx);
			namespace = namespaceTable.get(prefix);
		}
	}

	if (namespace != null) {
		writer.append('<');
		writer.append(namespace);
		writer.append(NTriplesUtil.escapeString(uriString.substring(splitIdx)));
		writer.append('>');
	} else {
		writer.append('<');
		writer.append(NTriplesUtil.escapeString(uriString));
		writer.append('>');
	}
}
 
Example 7
Source File: TestBigdataSailRemoteRepository.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test of insert and retrieval of a large literal.
 */
public void test_INSERT_veryLargeLiteral() throws Exception {

    final Graph g = new LinkedHashModel();
    
    final URI s = new URIImpl("http://www.bigdata.com/");
    final URI p = RDFS.LABEL;
    final Literal o = getVeryLargeLiteral();
    final Statement stmt = new StatementImpl(s, p, o);
    g.add(stmt);
    
    // Load the resource into the KB.
    assertEquals(
            1L,
            doInsertByBody("POST", RDFFormat.RDFXML, g, null/* defaultContext */));

    // Read back the data into a graph.
    final Graph g2;
    {
        final String queryStr = "DESCRIBE <" + s.stringValue() + ">";
        final GraphQuery query = cxn.prepareGraphQuery(QueryLanguage.SPARQL, queryStr);
        g2 = asGraph(query.evaluate());
        
    }
    
    assertEquals(1, g2.size());
    
    assertTrue(g2.match(s, p, o).hasNext());
    
}
 
Example 8
Source File: BigdataStoreTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void testValueRoundTrip(Resource subj, URI pred, Value obj)
        throws Exception {
    con.begin();
    con.addStatement(subj, pred, obj);
    con.commit();

    CloseableIteration<? extends Statement, SailException> stIter = con
            .getStatements(null, null, null, false);

    try {
        assertTrue(stIter.hasNext());

        Statement st = stIter.next();
        assertEquals(subj, st.getSubject());
        assertEquals(pred, st.getPredicate());
        assertEquals(obj, st.getObject());
        assertTrue(!stIter.hasNext());
    } finally {
        stIter.close();
    }

    final String query = "SELECT ?S ?P ?O WHERE { ?S ?P ?O filter(?P = <"
            + pred.stringValue() + ">) }";

    CloseableIteration<? extends BindingSet, QueryEvaluationException> iter;
    iter = evaluate(query, con);

    try {
        assertTrue(iter.hasNext());

        BindingSet bindings = iter.next();
        assertEquals(subj, bindings.getValue("S"));
        assertEquals(pred, bindings.getValue("P"));
        assertEquals(obj, bindings.getValue("O"));
        assertTrue(!iter.hasNext());
    } finally {
        iter.close();
    }
}
 
Example 9
Source File: RDFClass.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private void constants(JavaMessageBuilder builder) {
	List<? extends Value> oneOf = this.getList(OWL.ONEOF);
	if (oneOf != null) {
		Map<String, URI> names = new LinkedHashMap<String, URI>();
		for (Value one : oneOf) {
			if (one instanceof URI) {
				URI uri = (URI) one;
				String localPart = uri.getLocalName();
				if (localPart.length() < 1) {
					localPart = uri.stringValue();
				}
				String name = localPart.replaceAll("^[^a-zA-Z]", "_")
						.replaceAll("\\W+", "_");
				if (names.containsKey(name)) {
					int count = 1;
					while (names.containsKey(name + '_' + count)) {
						count++;
					}
					name = name + '_' + count;
				}
				names.put(name, uri);
			}
		}
		if (!names.isEmpty()) {
			names = toUpperCase(names);
			for (Map.Entry<String, URI> e : names.entrySet()) {
				builder.staticURIField(e.getKey(), e.getValue());
			}
			if (!names.containsKey("ONEOF")) {
				builder.staticURIArrayField("ONEOF", names.keySet());
			}
		}
	}
}
 
Example 10
Source File: AbstractRule.java    From neo4j-sparql-extension with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the URI of a constant {@link Var} object.
 *
 * @param v the {@link Var} object
 * @return URI as string if it is a URI, null otherwise
 */
protected String getURIString(Var v) {
	if (v.isConstant()) {
		Value val = v.getValue();
		if (val instanceof URI) {
			URI uri = (URI) val;
			return uri.stringValue();
		}
	}
	return null;
}
 
Example 11
Source File: AST2SPARQLUtil.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public String toExternal(final URI uri) {

        if (prefixDecls != null) {

            final String prefix = namespaces.get(uri.getNamespace());

            if (prefix != null) {

                return prefix + ":" + uri.getLocalName();

            }

        }

        return "<" + uri.stringValue() + ">";

    }
 
Example 12
Source File: TestSparqlUpdate.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void testLoadIntoGraph()
    throws Exception
{
	final URL url = this.getClass().getClassLoader().getResource("com/bigdata/rdf/rio/small.rdf");


    final URI g1 = f.createURI("http://www.bigdata.com/g1");
    final URI g2 = f.createURI("http://www.bigdata.com/g2");

    final String update = "LOAD <" + url.toExternalForm() + "> "
            + "INTO GRAPH <" + g1.stringValue() + ">";
    
    final String ns = "http://bigdata.com/test/data#";
    
    m_repo.prepareUpdate(update).evaluate();

    assertFalse(hasStatement(f.createURI(ns, "mike"), RDFS.LABEL,
            f.createLiteral("Michael Personick"), true, g2));

    assertTrue(hasStatement(f.createURI(ns, "mike"), RDFS.LABEL,
            f.createLiteral("Michael Personick"), true, g1));

}
 
Example 13
Source File: InlineURIFactory.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public URIExtensionIV createInlineURIIV(final URI uri) {

		final String str = uri.stringValue();

		// Find handler with longest prefix match LTE the given URI.
		final Map.Entry<String, InlineURIHandler> floorEntry = getHandlersByNamespace().floorEntry(str);

		if (floorEntry == null) {

    		// No potentially suitable handler.
    		return null;
 
		}

		final String prefix = floorEntry.getKey();
		
		/*
		 * Note: the floorEntry is NOT guaranteed to be a prefix. It can also be
		 * strictly LT the probe key. Therefore we must additionally verify here
		 * that the prefix under which the URI handler was registered is a
		 * prefix of the URI before invoking that handler.
		 */
		if (str.startsWith(prefix)) {

			final InlineURIHandler handler = floorEntry.getValue();

			final URIExtensionIV iv = handler.createInlineIV(uri);

			if (iv != null) {

				return iv;

			}

		}

		return null;

		/*
		 * Note: This code checks each handler. This is presumably being done
		 * because the ipv4 syntax can include "/" characters (for the optional
		 * netmask) so the URI namespace (as defined by openrdf) is not matching
		 * the prefix under which the handler is registered.
		 */
//        for (InlineURIHandler handler : handlersByNamespace.values()) {
//            final URIExtensionIV iv = handler.createInlineIV(uri);
//            if (iv != null) {
//                return iv;
//            }
//        }
//        return null;
    }
 
Example 14
Source File: DerivedNumericsExtension.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Attempts to convert the supplied value into an internal representation
 * using BigInteger.
 */
public LiteralExtensionIV createIV(final Value value) {
    
    if (value instanceof Literal == false)
        throw new IllegalArgumentException();
    
    final Literal lit = (Literal) value;
    
    final URI dt = lit.getDatatype();
    
    if (dt == null)
        throw new IllegalArgumentException();
    
    final String dts = dt.stringValue();
    
    BigdataURI resolvedDT = null;
    for (BigdataURI val : datatypes.values()) {
        // Note: URI.stringValue() is efficient....
        if (val.stringValue().equals(dts)) {
            resolvedDT = val;
        }
    }
    
    if (resolvedDT == null)
        throw new IllegalArgumentException();
    
    final String s = lit.getLabel();

    final boolean valid;
    if (dts.equals(XSD.POSITIVE_INTEGER.stringValue())) {
    	valid = XMLDatatypeUtil.isValidPositiveInteger(s);
    } else if (dts.equals(XSD.NEGATIVE_INTEGER.stringValue())) {
    	valid = XMLDatatypeUtil.isValidNegativeInteger(s);
    } else if (dts.equals(XSD.NON_POSITIVE_INTEGER.stringValue())) {
    	valid = XMLDatatypeUtil.isValidNonPositiveInteger(s);
    } else if (dts.equals(XSD.NON_NEGATIVE_INTEGER.stringValue())) {
    	valid = XMLDatatypeUtil.isValidNonNegativeInteger(s);
    } else {
    	valid = false;
    }
    
    if (!valid) {
    	throw new RuntimeException("could not correctly parse label: " + s + " for datatype: " + dts);
    }

    final BigInteger bi = XMLDatatypeUtil.parseInteger(s);
    
    final AbstractLiteralIV delegate = new XSDIntegerIV(bi);

    return new LiteralExtensionIV(delegate, resolvedDT.getIV());
    
}
 
Example 15
Source File: RMLMappingFactory.java    From GeoTriples with Apache License 2.0 4 votes vote down vote up
protected static ReferencingObjectMap extractReferencingObjectMap(
		CustomSesameDataset r2rmlMappingGraph, Resource object,
		Set<GraphMap> graphMaps,
		Map<Resource, TriplesMap> triplesMapResources)
		throws InvalidR2RMLStructureException, InvalidR2RMLSyntaxException, R2RMLDataError {
	log.debug("[RMLMappingFactory:extractReferencingObjectMap] Extract referencing object map..");
	URI parentTriplesMap = (URI) extractValueFromTermMap(r2rmlMappingGraph,
			object, R2RMLTerm.PARENT_TRIPLES_MAP);
	Set<JoinCondition> joinConditions = extractJoinConditions(
			r2rmlMappingGraph, object, graphMaps, triplesMapResources);
	
	
	if (parentTriplesMap == null && !joinConditions.isEmpty()) {
		throw new InvalidR2RMLStructureException(
				"[RMLMappingFactory:extractReferencingObjectMap] "
						+ object.stringValue()
						+ " has no parentTriplesMap map defined whereas one or more joinConditions exist"
						+ " : exactly one parentTripleMap is required.");
	}
	if (parentTriplesMap == null && joinConditions.isEmpty()) {
		log.debug("[RMLMappingFactory:extractReferencingObjectMap] This object map is not a referencing object map.");
		return null;
	}
	// Extract parent
	boolean contains = false;
	TriplesMap parent = null;
	for (Resource triplesMapResource : triplesMapResources.keySet()) {
		if (triplesMapResource.stringValue().equals(
				parentTriplesMap.stringValue())) {
			contains = true;
			parent = triplesMapResources.get(triplesMapResource);
			log.debug("[RMLMappingFactory:extractReferencingObjectMap] Parent triples map found : "
					+ triplesMapResource.stringValue());
			break;
		}
	}
	if (!contains) {
		throw new InvalidR2RMLStructureException(
				"[RMLMappingFactory:extractReferencingObjectMap] "
						+ object.stringValue()
						+ " reference to parent triples maps is broken : "
						+ parentTriplesMap.stringValue() + " not found.");
	}
	// Link between this reerencing object and its triplesMap parent will be
	// performed
	// at the end f treatment.
	ReferencingObjectMap refObjectMap = new StdReferencingObjectMap(null,
			parent, joinConditions);
	log.debug("[RMLMappingFactory:extractReferencingObjectMap] Extract referencing object map done.");
	return refObjectMap;
}
 
Example 16
Source File: SparqlDynamicErrorException.java    From database with GNU General Public License v2.0 2 votes vote down vote up
public GraphExistsException(final URI graphUri) {

            super(0001/* errorCode */, SPARQL_DYNAMIC_ERROR_0001,
                    new NV[] { new NV("uri", graphUri.stringValue()) });

        }
 
Example 17
Source File: SparqlDynamicErrorException.java    From database with GNU General Public License v2.0 2 votes vote down vote up
public GraphEmptyException(final URI graphUri) {

            super(0002/* errorCode */, SPARQL_DYNAMIC_ERROR_0002,
                    new NV[] { new NV("uri", graphUri.stringValue()) });

        }
 
Example 18
Source File: BlazeValueFactory.java    From tinkerpop3 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Convert an RDF URI (element id/label or property key) back into a string.
 * 
 * @param uri
 *          RDF representation of an element id/label or property key
 * @return
 *          property graph (string) representation
 */
default String fromURI(final URI uri) {
    final String s = uri.stringValue();
    return s.substring(s.lastIndexOf(':')+1);
}