Search in sources :

Example 1 with ResourceIterator

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);
        }
    }
}
Also used : XPathQueryService(org.xmldb.api.modules.XPathQueryService) Collection(org.xmldb.api.base.Collection) XMLDBException(org.xmldb.api.base.XMLDBException) PropertyHelper(org.apache.tools.ant.PropertyHelper) BuildException(org.apache.tools.ant.BuildException) ResourceSet(org.xmldb.api.base.ResourceSet) IOException(java.io.IOException) ResourceIterator(org.xmldb.api.base.ResourceIterator) XMLResource(org.xmldb.api.modules.XMLResource)

Example 2 with ResourceIterator

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());
}
Also used : XPathQueryService(org.xmldb.api.modules.XPathQueryService) ResourceSet(org.xmldb.api.base.ResourceSet) ResourceIterator(org.xmldb.api.base.ResourceIterator) Test(org.junit.Test)

Example 3 with ResourceIterator

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);
    }
}
Also used : Node(org.w3c.dom.Node) XMLDBException(org.xmldb.api.base.XMLDBException) Document(org.w3c.dom.Document) NodeProxy(org.exist.dom.persistent.NodeProxy) SAXException(org.xml.sax.SAXException) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) NodeList(org.w3c.dom.NodeList) List(java.util.List) NodeImpl(org.exist.dom.memtree.NodeImpl) NodeList(org.w3c.dom.NodeList) ResourceSet(org.xmldb.api.base.ResourceSet) AVLTreeNodeSet(org.exist.dom.persistent.AVLTreeNodeSet) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) RemoteXMLResource(org.exist.xmldb.RemoteXMLResource) XMLResource(org.xmldb.api.modules.XMLResource) LocalXMLResource(org.exist.xmldb.LocalXMLResource) DBBroker(org.exist.storage.DBBroker) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) DOMStreamer(org.exist.util.serializer.DOMStreamer) ResourceIterator(org.xmldb.api.base.ResourceIterator)

Example 4 with ResourceIterator

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;
}
Also used : XQueryService(org.xmldb.api.modules.XQueryService) XMLDBException(org.xmldb.api.base.XMLDBException) ResourceSet(org.xmldb.api.base.ResourceSet) CompiledExpression(org.xmldb.api.base.CompiledExpression) XMLResource(org.xmldb.api.modules.XMLResource) SAXException(org.xml.sax.SAXException) SAXSerializer(org.exist.util.serializer.SAXSerializer) ResourceIterator(org.xmldb.api.base.ResourceIterator)

Example 5 with ResourceIterator

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;
    }
}
Also used : XPathQueryService(org.xmldb.api.modules.XPathQueryService) BinaryResource(org.xmldb.api.modules.BinaryResource) XMLResource(org.xmldb.api.modules.XMLResource) Resource(org.xmldb.api.base.Resource) Collection(org.xmldb.api.base.Collection) ResourceSet(org.xmldb.api.base.ResourceSet) ResourceIterator(org.xmldb.api.base.ResourceIterator)

Aggregations

ResourceIterator (org.xmldb.api.base.ResourceIterator)7 ResourceSet (org.xmldb.api.base.ResourceSet)7 XMLResource (org.xmldb.api.modules.XMLResource)6 Test (org.junit.Test)3 XMLDBException (org.xmldb.api.base.XMLDBException)3 XPathQueryService (org.xmldb.api.modules.XPathQueryService)3 Node (org.w3c.dom.Node)2 SAXException (org.xml.sax.SAXException)2 Collection (org.xmldb.api.base.Collection)2 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 List (java.util.List)1 UnsynchronizedByteArrayInputStream (org.apache.commons.io.input.UnsynchronizedByteArrayInputStream)1 BuildException (org.apache.tools.ant.BuildException)1 PropertyHelper (org.apache.tools.ant.PropertyHelper)1 DocumentBuilderReceiver (org.exist.dom.memtree.DocumentBuilderReceiver)1 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)1 NodeImpl (org.exist.dom.memtree.NodeImpl)1 AVLTreeNodeSet (org.exist.dom.persistent.AVLTreeNodeSet)1 NodeProxy (org.exist.dom.persistent.NodeProxy)1