@Override public void write(OutputStream out) throws IOException { getMapper().writeValue(new OutputStreamWriter(out, "UTF-8"), get()); } }
@Override public Boolean executeAsk(SPARQLQueryDefinition qdef) { JsonNode result = executeQueryImpl(qdef, new JacksonHandle(), null, false).get(); return result.get("boolean").asBoolean(); }
@Override public Boolean executeAsk(SPARQLQueryDefinition qdef, Transaction tx) { JsonNode result = executeQueryImpl(qdef, new JacksonHandle(), tx, false).get(); return result.get("boolean").asBoolean(); }
@Test public void test105Searches() throws IOException { QueryManager queryMgr = Common.client.newQueryManager(); StructuredQueryBuilder qb = queryMgr.newStructuredQueryBuilder(); for (int i=0;i<105;i++) { for (QueryDefinition t : new QueryDefinition[] { qb.term("leaf3"), qb.build(qb.value(qb.element("leaf"), "leaf3")) }) { JacksonHandle results = queryMgr.search(t, new JacksonHandle()); assertNotNull(results); JsonNode jsonResults =results.get(); @SuppressWarnings("unused") String resultString = results.getMapper().writeValueAsString(jsonResults); // ignore. } } }
@Override public GraphPermissions getPermissions(String uri, Transaction transaction) { JsonNode json = services.getPermissions(requestLogger, uri, new JacksonHandle(), transaction).get(); GraphPermissions perms = new GraphPermissionsImpl(); for ( JsonNode permission : json.path("permissions") ) { String role = permission.path("role-name").asText(); Set<Capability> capabilities = new HashSet<>(); for ( JsonNode capability : permission.path("capabilities") ) { String value = capability.asText(); if ( value != null ) { capabilities.add(Capability.valueOf(value.toUpperCase())); } } perms.put(role, capabilities); } return perms; }
@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 testExecuteSelectQueryNullQDEF() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException { System.out.println("In SPARQL Query Manager Test testExecuteSelectQueryNullQDEF method"); SPARQLQueryManager sparqlQmgr = readclient.newSPARQLQueryManager(); String expectedException = "IllegalArgumentException"; String exception = ""; try { sparqlQmgr.executeSelect(null, new JacksonHandle()).get(); } catch (Exception e) { exception = e.toString(); } System.out.println("Exception thrown from testExecuteSelectQueryNullQDEF is \n" + exception); assertTrue(" Test testExecuteSelectQueryNullQDEF 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()); }
@Override public JsonNode validateAll() { ResourceServices.ServiceResultIterator resultItr = this.getServices().get(new RequestParameters()); if (resultItr == null || ! resultItr.hasNext()) { return null; } ResourceServices.ServiceResult res = resultItr.next(); return res.getContent(new JacksonHandle()).get(); }
@Test public void testWrite_rdfjson_JacksonHandle() throws Exception { File file = new File(datasource + "relative6.json"); FileHandle filehandle = new FileHandle(); filehandle.set(file); gmWriter.write("htp://test.sem.graph/rdfjson", filehandle.withMimetype("application/rdf+json")); JacksonHandle handle1 = gmWriter.read("htp://test.sem.graph/rdfjson", new JacksonHandle()); JsonNode readFile = handle1.get(); assertTrue("Did not insert document or inserted empty doc", readFile.toString().contains("http://purl.org/dc/elements/1.1/title")); }
private ArrayNode executeAndExtractBindings(SPARQLQueryDefinition qdef) { JacksonHandle handle = smgr.executeSelect(qdef, new JacksonHandle()); JsonNode results = handle.get(); ArrayNode bindings = (ArrayNode) results.findPath("results").findPath( "bindings"); return bindings; }
@Test public void testPOJOValueQueryWithCriteria() { PojoRepository<Artifact, Long> products = client.newPojoRepository(Artifact.class, Long.class); PojoPage<Artifact> p; this.loadSimplePojos(products); String[] searchOptions = { "case-sensitive", "wildcarded", "min-occurs=1" }; PojoQueryBuilder qb = products.getQueryBuilder(); String[] searchNames = { "Acme spe* *", "Widgets spe* *" }; PojoQueryDefinition qd = qb.value("name", searchOptions, 100.0, searchNames).withCriteria("Cogs 101"); JacksonHandle jh = new JacksonHandle(); products.setPageLength(5); p = products.search(qd, 1, jh); JsonNode nodePos = jh.get(); // Return 1 node - constraint2.xml assertEquals("Number of results returned incorrect in response", "1", nodePos.path("total").asText()); assertEquals("Result returned incorrect in response", "com.marklogic.client.functionaltest.Artifact/101.json", nodePos.path("results").get(0).path("uri").asText()); }
private void checkJSONDocRows(RowSet<JacksonHandle> rowSet) { int rowCount = 0; for (JacksonHandle jsonRow: rowSet) { JsonNode row = jsonRow.get(); rowCount++; String value = row.findValue("rowNum").findValue("value").asText(); assertEquals("unexpected first binding value in JSON", String.valueOf(rowCount), value); value = row.findValue("uri").findValue("value").asText(); assertEquals("unexpected second binding value in JSON", uris[rowCount - 1], value); if (uris[rowCount - 1].endsWith(".json")) { value = row.findValue("doc").findValue("value").toString(); assertEquals("unexpected third binding value in JSON", docs[rowCount - 1].replace(" ", ""), value); } else { value = row.findValue("doc").findValue("value").asText(); assertEquals("unexpected third binding value in JSON", docs[rowCount - 1], value); } } assertEquals("row count for JSON document join", 3, rowCount); } private void checkRecordDocRows(RowSet<RowRecord> rowSet) throws SAXException, IOException {
@Test public void testJSONOptions() throws JAXBException, ResourceNotFoundException, ForbiddenUserException, FailedRequestException, ResourceNotResendableException { QueryOptionsManager mgr = Common.adminClient.newServerConfigManager().newQueryOptionsManager(); assertNotNull("Client could not create query options manager", mgr); FileHandle jsonHandle = new FileHandle(new File("src/test/resources/json-config.json")); jsonHandle.setFormat(Format.JSON); mgr.writeOptions("jsonoptions", jsonHandle); JsonNode options = mgr.readOptions("jsonoptions", new JacksonHandle()).get(); assertEquals("JSON options came back incorrectly", options.findPath("constraint").get(0).get("name").textValue(), "decade"); StringHandle jsonStringHandle = new StringHandle(); jsonStringHandle.setFormat(Format.JSON); mgr.readOptions("jsonoptions", jsonStringHandle); assertTrue("JSON String from QueryManager must start with json options", jsonStringHandle.get().startsWith("{\"options\":")); mgr.deleteOptions("jsonoptions"); }; }
@Test public void runJSONErrorFlowWithoutTracing() { assertEquals(0, getFinalDocCount()); assertEquals(0, getTracingDocCount()); Tracing t = Tracing.create(flowRunnerClient); assertFalse(t.isEnabled()); Flow flow = fm.getFlow("trace-entity", "tracemeJSONError"); FlowRunner flowRunner = fm.newFlowRunner() .withFlow(flow) .withBatchSize(10) .withThreadCount(1); flowRunner.run(); flowRunner.awaitCompletion(); assertEquals(0, getFinalDocCount()); assertEquals(5, getTracingDocCount()); JsonNode node = jobDocMgr.search(allButCollectors(), 1).next().getContent(new JacksonHandle()).get(); System.out.println(node.asText()); assertEquals(1, node.get("trace").get("steps").size()); assertEquals("content", node.get("trace").get("steps").get(0).get("label").asText()); }
@Override public JsonNode validate(String entity, String flow, String plugin, String type, String content) { RequestParameters params = new RequestParameters(); params.add("entity", entity); params.add("flow", flow); params.add("plugin", plugin); params.add("type", type); StringHandle handle = new StringHandle(content); handle.setFormat(Format.TEXT); ResourceServices.ServiceResultIterator resultItr = this.getServices().post(params, handle ); if (resultItr == null || ! resultItr.hasNext()) { return null; } ResourceServices.ServiceResult res = resultItr.next(); return res.getContent(new JacksonHandle()).get(); } }
@Test public void testnamedSchemaViewWithQualifier() throws KeyManagementException, NoSuchAlgorithmException, IOException, SAXException, ParserConfigurationException { System.out.println("In testnamedSchemaViewWithQualifier method"); RowManager rowMgr = client.newRowManager(); PlanBuilder p = rowMgr.newPlanBuilder(); AccessPlan plan = p.fromView("opticFunctionalTest", "detail", "MarkLogicQAQualifier"); plan.orderBy(p.sortKeySeq(p.viewCol("opticFunctionalTest", "MarkLogicQAQualifier.masterId"), p.viewCol("opticFunctionalTest", "MarkLogicQAQualifier.color"), p.viewCol("opticFunctionalTest", "MarkLogicQAQualifier.amount"))); JacksonHandle jacksonHandle = new JacksonHandle(); jacksonHandle.setMimetype("application/json"); rowMgr.resultDoc(plan, jacksonHandle); JsonNode jsonResults = jacksonHandle.get(); JsonNode jsonBindingsNodes = jsonResults.path("rows"); // Should have 6 nodes returned. assertEquals("Six nodes not returned from testnamedSchemaViewWithQualifier method ", 6, jsonBindingsNodes.size()); }
@Test public void runJSONWriterErrorFlowWithoutTracing() { assertEquals(0, getFinalDocCount()); assertEquals(0, getTracingDocCount()); Tracing t = Tracing.create(flowRunnerClient); assertFalse(t.isEnabled()); Flow flow = fm.getFlow("trace-entity", "tracemeJSONWriterError"); FlowRunner flowRunner = fm.newFlowRunner() .withFlow(flow) .withBatchSize(10) .withThreadCount(1); flowRunner.run(); flowRunner.awaitCompletion(); assertEquals(0, getFinalDocCount()); assertEquals(5, getTracingDocCount()); JsonNode node = jobDocMgr.search(allButCollectors(), 1).next().getContent(new JacksonHandle()).get(); assertEquals(1, node.get("trace").get("steps").size()); assertEquals("writer", node.get("trace").get("steps").get(0).get("label").asText()); } }
@Test public void testExplain() throws IOException { RowManager rowMgr = Common.client.newRowManager(); PlanBuilder p = rowMgr.newPlanBuilder(); PlanBuilder.ExportablePlan builtPlan = p.fromLiterals(litRows); JsonNode jsonRoot = rowMgr.explain(builtPlan, new JacksonHandle()).get(); assertNotNull(jsonRoot); jsonRoot = rowMgr.explainAs(builtPlan, JsonNode.class); assertNotNull(jsonRoot); Document xmlRoot = rowMgr.explain(builtPlan, new DOMHandle()).get(); assertNotNull(xmlRoot); xmlRoot = rowMgr.explainAs(builtPlan, Document.class); assertNotNull(xmlRoot); String stringRoot = rowMgr.explain(builtPlan, new StringHandle()).get(); assertNotNull(new ObjectMapper().readTree(stringRoot)); } private DOMHandle initNamespaces(DOMHandle handle) {