Java Code Examples for org.eclipse.rdf4j.model.IRI#toString()

The following examples show how to use org.eclipse.rdf4j.model.IRI#toString() . 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: StatementSerializer.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Write a {@link Statement} to a {@link String}
 *
 * @param statement
 *            the {@link Statement} to write
 * @return a {@link String} representation of the statement
 */
public static String writeStatement(final Statement statement) {
    final Resource subject = statement.getSubject();
    final Resource context = statement.getContext();
    final IRI predicate = statement.getPredicate();
    final Value object = statement.getObject();

    Validate.notNull(subject);
    Validate.notNull(predicate);
    Validate.notNull(object);

    String s = "";
    if (context == null) {
        s = SEP + subject.toString() + SEP + predicate.toString() + SEP + object.toString();
    } else {
        s = context.toString() + SEP + subject.toString() + SEP + predicate.toString() + SEP + object.toString();
    }
    return s;
}
 
Example 2
Source File: PowsyblWriter.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
private void writeResource(Value obj) throws IOException {
    Resource objRes = (Resource) obj;

    if (objRes instanceof BNode) {
        BNode bNode = (BNode) objRes;
        writeAttribute(RDF.NAMESPACE, "nodeID", getValidNodeId(bNode));
    } else {
        IRI uri = (IRI) objRes;
        String value = uri.toString();
        String prefix = namespaceTable.get(uri.getNamespace());
        // FIXME review the use of hard-coded literal "data" for CGMES
        if (prefix != null && prefix.equals("data")) {
            value = "#" + uri.getLocalName();
        }
        writeAttribute(RDF.NAMESPACE, "resource", value);
    }

    writeEndOfEmptyTag();
}
 
Example 3
Source File: IndexingMongoDBStorageStrategy.java    From rya with Apache License 2.0 6 votes vote down vote up
public Document getQuery(final StatementConstraints contraints) {
    final QueryBuilder queryBuilder = QueryBuilder.start();
    if (contraints.hasSubject()){
        queryBuilder.and(new Document(SUBJECT, contraints.getSubject().toString()));
    }

    if (contraints.hasPredicates()){
        final Set<IRI> predicates = contraints.getPredicates();
        if (predicates.size() > 1){
            for (final IRI pred : predicates){
                final Document currentPred = new Document(PREDICATE, pred.toString());
                queryBuilder.or(currentPred);
            }
        }
        else if (!predicates.isEmpty()){
            queryBuilder.and(new Document(PREDICATE, predicates.iterator().next().toString()));
        }
    }
    if (contraints.hasContext()){
        queryBuilder.and(new Document(CONTEXT, contraints.getContext().toString()));
    }
    return queryBuilder.get();
}
 
Example 4
Source File: CbSailTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testSimpleQuery() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI cpu = VF.createIRI(litdupsNS, "cpu");
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    IRI uri1 = VF.createIRI(litdupsNS, "uri1");
    conn.add(cpu, loadPerc, uri1);
    conn.commit();
    conn.close();

    resultEndpoint.expectedMessageCount(1);

    //query through camel
    String query = "select * where {" +
            "<" + cpu.toString() + "> ?p ?o1." +
            "}";
    template.sendBodyAndHeader(null, CbSailComponent.SPARQL_QUERY_PROP, query);

    assertMockEndpointsSatisfied();
}
 
Example 5
Source File: ForwardChainingRDFSInferencerConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int applyRuleX1() throws SailException {
	int nofInferred = 0;

	String prefix = RDF.NAMESPACE + "_";
	Iterable<Statement> iter = newThisIteration.getStatements(null, null, null);

	for (Statement st : iter) {
		IRI predNode = st.getPredicate();
		String predURI = predNode.toString();

		if (predURI.startsWith(prefix) && isValidPredicateNumber(predURI.substring(prefix.length()))) {
			boolean added = addInferredStatement(predNode, RDF.TYPE, RDFS.CONTAINERMEMBERSHIPPROPERTY);
			if (added) {
				nofInferred++;
			}
		}
	}

	return nofInferred;
}
 
Example 6
Source File: SPARQLResultsCSVWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void writeURI(IRI uri) throws IOException {
	String uriString = uri.toString();
	boolean quoted = uriString.contains(",");

	if (quoted) {
		// write opening quote for entire value
		writer.write("\"");
	}

	writer.write(uriString);

	if (quoted) {
		// write closing quote for entire value
		writer.write("\"");
	}
}
 
Example 7
Source File: FallbackDataset.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void appendURI(StringBuilder sb, IRI uri) {
	String str = uri.toString();
	if (str.length() > 50) {
		sb.append("<").append(str, 0, 19).append("..");
		sb.append(str, str.length() - 29, str.length()).append(">\n");
	} else {
		sb.append("<").append(uri).append(">\n");
	}
}
 
Example 8
Source File: CbSailTest.java    From rya with Apache License 2.0 5 votes vote down vote up
public void testSimpleQueryAuth() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI cpu = VF.createIRI(litdupsNS, "cpu");
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    IRI uri1 = VF.createIRI(litdupsNS, "uri1");
    IRI uri2 = VF.createIRI(litdupsNS, "uri2");
    IRI auth1 = VF.createIRI(RdfCloudTripleStoreConstants.AUTH_NAMESPACE, "auth1");
    conn.add(cpu, loadPerc, uri1, auth1);
    conn.add(cpu, loadPerc, uri2);
    conn.commit();
    conn.close();

    resultEndpoint.expectedMessageCount(1);

    //query through camel
    String query = "select * where {" +
            "<" + cpu.toString() + "> ?p ?o1." +
            "}";
    template.sendBodyAndHeader(null, CbSailComponent.SPARQL_QUERY_PROP, query);

    assertMockEndpointsSatisfied();

    resultEndpoint.expectedMessageCount(2);

    query = "select * where {" +
            "<" + cpu.toString() + "> ?p ?o1." +
            "}";
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(CbSailComponent.SPARQL_QUERY_PROP, query);
    headers.put(RdfCloudTripleStoreConfiguration.CONF_QUERY_AUTH, "auth1");
    template.sendBodyAndHeaders(null, headers);

    assertMockEndpointsSatisfied();
}
 
Example 9
Source File: TurtleParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void parsePrefixID() throws IOException, RDFParseException, RDFHandlerException {
	skipWSC();

	// Read prefix ID (e.g. "rdf:" or ":")
	StringBuilder prefixID = new StringBuilder(8);

	while (true) {
		int c = readCodePoint();

		if (c == ':') {
			unread(c);
			break;
		} else if (TurtleUtil.isWhitespace(c)) {
			break;
		} else if (c == -1) {
			throwEOFException();
		}

		appendCodepoint(prefixID, c);
	}

	skipWSC();

	verifyCharacterOrFail(readCodePoint(), ":");

	skipWSC();

	// Read the namespace URI
	IRI namespace = parseURI();

	// Store and report this namespace mapping
	String prefixStr = prefixID.toString();
	String namespaceStr = namespace.toString();

	setNamespace(prefixStr, namespaceStr);

	if (rdfHandler != null) {
		rdfHandler.handleNamespace(prefixStr, namespaceStr);
	}
}
 
Example 10
Source File: TurtleWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void writeURI(IRI uri) throws IOException {
	String uriString = uri.toString();

	// Try to find a prefix for the URI's namespace
	String prefix = null;

	int splitIdx = TurtleUtil.findURISplitIndex(uriString);
	if (splitIdx > 0) {
		String namespace = uriString.substring(0, splitIdx);
		prefix = namespaceTable.get(namespace);
	}

	if (prefix != null) {
		// Namespace is mapped to a prefix; write abbreviated URI
		writer.write(prefix);
		writer.write(":");
		writer.write(uriString.substring(splitIdx));
	} else if (baseIRI != null) {
		// Write relative URI
		writer.write("<");
		StringUtil.simpleEscapeIRI(baseIRI.relativize(uriString), writer, false);
		writer.write(">");
	} else {
		// Write full URI
		writer.write("<");
		StringUtil.simpleEscapeIRI(uriString, writer, false);
		writer.write(">");
	}
}
 
Example 11
Source File: TupleExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Object visit(ASTFunctionCall node, Object data) throws VisitorException {
	ValueConstant uriNode = (ValueConstant) node.jjtGetChild(0).jjtAccept(this, null);
	IRI functionURI = (IRI) uriNode.getValue();

	FunctionCall functionCall = new FunctionCall(functionURI.toString());

	for (int i = 1; i < node.jjtGetNumChildren(); i++) {
		Node argNode = node.jjtGetChild(i);
		functionCall.addArg(castToValueExpr(argNode.jjtAccept(this, null)));
	}

	return functionCall;
}
 
Example 12
Source File: SimpleDataset.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void appendURI(StringBuilder sb, IRI uri) {
	String str = uri.toString();
	if (str.length() > 50) {
		sb.append("<").append(str, 0, 19).append("..");
		sb.append(str, str.length() - 29, str.length()).append(">\n");
	} else {
		sb.append("<").append(uri).append(">\n");
	}
}
 
Example 13
Source File: PowsyblWriter.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void handleStatement(Statement st) {
    if (!writingStarted) {
        throw new RDFHandlerException("Document writing has not yet been started");
    }

    Resource subj = st.getSubject();
    IRI pred = st.getPredicate();
    Value obj = st.getObject();

    // Verify that an XML namespace-qualified name can be created for the predicate
    String predString = pred.toString();
    int predSplitIdx = XMLUtil.findURISplitIndex(predString);
    if (predSplitIdx == -1) {
        throw new RDFHandlerException("Unable to create XML namespace-qualified name for predicate: " + predString);
    }

    String predNamespace = predString.substring(0, predSplitIdx);
    String predLocalName = predString.substring(predSplitIdx);

    try {
        if (!headerWritten) {
            writeHeader();
        }

        // SUBJECT
        if (!subj.equals(lastWrittenSubject)) {
            writeNewSubject(subj, obj, st.getContext().stringValue());
        } else {
            writeLastSubject(obj, predNamespace, predLocalName);
        }

        // Don't write </rdf:Description> yet, maybe the next statement
        // has the same subject.
    } catch (IOException e) {
        throw new RDFHandlerException(e);
    }
}
 
Example 14
Source File: ValueStore.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Creates a NativeURI that is equal to the supplied URI. This method returns the supplied URI itself if it is
 * already a NativeURI that has been created by this ValueStore, which prevents unnecessary object creations.
 *
 * @return A NativeURI for the specified URI.
 */
public NativeIRI getNativeURI(IRI uri) {
	if (isOwnValue(uri)) {
		return (NativeIRI) uri;
	}

	return new NativeIRI(revision, uri.toString());
}
 
Example 15
Source File: SPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void upload(IRI graphURI, Resource context) throws Exception {
	RepositoryConnection con = dataRep.getConnection();

	try {
		con.begin();
		RDFFormat rdfFormat = Rio.getParserFormatForFileName(graphURI.toString()).orElse(RDFFormat.TURTLE);
		RDFParser rdfParser = Rio.createParser(rdfFormat, dataRep.getValueFactory());
		rdfParser.setVerifyData(false);
		rdfParser.setDatatypeHandling(DatatypeHandling.IGNORE);
		// rdfParser.setPreserveBNodeIDs(true);

		RDFInserter rdfInserter = new RDFInserter(con);
		rdfInserter.enforceContext(context);
		rdfParser.setRDFHandler(rdfInserter);

		URL graphURL = new URL(graphURI.toString());
		InputStream in = graphURL.openStream();
		try {
			rdfParser.parse(in, graphURI.toString());
		} finally {
			in.close();
		}

		con.commit();
	} catch (Exception e) {
		if (con.isActive()) {
			con.rollback();
		}
		throw e;
	} finally {
		con.close();
	}
}
 
Example 16
Source File: SPARQLComplianceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void upload(IRI graphURI, Resource context) throws Exception {
	RepositoryConnection con = getDataRepository().getConnection();

	try {
		con.begin();
		RDFFormat rdfFormat = Rio.getParserFormatForFileName(graphURI.toString()).orElse(RDFFormat.TURTLE);
		RDFParser rdfParser = Rio.createParser(rdfFormat, getDataRepository().getValueFactory());
		rdfParser.setVerifyData(false);
		rdfParser.setDatatypeHandling(DatatypeHandling.IGNORE);
		// rdfParser.setPreserveBNodeIDs(true);

		RDFInserter rdfInserter = new RDFInserter(con);
		rdfInserter.enforceContext(context);
		rdfParser.setRDFHandler(rdfInserter);

		URL graphURL = new URL(graphURI.toString());
		InputStream in = graphURL.openStream();
		try {
			rdfParser.parse(in, graphURI.toString());
		} finally {
			in.close();
		}

		con.commit();
	} catch (Exception e) {
		if (con.isActive()) {
			con.rollback();
		}
		throw e;
	} finally {
		con.close();
	}
}
 
Example 17
Source File: SPARQLResultsTSVWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void writeURI(IRI uri) throws IOException {
	String uriString = uri.toString();
	writer.write("<" + uriString + ">");
}
 
Example 18
Source File: SearchFields.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static String getPropertyField(IRI property) {
	return property.toString();
}
 
Example 19
Source File: HasValueVisitor.java    From rya with Apache License 2.0 4 votes vote down vote up
/**
 * Checks whether facts matching the StatementPattern could be derived using
 * has-value inference, and if so, replaces the StatementPattern node with a
 * union of itself and any such possible derivations.
 */
@Override
protected void meetSP(StatementPattern node) throws Exception {
    final Var subjVar = node.getSubjectVar();
    final Var predVar = node.getPredicateVar();
    final Var objVar = node.getObjectVar();
    // We can reason over two types of statement patterns:
    // { ?var rdf:type :Restriction } and { ?var :property ?value }
    // Both require defined predicate
    if (predVar != null && predVar.getValue() != null) {
        final IRI predIRI = (IRI) predVar.getValue();
        if (RDF.TYPE.equals(predIRI) && objVar != null && objVar.getValue() != null
                && objVar.getValue() instanceof Resource) {
            // If the predicate is rdf:type and the type is specified, check whether it can be
            // inferred using any hasValue restriction(s)
            final Resource objType = (Resource) objVar.getValue();
            final Map<IRI, Set<Value>> sufficientValues = inferenceEngine.getHasValueByType(objType);
            if (sufficientValues.size() > 0) {
                final Var valueVar = new Var("v-" + UUID.randomUUID());
                TupleExpr currentNode = node.clone();
                for (IRI property : sufficientValues.keySet()) {
                    final Var propVar = new Var(property.toString(), property);
                    final TupleExpr valueSP = new DoNotExpandSP(subjVar, propVar, valueVar);
                    final FixedStatementPattern relevantValues = new FixedStatementPattern(objVar, propVar, valueVar);
                    for (Value value : sufficientValues.get(property)) {
                        relevantValues.statements.add(new NullableStatementImpl(objType, property, value));
                    }
                    currentNode = new InferUnion(currentNode, new InferJoin(relevantValues, valueSP));
                }
                node.replaceWith(currentNode);
            }
        }
        else {
            // If the predicate has some hasValue restriction associated with it, then finding
            // that the object belongs to the appropriate type implies a value.
            final Map<Resource, Set<Value>> impliedValues = inferenceEngine.getHasValueByProperty(predIRI);
            if (impliedValues.size() > 0) {
                final Var rdfTypeVar = new Var(RDF.TYPE.stringValue(), RDF.TYPE);
                final Var typeVar = new Var("t-" + UUID.randomUUID());
                final Var hasValueVar = new Var(OWL.HASVALUE.stringValue(), OWL.HASVALUE);
                final TupleExpr typeSP = new DoNotExpandSP(subjVar, rdfTypeVar, typeVar);
                final FixedStatementPattern typeToValue = new FixedStatementPattern(typeVar, hasValueVar, objVar);
                final TupleExpr directValueSP = node.clone();
                for (Resource type : impliedValues.keySet()) {
                    // { ?var rdf:type :type } implies { ?var :property :val } for certain (:type, :val) pairs
                    for (Value impliedValue : impliedValues.get(type)) {
                        typeToValue.statements.add(new NullableStatementImpl(type, OWL.HASVALUE, impliedValue));
                    }
                }
                node.replaceWith(new InferUnion(new InferJoin(typeToValue, typeSP), directValueSP));
            }
        }
    }
}
 
Example 20
Source File: PowsyblWriter.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
private void writeNewSubject(Resource subj, Value obj, String ctxt) throws IOException {
    flushPendingStatements();

    String objString = obj.toString();
    int objSplitIdx = XMLUtil.findURISplitIndex(objString);
    if (objSplitIdx == -1) {
        throw new RDFHandlerException("Unable to create XML namespace-qualified name for predicate: " + objString);
    }
    String objNamespace = objString.substring(0, objSplitIdx);
    String objLocalName = objString.substring(objSplitIdx);

    // Write new subject:
    writeNewLine();
    writeStartOfStartTag(objNamespace, objLocalName);

    // FIXME This is hard-coded logic for processing CGMES data
    IRI uri = (IRI) subj;
    String attName = "ID";
    String value = uri.toString();
    String prefix = namespaceTable.get(uri.getNamespace());
    if (uri.getNamespace().equals("urn:uuid:")) {
        if (objLocalName.equals("FullModel")) {
            attName = "about";
        } else {
            value = "_" + uri.getLocalName();
        }
    }
    if (prefix != null && prefix.equals("data")) {
        if (ctxt.contains("_SSH_") || (ctxt.contains("_DY_") && objLocalName.equals("EnergyConsumer"))
                || (ctxt.contains("_TP_") && !objLocalName.equals("TopologicalNode"))) {
            attName = "about";
            value = "#" + uri.getLocalName();
        } else {
            value = uri.getLocalName();
        }
    }

    writeAttribute(RDF.NAMESPACE, attName, value);
    writeEndOfStartTag();
    writeNewLine();
    lastWrittenSubject = subj;
    lastObjNamespace = objNamespace;
    lastObjLocalName = objLocalName;
}