/** * Create a new {@link com.marklogic.client.semantics.SPARQLQueryDefinition} * from a query String. You can use the resulting object to configure * various aspects of the query or set binding variables. * * @param queryString * A SPARQL Query or SPARQL Update. * @return A new * {@link com.marklogic.client.semantics.SPARQLQueryDefinition} */ public SPARQLQueryDefinition newQueryDefinition(String queryString) { return this.sparqlQueryManager.newQueryDefinition(queryString); }
sparqlQueryTrue.append(newline); sparqlQueryTrue.append("ASK { ?alum foaf:schoolHomepage <http://www.ucsb.edu/> }"); SPARQLQueryDefinition qdef = sparqlQmgr.newQueryDefinition(sparqlQueryTrue.toString()); boolean bAskTrue = sparqlQmgr.executeAsk(qdef); sparqlQueryfalse.append(newline); sparqlQueryfalse.append("ASK { ?alum foaf:schoolHomepage <http://www.blahblah.edu/> }"); SPARQLQueryDefinition qdef1 = sparqlQmgr.newQueryDefinition(sparqlQueryfalse.toString()); boolean bAskFalse = sparqlQmgr.executeAsk(qdef1); sparqlQueryEmpty.append(newline); sparqlQueryEmpty.append("ASK { }"); SPARQLQueryDefinition qdefEmpty = sparqlQmgr.newQueryDefinition(sparqlQueryEmpty.toString()); boolean bAskEmpty = sparqlQmgr.executeAsk(qdefEmpty);
SPARQLQueryDefinition qdef = sparqlQmgr.newQueryDefinition(sparqlQuery.toString());
@Test public void testSPARQLWithLimit() throws Exception { SPARQLQueryDefinition qdef1 = smgr.newQueryDefinition("select ?s ?p ?o { ?s ?p ?o } limit 1"); qdef1.setIncludeDefaultRulesets(false); qdef1.setCollections(graphUri); JsonNode jsonResults = smgr.executeSelect(qdef1, new JacksonHandle()).get(); int numResults = jsonResults.path("results").path("bindings").size(); // because we said 'limit 1' we should only get one result assertEquals(1, numResults); JsonNode firstResult = jsonResults.path("results").path("bindings").path(0); assertEquals(mapper.readTree(expectedFirstResult), firstResult); }
@Test public void testExecuteEmptySelectQuery() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException { System.out.println("In SPARQL Query Manager Test testExecuteEmptySelectQuery method"); SPARQLQueryManager sparqlQmgr = readclient.newSPARQLQueryManager(); StringBuffer sparqlQuery = new StringBuffer().append(""); SPARQLQueryDefinition qdef = sparqlQmgr.newQueryDefinition(sparqlQuery.toString()); String expectedException = "FailedRequestException"; String exception = ""; try { sparqlQmgr.executeSelect(qdef, new JacksonHandle()).get(); } catch (Exception e) { exception = e.toString(); } System.out.println("Exception thrown from testExecuteEmptySelectQuery is \n" + exception); assertTrue("Test testExecuteEmptySelectQuery method exception is not thrown", exception.contains(expectedException)); }
@Test public void testBaseUri() { // verify base has expected effect String relativeConstruct = "CONSTRUCT { <relative1> <relative2> <relative3> } \n" + "WHERE { ?s ?p ?o . } LIMIT 1"; SPARQLQueryDefinition qdef = smgr.newQueryDefinition(relativeConstruct); qdef.setBaseUri("http://marklogic.com/SPARQLQDefTest/"); JsonNode rdf = smgr.executeConstruct(qdef, new JacksonHandle()).get(); String subject = rdf.fieldNames().next(); assertEquals("base uri plus relative subject uri", "http://marklogic.com/SPARQLQDefTest/relative1", subject); String predicate = rdf.get(subject).fieldNames().next(); assertEquals("base uri plus relative predicate uri", "http://marklogic.com/SPARQLQDefTest/relative2", predicate); JsonNode objects = rdf.get(subject).get(predicate); assertEquals(1, objects.size()); assertEquals("base uri plus relative uri", "http://marklogic.com/SPARQLQDefTest/relative3", objects.path(0).path("value").asText()); }
@Test public void testExecuteConstruct() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException { System.out.println("In SPARQL Query Manager Test testExecuteConstruct method"); SPARQLQueryManager sparqlQmgr = readclient.newSPARQLQueryManager(); StringBuffer sparqlQuery = new StringBuffer().append(" PREFIX foaf: <http://xmlns.com/foaf/0.1/>"); sparqlQuery.append(newline); sparqlQuery.append("CONSTRUCT {<http://www.ucsb.edu/random-alum> foaf:knows ?alum }"); sparqlQuery.append(newline); sparqlQuery.append("where"); sparqlQuery.append(newline); sparqlQuery.append("{ ?alum foaf:schoolHomepage <http://www.ucsb.edu/> }"); SPARQLQueryDefinition qdef = sparqlQmgr.newQueryDefinition(sparqlQuery.toString()); // Execute Construct query String[] jsonResults = sparqlQmgr.executeConstruct(qdef, new StringHandle()).get().split(" "); // Account for the dot at the end of the triple. Hence size is 4. assertEquals("Method testExecuteConstruct in-memory Triple part size is incorrect", 4, jsonResults.length); assertEquals("Method testExecuteConstruct in-memory subject is incorrect", "<http://www.ucsb.edu/random-alum>", jsonResults[0]); assertEquals("Method testExecuteConstruct in-memory predicate is incorrect", "<http://xmlns.com/foaf/0.1/knows>", jsonResults[1]); assertEquals("Method testExecuteConstruct in-memory object is incorrect", "<1bfbfb8:ff2d706919:-7fa9>", jsonResults[2]); }
@Test public void testSPARQLWithTwoResults() throws Exception { SPARQLQueryDefinition qdef2 = smgr.newQueryDefinition("select ?s ?p ?o { ?s ?p ?o } limit 100"); qdef2.setIncludeDefaultRulesets(false); qdef2.setCollections(graphUri); JsonNode jsonResults = smgr.executeSelect(qdef2, new JacksonHandle()).get(); JsonNode tuples = jsonResults.path("results").path("bindings"); // loop through the "bindings" array (we would call each row a tuple) for ( int i=0; i < tuples.size(); i++ ) { JsonNode tuple = tuples.get(i); String s = tuple.path("s").path("value").asText(); String p = tuple.path("p").path("value").asText(); String o = tuple.path("o").path("value").asText(); if ( "http://example.org/s1".equals(s) ) { assertEquals("http://example.org/p1", p); assertEquals("http://example.org/o1", o); } else if ( "http://example.org/s2".equals(s) ) { assertEquals("http://example.org/p2", p); assertEquals("http://example.org/o2", o); } else { fail("Unexpected value for s:[" + s + "]"); } } }
@Test public void testDescribe() { // verify base has expected effect String relativeConstruct = "DESCRIBE <http://example.org/s1>"; SPARQLQueryDefinition qdef = smgr.newQueryDefinition(relativeConstruct); Document rdf = smgr.executeConstruct(qdef, new DOMHandle()).get(); Node description = rdf.getFirstChild().getFirstChild(); assertNotNull(description.getAttributes()); assertEquals("subject", "http://example.org/s1", description.getAttributes().item(0).getTextContent()); assertNotNull(description.getFirstChild()); assertEquals("predicate", "p1", description.getFirstChild().getNodeName()); assertEquals("predicate namespace", "http://example.org/", description.getFirstChild().getNamespaceURI()); NamedNodeMap attrs = description.getFirstChild().getAttributes(); assertNotNull(attrs); assertNotNull(attrs.getNamedItemNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "resource")); assertEquals("object", "http://example.org/o1", attrs.getNamedItemNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "resource").getTextContent()); }
@Test public void issue_357() { // open transaction Transaction transaction = Common.client.openTransaction(); try { // insert some data under transaction String insertString="BASE <http://example.org/addressbook>\n " + "INSERT DATA { <http://example.org/id#3333> <#email> \"jonny@ramone.com\"}"; SPARQLQueryDefinition insertDef = smgr.newQueryDefinition(insertString); smgr.executeUpdate(insertDef, transaction); // ask for it w/ transaction String queryString = "ASK WHERE { <http://example.org/id#3333> <http://example.org/addressbook#email> ?o }"; SPARQLQueryDefinition booleanDef = smgr.newQueryDefinition(queryString); assertTrue(smgr.executeAsk(booleanDef,transaction)); } finally { transaction.rollback(); } }
@Test public void testUsingURI() { // verify default graph String defGraphQuery = "INSERT { GRAPH <http://marklogic.com/SPARQLQDefTest/g3> " + "{ <http://marklogic.com/SPARQLQDefTest/r3> " + "<http://marklogic.com/SPARQLQDefTest/p3> " + "<http://marklogic.com/SPARQLQDefTest/o3> } } " + "WHERE { <http://marklogic.com/SPARQLQDefTest/r1> <http://marklogic.com/SPARQLQDefTest/p3> ?o }"; String defCheckQuery = "ASK WHERE { <http://marklogic.com/SPARQLQDefTest/r3> <http://marklogic.com/SPARQLQDefTest/p3> <http://marklogic.com/SPARQLQDefTest/o3> }"; SPARQLQueryDefinition qdef = smgr.newQueryDefinition(defGraphQuery); qdef.setUsingGraphUris("http://marklogic.com/SPARQLQDefTest/g1"); smgr.executeUpdate(qdef); SPARQLQueryDefinition checkDef = smgr.newQueryDefinition(defCheckQuery); checkDef.setDefaultGraphUris("http://marklogic.com/SPARQLQDefTest/g3"); assertTrue(smgr.executeAsk(checkDef)); // clean up smgr.executeUpdate(smgr.newQueryDefinition("DROP GRAPH <http://marklogic.com/SPARQLQDefTest/g3>")); assertFalse(smgr.executeAsk(checkDef)); }
@Test public void testSPARQLWithBindings() throws Exception { SPARQLQueryDefinition qdef3 = smgr.newQueryDefinition("construct { ?s ?p ?o } where { <subjectExample0> ?p ?o } "); qdef3.setIncludeDefaultRulesets(false); qdef3.setCollections(graphUri); StringHandle results1 = smgr.executeConstruct(qdef3, new StringHandle()); SPARQLQueryDefinition qdef4 = smgr.newQueryDefinition("select ?s ?p ?o { ?s ?p ?o . filter (?s = ?b) }"); qdef4.setCollections(graphUri); SPARQLBindings bindings = qdef4.getBindings(); bindings.bind("b", "http://example.org/s1"); qdef4.setBindings(bindings); // or use a builder qdef4 = qdef4.withBinding("c", "http://example.org/o2").withBinding("d", "http://example.org/o3"); DOMHandle handle = new DOMHandle(); handle.setMimetype(SPARQLMimeTypes.SPARQL_XML); Document jsonResults2 = smgr.executeSelect(qdef4, handle).get(); NodeList results = jsonResults2.getDocumentElement().getLastChild().getChildNodes(); // the number of children of the element "bindings" int numResults2 = results.getLength(); // because we said 'filter (?s = ?b)' we should only get one result assertEquals(1, numResults2); Node s = results.item(0).getChildNodes().item(0); Node o = results.item(0).getChildNodes().item(1); Node p = results.item(0).getChildNodes().item(2); assertEquals("http://example.org/s1", s.getTextContent()); assertEquals("http://example.org/p1", o.getTextContent()); assertEquals("http://example.org/o1", p.getTextContent()); }
@Override public void run() { Transaction t2 = writeclient.openTransaction(); try { System.out.println("In ExecuteAskSecondThreadFalse run method"); SPARQLQueryManager sparqlQmgrTh = writeclient.newSPARQLQueryManager(); StringBuffer sparqlQueryTh = new StringBuffer(); sparqlQueryTh.append("ASK FROM <rdfxml> where { <http://example.org/kennedy/person1> <http://purl.org/dc/elements/1.1/title> \"Person\'s title\"@en }"); SPARQLQueryDefinition qdefTh = sparqlQmgrTh.newQueryDefinition(sparqlQueryTh.toString()); // Verify result in t2 transaction. boolean bAskInTransT2 = sparqlQmgrTh.executeAsk(qdefTh, t2); System.out.println("Method ExecuteAskSecondThreadFalse Run result is " + bAskInTransT2); assertFalse("Class ExecuteAskSecondThreadFalse Run result is incorrect. No Records should be returned.", bAskInTransT2); setbCompleted(true); } catch (ForbiddenUserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FailedRequestException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (t2 != null) { t2.rollback(); t2 = null; } } } }
@Test public void testPagination() throws Exception { SPARQLQueryDefinition qdef1 = smgr.newQueryDefinition( "SELECT ?s ?p ?o FROM <" + graphUri + "> { ?s ?p ?o }"); qdef1.setIncludeDefaultRulesets(false); qdef1.setCollections(graphUri); long start = 1; smgr.setPageLength(1); JacksonHandle handle = new JacksonHandle(); handle.setMimetype(SPARQLMimeTypes.SPARQL_JSON); JsonNode results = smgr.executeSelect(qdef1, handle, start).get(); JsonNode bindings = results.path("results").path("bindings"); // because we set pageLength to 1 we should only get one result assertEquals(1, bindings.size()); String uri1 = bindings.get(0).get("s").get("value").asText(); smgr.setPageLength(2); results = smgr.executeSelect(qdef1, new JacksonHandle(), start).get(); // because we set pageLength to 2 we should get two results assertEquals(2, results.path("results").path("bindings").size()); start = 2; results = smgr.executeSelect(qdef1, new JacksonHandle(), start).get(); bindings = results.path("results").path("bindings"); // because we skipped the first result (by setting start=2) there are not enough // results for a full page, so size() only returns 1 assertEquals(1, bindings.size()); String uri2 = bindings.get(0).get("s").get("value").asText(); assertNotEquals(uri1, uri2); }
@Test public void testIncludeDefaultInference() { // install default inference. // TODO installDefaultInference("rdfs.rules"); // check query with and without // uninstall default inference. SPARQLQueryDefinition qdef = smgr .newQueryDefinition("select ?o where {?s a ?o . filter (?s = <http://marklogic.com/SPARQLQDefTest/r4> )}"); qdef.setIncludeDefaultRulesets(false); assertFalse(qdef.getIncludeDefaultRulesets()); JacksonHandle handle = smgr.executeSelect(qdef, new JacksonHandle()); JsonNode results = handle.get(); assertEquals("Size of results with no inference", 1, results.get("results").get("bindings").size()); qdef.setIncludeDefaultRulesets(true); handle = smgr.executeSelect(qdef, new JacksonHandle()); results = handle.get(); assertEquals("Size of results with default inference", 3, results.get("results").get("bindings").size()); qdef = smgr .newQueryDefinition( "select ?o where {?s a ?o . filter (?s = <http://marklogic.com/SPARQLQDefTest/r4> )}") .withIncludeDefaultRulesets(false); // TODO removeDefaultInference(); } }
@Test public void testNamedGraphUris() { SPARQLQueryDefinition qdef = smgr .newQueryDefinition("SELECT ?s where { GRAPH ?g { ?s a ?o } }"); qdef.setIncludeDefaultRulesets(false); qdef.setNamedGraphUris("http://marklogic.com/SPARQLQDefTest/g3"); ArrayNode bindings = executeAndExtractBindings(qdef); assertEquals("From named 0 result assertions", 0, bindings.size()); qdef.setNamedGraphUris("http://marklogic.com/SPARQLQDefTest/g4"); bindings = executeAndExtractBindings(qdef); assertEquals("From named 1 result assertions", 1, bindings.size()); qdef.setNamedGraphUris("http://marklogic.com/SPARQLQDefTest/g4", "http://marklogic.com/SPARQLQDefTest/g2"); bindings = executeAndExtractBindings(qdef); assertEquals("From named 1 result assertions", 2, bindings.size()); }
@Test public void testUsingNamedURI() { // verify default graph String defGraphQuery = "INSERT { GRAPH <http://marklogic.com/SPARQLQDefTest/g65> " + "{ <http://marklogic.com/SPARQLQDefTest/r3> " + "<http://marklogic.com/SPARQLQDefTest/p3> " + "<http://marklogic.com/SPARQLQDefTest/o3> } } " + "WHERE { GRAPH ?g { <http://marklogic.com/SPARQLQDefTest/r1> <http://marklogic.com/SPARQLQDefTest/p3> ?o } }"; String checkQuery = "ASK WHERE { <http://marklogic.com/SPARQLQDefTest/r3> <http://marklogic.com/SPARQLQDefTest/p3> <http://marklogic.com/SPARQLQDefTest/o3> }"; SPARQLQueryDefinition qdef = smgr.newQueryDefinition(defGraphQuery); // negative, no insert qdef.setUsingNamedGraphUris("http://marklogic.com/SPARQLQDefTest/baloney"); smgr.executeUpdate(qdef); SPARQLQueryDefinition checkDef = smgr.newQueryDefinition(checkQuery); checkDef.setDefaultGraphUris("http://marklogic.com/SPARQLQDefTest/g65"); assertFalse(smgr.executeAsk(checkDef)); // positive qdef.setUsingNamedGraphUris("http://marklogic.com/SPARQLQDefTest/g1"); smgr.executeUpdate(qdef); checkDef.setDefaultGraphUris("http://marklogic.com/SPARQLQDefTest/g65"); assertTrue(smgr.executeAsk(checkDef)); }
@Test public void testDefaultURI() { // verify default graph String defGraphQuery = "SELECT ?s WHERE { ?s a ?o }"; SPARQLQueryDefinition qdef = smgr.newQueryDefinition(defGraphQuery); qdef.setIncludeDefaultRulesets(false); qdef.setOptimizeLevel(1); // this only tests whether optimize level is set, not sent to server // I'm not sure how to test that assertEquals(1, qdef.getOptimizeLevel()); ArrayNode bindings = executeAndExtractBindings(qdef); qdef.setDefaultGraphUris("http://marklogic.com/SPARQLQDefTest/g4"); bindings = executeAndExtractBindings(qdef); assertEquals("Single graphs has one assertion", 1, bindings.size()); qdef.setDefaultGraphUris("http://marklogic.com/SPARQLQDefTest/g4", "http://marklogic.com/SPARQLQDefTest/g2"); bindings = executeAndExtractBindings(qdef); assertEquals("Union two default graphs has two assertions", 2, bindings.size()); }
@Test public void G_testSPARQLInsertPermissions() throws Exception { String localGraphUri = graphUri + ".SPARQLPermissions"; String sparql = "INSERT DATA { GRAPH <" + localGraphUri + "> { <s2> <p2> <o2> } }"; SPARQLQueryManager sparqlMgr = Common.client.newSPARQLQueryManager(); SPARQLQueryDefinition qdef = sparqlMgr.newQueryDefinition(sparql) .withUpdatePermission("write-privileged", Capability.READ) .withUpdatePermission("write-privileged", Capability.UPDATE); sparqlMgr.executeUpdate(qdef); GraphPermissions getPermissions = gmgr.getPermissions(localGraphUri); assertEquals(5, getPermissions.size()); assertNotNull(getPermissions.get("write-privileged")); assertEquals(2, getPermissions.get("write-privileged").size()); for ( Capability capability : getPermissions.get("write-privileged") ) { if ( capability == null ) fail("capability should not be null"); if ( capability != Capability.READ && capability != Capability.UPDATE ) { fail("capabilities should be read or update, not [" + capability + "]"); } } gmgr.delete(localGraphUri); } }
@Test public void testInference() throws Exception { gmgr.write("/ontology", new StringHandle(ontology).withMimetype("application/n-triples")); SPARQLQueryDefinition qdef = smgr.newQueryDefinition( "SELECT ?s { ?s a <http://example.org/C1> }"); qdef.setIncludeDefaultRulesets(false); StringHandle handle = new StringHandle().withMimetype(SPARQLMimeTypes.SPARQL_CSV); String results = smgr.executeSelect(qdef, handle).get(); assertEquals("%0D%0A", URLEncoder.encode(results, "utf8")); qdef.setRulesets(SPARQLRuleset.RANGE); results = smgr.executeSelect(qdef, handle).get(); assertEquals(1, countLines(parseCsv(results))); qdef.setRulesets(SPARQLRuleset.RANGE, SPARQLRuleset.DOMAIN); results = smgr.executeSelect(qdef, handle).get(); MappingIterator<Map<String,String>> csvRows = parseCsv(results); assertTrue(csvRows.hasNext()); Map<String,String> row = csvRows.next(); assertEquals("http://example.org/o1", row.get("s")); assertTrue(csvRows.hasNext()); row = csvRows.next(); assertEquals("http://example.org/s2", row.get("s")); assertFalse(csvRows.hasNext()); gmgr.delete("/ontology"); }