/** * Returns the DOM document as an XML string. */ @Override public String toString() { try { return new String(toBuffer(),"UTF-8"); } catch (UnsupportedEncodingException e) { throw new MarkLogicIOException(e); } }
/** * Initializes the handle with a DOM document for the content. * @param content a DOM document */ public DOMHandle(Document content) { this(); set(content); }
/** * Evaluate a compiled XPath expression against the retrieved document. * An XPath expression can return a Node or subinterface such as * Element or Text, a NodeList, or a Boolean, Number, or String value. * @param xpathExpression an XPath expression compiled previously * @param as the type of the value * @return the value produced by the XPath expression */ public <T> T evaluateXPath(XPathExpression xpathExpression, Class<T> as) throws XPathExpressionException { return evaluateXPath(xpathExpression, get(), as); } /**
/** * Evaluate a string XPath expression relative to a node such as a node * returned by a previous XPath expression. * An XPath expression can return a Node or subinterface such as * Element or Text, a NodeList, or a Boolean, Number, or String value. * @param xpathExpression the XPath expression as a string * @param context the node for evaluating the expression * @param as the type of the value * @return the value produced by the XPath expression */ public <T> T evaluateXPath(String xpathExpression, Node context, Class<T> as) throws XPathExpressionException { checkContext(context); return castAs( getXPathProcessor().evaluate(xpathExpression, context, returnXPathConstant(as)), as ); } /**
DOMHandle writeMetadataHandle = new DOMHandle(); writeMetadataHandle.set(docMetadata); DOMHandle readMetadataHandle = new DOMHandle(); Document docReadMetadata = readMetadataHandle.get(); DOMHandle writeMetadataHandleUpdate = new DOMHandle(); writeMetadataHandleUpdate.set(docMetadataUpdate); DOMHandle readMetadataHandleUpdate = new DOMHandle(); Document docReadMetadataUpdate = readMetadataHandleUpdate.get(); DOMHandle readMetadataHandleDelete = new DOMHandle(); Document docReadMetadataDelete = readMetadataHandleDelete.get();
static public DOMHandle DocumentToHandle(Document value) { return (value == null) ? null : new DOMHandle(value); } static public Stream<DOMHandle> DocumentToHandle(Stream<? extends Document> values) {
qdef.setCriteria("leaf3"); DOMHandle responseHandle = queryMgr.search(qdef, new DOMHandle()); Document doc = responseHandle.get(); assertNotNull("null response document", doc); responseHandle.getXPathProcessor().setNamespaceContext(namespaces); String total = responseHandle.evaluateXPath("string(/search:response/@total)", String.class); assertNotNull("null total", total); XPathExpression resultsExpression = responseHandle.compileXPath("/search:response/search:result"); NodeList resultList = responseHandle.evaluateXPath(resultsExpression, NodeList.class); assertNotNull("null result list", resultList); assertEquals("result count mismatch", resultList.getLength(), Integer.parseInt(total)); Element firstResult = responseHandle.evaluateXPath("/search:response/search:result[1]", Element.class); assertNotNull("null first result", firstResult); String firstResultUri = responseHandle.evaluateXPath("string(@uri)", firstResult, String.class); String firstItemUri = ((Element) resultList.item(0)).getAttribute("uri"); assertEquals("first uri mismatch", firstResultUri, firstItemUri);
/** * Write document using DOMHandle * * @param client * @param filename * @param uri * @param type * @throws IOException * @throws ParserConfigurationException * @throws SAXException */ public void writeDocumentUsingDOMHandle(DatabaseClient client, String filename, String uri, String type) throws IOException, ParserConfigurationException, SAXException { // create doc manager DocumentManager docMgr = null; docMgr = documentManagerSelector(client, docMgr, type); // acquire the content DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document content = docBuilder.parse(new File("src/test/java/com/marklogic/client/functionaltest/data/" + filename)); // create an identifier for the document String docId = uri + filename; // create a handle on the content DOMHandle handle = new DOMHandle(); handle.set(content); // write the document content docMgr.write(docId, handle); System.out.println("Write " + docId + " to database"); }
DOMHandle writeMetadataHandle = new DOMHandle(); writeMetadataHandle.set(docMetadata); writeset.add(docdisc, new DOMHandle(getDocumentContent("This is so foo1"))); writeset.add(docId[1], new DOMHandle().with(getDocumentContent("This is so foo2"))); writeset.add(docId[2], new DOMHandle().with(getDocumentContent("This is so foo3"))); DocumentRecord rec; Document docReadMetadata = null; DOMHandle mh = new DOMHandle(); while (page.hasNext()) { rec = page.next(); docMgr.readMetadata(rec.getUri(), mh); docReadMetadata = mh.get(); assertXpathEvaluatesTo("coll1", "string(//*[local-name()='collection'][1])", docReadMetadata); assertXpathEvaluatesTo("coll3", "string(//*[local-name()='collection'][2])", docReadMetadata); writeset.add(docId[3], new DOMHandle(getDocumentContent("This is so foo4"))); writeset.addDefault(mh2); writeset.add(docId[4], writeMetadataHandle, new DOMHandle().with(getDocumentContent("This is so foo5"))); writeset.add(docId[5], new DOMHandle().with(getDocumentContent("This is so foo6"))); docMgr.write(writeset); rec = page.next(); docMgr.readMetadata(rec.getUri(), mh); docReadMetadata = mh.get(); System.out.println(rec.getUri() + " " + docReadMetadata + docId[4]); assertXpathEvaluatesTo("coll1", "string(//*[local-name()='collection'][1])", docReadMetadata);
@Test public void testWriteMultipleXMLDoc() throws KeyManagementException, NoSuchAlgorithmException, Exception { String docId[] = { "/foo/test/Foo1.xml", "/foo/test/Foo2.xml", "/foo/test/Foo3.xml" }; XMLDocumentManager docMgr = client.newXMLDocumentManager(); DocumentWriteSet writeset = docMgr.newWriteSet(); writeset.add(docId[0], new DOMHandle(getDocumentContent("This is so foo1"))); writeset.add(docId[1], new DOMHandle().with(getDocumentContent("This is so foo2"))); writeset.add(docId[2], new DOMHandle().with(getDocumentContent("This is so foo3"))); docMgr.write(writeset); DOMHandle dh = new DOMHandle(); docMgr.read(docId[0], dh); assertEquals("xml document write difference", "This is so foo1", dh.get().getChildNodes().item(0).getTextContent()); docMgr.read(docId[1], dh); assertEquals("xml document write difference", "This is so foo2", dh.get().getChildNodes().item(0).getTextContent()); docMgr.read(docId[2], dh); assertEquals("xml document write difference", "This is so foo3", dh.get().getChildNodes().item(0).getTextContent()); // Bulk delete on XMLDocumentManager docMgr.delete(docId[0], docId[1], docId[2]); }
@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 List<File> exportWorkspaces(String user, String... workspaceNames) { if (baseDir == null) { baseDir = getDefaultWorkspacesDir(); } File userDir = new File(baseDir, user); userDir.mkdirs(); List<File> files = new ArrayList<>(); for (String workspaceName : workspaceNames) { EvalResultIterator result = client.newServerEval() .addVariable("user", user) .addVariable("workspace", workspaceName) .xquery(QconsoleScripts.EXPORT).eval(); while (result.hasNext()) { DOMHandle dom = result.next().get(new DOMHandle()); File f = new File(userDir, workspaceName + ".xml"); try { FileCopyUtils.copy(dom.toBuffer(), f); if (logger.isInfoEnabled()) { logger.info(format("Exported workspace %s to %s", workspaceName, f.getAbsolutePath())); } files.add(f); } catch (IOException ie) { throw new RuntimeException("Unable to write workspace XML to file, workspace: " + workspaceName + "; cause: " + ie.getMessage()); } } } return files; }
String beforeStr = null; DOMHandle domH = new DOMHandle().with(domDocument); before = domH.toBuffer(); beforeStr = new String(before); assertXMLEqual("Bytes buffering",beforeStr,new String(after)); domH.fromBuffer(before); after = domH.toBuffer(); assertNotNull("DOM after",after); assertXMLEqual("DOM buffering",beforeStr,new String(after));
public static void writeDoc() throws Exception { Document domDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = domDocument.createElement("root"); root.setAttribute("xml:lang", "en"); root.setAttribute("foo", "bar"); root.appendChild(domDocument.createElement("child")); root.appendChild(domDocument.createTextNode("mixed")); domDocument.appendChild(root); @SuppressWarnings("unused") String domString = ((DOMImplementationLS) DocumentBuilderFactory.newInstance().newDocumentBuilder() .getDOMImplementation()).createLSSerializer().writeToString(domDocument); XMLDocumentManager docMgr = client.newXMLDocumentManager(); docMgr.write(docId, new DOMHandle().with(domDocument)); }
RowSet<DOMHandle> xmlRowSet = rowMgr.resultRows(plan, new DOMHandle()); checkHeader("XML", xmlRowSet, datatypeStyle); assertTrue("no XML row to iterate", xmlRowItr.hasNext()); DOMHandle xmlRow = initNamespaces(xmlRowItr.next()); checkSingleRow(xmlRow.evaluateXPath("/table:row/table:cell", NodeList.class), datatypeStyle); assertFalse("expected one XML row", xmlRowItr.hasNext()); DOMHandle xmlRow = initNamespaces(new DOMHandle().with(xmlRowItrAs.next())); checkSingleRow(xmlRow.evaluateXPath("/table:row/table:cell", NodeList.class), datatypeStyle); assertFalse("expected one XML row", xmlRowItrAs.hasNext());
DOMHandle domHandle = initNamespaces(rowMgr.resultDoc(plan, new DOMHandle())); NodeList testList = domHandle.evaluateXPath("/table:table/table:columns/table:column", NodeList.class); assertEquals("unexpected header count in XML", 2, testList.getLength()); Element testElement = (Element) testList.item(0); testList = domHandle.evaluateXPath("/table:table/table:rows/table:row", NodeList.class); assertEquals("unexpected row count in XML", 1, testList.getLength()); testList = domHandle.evaluateXPath("/table:table/table:rows/table:row[1]/table:cell", NodeList.class); checkSingleRow(testList, datatypeStyle);
@Override public Content adapt(DocumentWriteOperation operation) { String uri = operation.getUri(); ContentCreateOptions options = adaptMetadata(operation.getMetadata()); AbstractWriteHandle handle = operation.getContent(); if (handle instanceof StringHandle) { return ContentFactory.newContent(uri, ((StringHandle) handle).get(), options); } else if (handle instanceof FileHandle) { return ContentFactory.newContent(uri, ((FileHandle) handle).get(), options); } else if (handle instanceof BytesHandle) { return ContentFactory.newContent(uri, ((BytesHandle) handle).get(), options); } else if (handle instanceof InputStreamHandle) { try { return ContentFactory.newContent(uri, ((InputStreamHandle) handle).get(), options); } catch (IOException e) { throw new RuntimeException("Unable to read content input stream: " + e.getMessage(), e); } } else if (handle instanceof DOMHandle) { return ContentFactory.newContent(uri, ((DOMHandle) handle).get(), options); } else throw new IllegalArgumentException("No support yet for content class: " + handle.getClass().getName()); }