|
| 1 | +package com.marklogic.client; |
| 2 | + |
| 3 | +import com.marklogic.client.query.StructuredQueryBuilder; |
| 4 | +import com.marklogic.client.query.StructuredQueryDefinition; |
| 5 | +import com.marklogic.rest.util.Fragment; |
| 6 | + |
| 7 | +import javax.xml.stream.XMLOutputFactory; |
| 8 | +import javax.xml.stream.XMLStreamWriter; |
| 9 | +import java.io.StringWriter; |
| 10 | + |
| 11 | +public class SerializeQueryTest { |
| 12 | + |
| 13 | + public static void main(String[] args) throws Exception { |
| 14 | + DatabaseClient client = new DatabaseClientBuilder() |
| 15 | + .withHost("localhost") |
| 16 | + .withPort(8000) |
| 17 | + .withDigestAuth("admin", "admin").build(); |
| 18 | + |
| 19 | + StructuredQueryBuilder qb = client.newQueryManager().newStructuredQueryBuilder(); |
| 20 | + StructuredQueryDefinition query = qb.and(qb.collection("hello"), qb.term("world")); |
| 21 | + |
| 22 | + final String SEARCH_NS = "http://marklogic.com/appservices/search"; |
| 23 | + |
| 24 | + XMLOutputFactory factory = XMLOutputFactory.newFactory(); |
| 25 | + // Required in order for default namespace to be applied. |
| 26 | + factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); |
| 27 | + |
| 28 | + StringWriter writer = new StringWriter(); |
| 29 | + XMLStreamWriter serializer = factory.createXMLStreamWriter(writer); |
| 30 | + |
| 31 | + // Must set this in order for the serialized query to be in the correct namespace. |
| 32 | + serializer.setDefaultNamespace(SEARCH_NS); |
| 33 | + |
| 34 | + serializer.writeStartElement("someOtherNamespace", "myDocument"); |
| 35 | + serializer.writeStartElement("someLocalElement"); |
| 36 | + serializer.writeEndElement(); |
| 37 | + |
| 38 | + // In order for query.serialize to work, it appears necessary to wrap the query in an element in the search |
| 39 | + // namespace. And because that's the default namespace on the XMLStreamWriter, it will be applied to each of |
| 40 | + // the child elements produced by query.serialize. |
| 41 | + serializer.writeStartElement(SEARCH_NS, "theMarkLogicQuery"); |
| 42 | + query.serialize(serializer); |
| 43 | + serializer.writeEndElement(); |
| 44 | + |
| 45 | + serializer.writeEndElement(); |
| 46 | + serializer.flush(); |
| 47 | + serializer.close(); |
| 48 | + |
| 49 | + String output = writer.toString(); |
| 50 | + new Fragment(output).prettyPrint(); |
| 51 | + } |
| 52 | +} |
0 commit comments