use of org.xmldb.api.base.ResourceIterator in project exist by eXist-db.
the class XMLDBXPathTask method execute.
@Override
public void execute() throws BuildException {
if (uri == null) {
throw new BuildException("you have to specify an XMLDB collection URI");
}
if (text != null) {
final PropertyHelper helper = PropertyHelper.getPropertyHelper(getProject());
query = helper.replaceProperties(null, text, null);
}
if (query == null) {
throw new BuildException("you have to specify a query");
}
log("XPath is: " + query, org.apache.tools.ant.Project.MSG_DEBUG);
registerDatabase();
try {
log("Get base collection: " + uri, Project.MSG_DEBUG);
final Collection base = DatabaseManager.getCollection(uri, user, password);
if (base == null) {
final String msg = "Collection " + uri + " could not be found.";
if (failonerror) {
throw new BuildException(msg);
} else {
log(msg, Project.MSG_ERR);
}
} else {
final XPathQueryService service = (XPathQueryService) base.getService("XPathQueryService", "1.0");
// set pretty-printing on
service.setProperty(OutputKeys.INDENT, "yes");
service.setProperty(OutputKeys.ENCODING, "UTF-8");
if (namespace != null) {
log("Using namespace: " + namespace, Project.MSG_DEBUG);
service.setNamespace("ns", namespace);
}
final ResourceSet results;
if (resource != null) {
log("Query resource: " + resource, Project.MSG_DEBUG);
results = service.queryResource(resource, query);
} else {
log("Query collection", Project.MSG_DEBUG);
results = service.query(query);
}
log("Found " + results.getSize() + " results", Project.MSG_INFO);
if ((destDir != null) && (results != null)) {
log("write results to directory " + destDir.getAbsolutePath(), Project.MSG_INFO);
final ResourceIterator iter = results.getIterator();
log("Writing results to directory " + destDir.getAbsolutePath(), Project.MSG_DEBUG);
while (iter.hasMoreResources()) {
final XMLResource res = (XMLResource) iter.nextResource();
log("Writing resource " + res.getId(), Project.MSG_DEBUG);
writeResource(res, destDir);
}
} else if (outputproperty != null) {
if (count) {
getProject().setNewProperty(outputproperty, String.valueOf(results.getSize()));
} else {
final ResourceIterator iter = results.getIterator();
final StringBuilder result = new StringBuilder();
while (iter.hasMoreResources()) {
final XMLResource res = (XMLResource) iter.nextResource();
result.append(res.getContent().toString());
result.append("\n");
}
getProject().setNewProperty(outputproperty, result.toString());
}
}
}
} catch (final XMLDBException e) {
final String msg = "XMLDB exception caught while executing query: " + e.getMessage();
if (failonerror) {
throw new BuildException(msg, e);
} else {
log(msg, e, Project.MSG_ERR);
}
} catch (final IOException e) {
final String msg = "XMLDB exception caught while writing destination file: " + e.getMessage();
if (failonerror) {
throw new BuildException(msg, e);
} else {
log(msg, e, Project.MSG_ERR);
}
}
}
use of org.xmldb.api.base.ResourceIterator in project exist by eXist-db.
the class ValueIndexTest method indexScan.
@Test
public void indexScan() throws XMLDBException, URISyntaxException {
configureCollection(CONFIG_PATH);
String queryBody = "declare namespace f=\'http://exist-db.org/xquery/test\';\n" + "declare namespace mods='http://www.loc.gov/mods/v3';\n" + "import module namespace u=\'http://exist-db.org/xquery/util\';\n" + "\n" + "declare function f:term-callback($term as item(), $data as xs:int+)\n" + "as element()+ {\n" + " <item>\n" + " <term>{$term}</term>\n" + " <frequency>{$data[1]}</frequency>\n" + " </item>\n" + "};\n" + "\n";
XPathQueryService service = storeXMLFileAndGetQueryService(ITEMS_FILENAME, ITEMS_FILE);
String query = queryBody + "u:index-keys(//item/name, \'\', util:function(xs:QName(\'f:term-callback\'), 2), 1000)";
ResourceSet result = service.query(query);
for (ResourceIterator i = result.getIterator(); i.hasMoreResources(); ) {
i.nextResource().getContent();
}
assertEquals(7, result.getSize());
query = queryBody + "u:index-keys(//item/stock, 0, util:function(xs:QName(\'f:term-callback\'), 2), 1000)";
result = service.query(query);
for (ResourceIterator i = result.getIterator(); i.hasMoreResources(); ) {
i.nextResource().getContent();
}
assertEquals(5, result.getSize());
}
use of org.xmldb.api.base.ResourceIterator in project exist by eXist-db.
the class XPathUtil method javaObjectToXPath.
public static final Sequence javaObjectToXPath(Object obj, XQueryContext context, boolean expandChars) throws XPathException {
if (obj == null) {
// return Sequence.EMPTY_SEQUENCE;
return null;
} else if (obj instanceof Sequence) {
return (Sequence) obj;
} else if (obj instanceof String) {
final StringValue v = new StringValue((String) obj);
return (expandChars ? v.expand() : v);
} else if (obj instanceof Boolean) {
return BooleanValue.valueOf(((Boolean) obj));
} else if (obj instanceof Float) {
return new FloatValue(((Float) obj));
} else if (obj instanceof Double) {
return new DoubleValue(((Double) obj));
} else if (obj instanceof Short) {
return new IntegerValue(((Short) obj), Type.SHORT);
} else if (obj instanceof Integer) {
return new IntegerValue(((Integer) obj), Type.INT);
} else if (obj instanceof Long) {
return new IntegerValue(((Long) obj), Type.LONG);
} else if (obj instanceof byte[]) {
return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), new UnsynchronizedByteArrayInputStream((byte[]) obj));
} else if (obj instanceof ResourceSet) {
final Sequence seq = new AVLTreeNodeSet();
try {
final DBBroker broker = context.getBroker();
for (final ResourceIterator it = ((ResourceSet) obj).getIterator(); it.hasMoreResources(); ) {
seq.add(getNode(broker, (XMLResource) it.nextResource()));
}
} catch (final XMLDBException xe) {
throw new XPathException("Failed to convert ResourceSet to node: " + xe.getMessage());
}
return seq;
} else if (obj instanceof XMLResource) {
return getNode(context.getBroker(), (XMLResource) obj);
} else if (obj instanceof Node) {
context.pushDocumentContext();
final DOMStreamer streamer = (DOMStreamer) SerializerPool.getInstance().borrowObject(DOMStreamer.class);
try {
final MemTreeBuilder builder = context.getDocumentBuilder();
builder.startDocument();
final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
streamer.setContentHandler(receiver);
streamer.serialize((Node) obj, false);
if (obj instanceof Document) {
return builder.getDocument();
} else {
return builder.getDocument().getNode(1);
}
} catch (final SAXException e) {
throw new XPathException("Failed to transform node into internal model: " + e.getMessage());
} finally {
context.popDocumentContext();
SerializerPool.getInstance().returnObject(streamer);
}
} else if (obj instanceof List<?>) {
boolean createNodeSequence = true;
for (Object next : ((List<?>) obj)) {
if (!(next instanceof NodeProxy)) {
createNodeSequence = false;
break;
}
}
Sequence seq = createNodeSequence ? new AVLTreeNodeSet() : new ValueSequence();
for (Object o : ((List<?>) obj)) {
seq.add((Item) javaObjectToXPath(o, context, expandChars));
}
return seq;
} else if (obj instanceof NodeList) {
context.pushDocumentContext();
final DOMStreamer streamer = (DOMStreamer) SerializerPool.getInstance().borrowObject(DOMStreamer.class);
try {
final MemTreeBuilder builder = context.getDocumentBuilder();
builder.startDocument();
final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
streamer.setContentHandler(receiver);
final ValueSequence seq = new ValueSequence();
final NodeList nl = (NodeList) obj;
int last = builder.getDocument().getLastNode();
for (int i = 0; i < nl.getLength(); i++) {
final Node n = nl.item(i);
streamer.serialize(n, false);
final NodeImpl created = builder.getDocument().getNode(last + 1);
seq.add(created);
last = builder.getDocument().getLastNode();
}
return seq;
} catch (final SAXException e) {
throw new XPathException("Failed to transform node into internal model: " + e.getMessage());
} finally {
context.popDocumentContext();
SerializerPool.getInstance().returnObject(streamer);
}
} else if (obj instanceof Object[]) {
boolean createNodeSequence = true;
final Object[] array = (Object[]) obj;
for (Object arrayItem : array) {
if (!(arrayItem instanceof NodeProxy)) {
createNodeSequence = false;
break;
}
}
Sequence seq = createNodeSequence ? new AVLTreeNodeSet() : new ValueSequence();
for (Object arrayItem : array) {
seq.add((Item) javaObjectToXPath(arrayItem, context, expandChars));
}
return seq;
} else {
return new JavaObjectValue(obj);
}
}
use of org.xmldb.api.base.ResourceIterator in project exist by eXist-db.
the class TestDataGenerator method generate.
public Path[] generate(final org.xmldb.api.base.Collection collection, final String xqueryContent) throws SAXException {
final String query = IMPORT + xqueryContent;
try {
final XQueryService service = (XQueryService) collection.getService("XQueryService", "1.0");
service.declareVariable("filename", "");
service.declareVariable("count", "0");
final CompiledExpression compiled = service.compile(query);
for (int i = 0; i < count; i++) {
generatedFiles[i] = Files.createTempFile(prefix, ".xml");
service.declareVariable("filename", generatedFiles[i].getFileName().toString());
service.declareVariable("count", new Integer(i));
final ResourceSet result = service.execute(compiled);
try (final Writer out = Files.newBufferedWriter(generatedFiles[i], StandardCharsets.UTF_8)) {
final SAXSerializer sax = new SAXSerializer(out, outputProps);
for (ResourceIterator iter = result.getIterator(); iter.hasMoreResources(); ) {
XMLResource r = (XMLResource) iter.nextResource();
r.getContentAsSAX(sax);
}
}
}
} catch (final XMLDBException | IOException e) {
LOG.error(e.getMessage(), e);
throw new SAXException(e.getMessage(), e);
}
return generatedFiles;
}
use of org.xmldb.api.base.ResourceIterator in project exist by eXist-db.
the class ResourceTest method queryRemoveResource.
@Test
public void queryRemoveResource() throws XMLDBException {
Resource resource = null;
Collection testCollection = DatabaseManager.getCollection(XmldbURI.LOCAL_DB + "/" + TEST_COLLECTION);
assertNotNull(testCollection);
String resourceName = "QueryTestPerson.xml";
String id = "test." + System.currentTimeMillis();
String content = "<?xml version='1.0'?><person id=\"" + id + "\"><name>Jason</name></person>";
resource = testCollection.createResource(resourceName, "XMLResource");
resource.setContent(content);
testCollection.storeResource(resource);
XPathQueryService service = (XPathQueryService) testCollection.getService("XPathQueryService", "1.0");
ResourceSet rs = service.query("/person[@id='" + id + "']");
for (ResourceIterator iterator = rs.getIterator(); iterator.hasMoreResources(); ) {
Resource r = iterator.nextResource();
testCollection.removeResource(r);
resource = null;
}
}
Aggregations