Search in sources :

Example 16 with StringSource

use of org.exist.source.StringSource in project exist by eXist-db.

the class ImportModuleTest method variablesCompositeFromMultipleLocationHints.

/**
 * Imports multiple XQuery Library Modules containing variables into the same target namespace.
 */
@Test
public void variablesCompositeFromMultipleLocationHints() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException, XPathException {
    final String module1 = "xquery version \"1.0\";\n" + "module namespace impl = \"http://example.com/impl\";\n" + "declare variable $impl:v1 := \"impl1\";\n";
    final String module2 = "xquery version \"1.0\";\n" + "module namespace impl = \"http://example.com/impl\";\n" + "declare variable $impl:v2 := \"impl2\";\n";
    final String module3 = "xquery version \"1.0\";\n" + "module namespace impl = \"http://example.com/impl\";\n" + "declare variable $impl:v3 := \"impl3\";\n";
    final String query = "import module namespace impl = \"http://example.com/impl\"" + "        at \"xmldb:exist:///db/impl1.xqm\", \"xmldb:exist:///db/impl2.xqm\", \"xmldb:exist:///db/impl3.xqm\";\n" + "<result>\n" + "    <impl1>{$impl:v1}</impl1>" + "    <impl2>{$impl:v2}</impl2>" + "    <impl3>{$impl:v3}</impl3>" + "</result>\n";
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    final Source source = new StringSource(query);
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        // store modules
        storeModules(broker, transaction, "/db", Tuple("impl1.xqm", module1), Tuple("impl2.xqm", module2), Tuple("impl3.xqm", module3));
        // execute query
        final Tuple2<XQueryContext, Sequence> contextAndResult = withCompiledQuery(broker, source, compiledXQuery -> {
            final Sequence result = executeQuery(broker, compiledXQuery);
            return Tuple(compiledXQuery.getContext(), result);
        });
        // check that the result was correct
        assertNotNull(contextAndResult._2);
        assertEquals(1, contextAndResult._2.getItemCount());
        final Element doc = (Element) contextAndResult._2.itemAt(0);
        assertNotNull(doc);
        final javax.xml.transform.Source actual = Input.fromDocument(doc.getOwnerDocument()).build();
        final javax.xml.transform.Source expected = Input.fromString("<result>" + "<impl1>impl1</impl1>" + "<impl2>impl2</impl2>" + "<impl3>impl3</impl3>" + "</result>").build();
        final Diff diff = DiffBuilder.compare(expected).withTest(actual).checkForSimilar().build();
        assertFalse(diff.toString(), diff.hasDifferences());
        transaction.commit();
    }
}
Also used : Diff(org.xmlunit.diff.Diff) Element(org.w3c.dom.Element) Txn(org.exist.storage.txn.Txn) Sequence(org.exist.xquery.value.Sequence) StringSource(org.exist.source.StringSource) StringInputSource(org.exist.util.StringInputSource) Source(org.exist.source.Source) DBBroker(org.exist.storage.DBBroker) StringSource(org.exist.source.StringSource) BrokerPool(org.exist.storage.BrokerPool) Test(org.junit.Test)

Example 17 with StringSource

use of org.exist.source.StringSource in project exist by eXist-db.

the class ImportModuleTest method prefixSameAsOtherImport.

/**
 * Checks that XQST0033 is raised if the prefix part of an `import module` statement is the same as the prefix
 * of another `import module` statement within the same module.
 */
@Test
public void prefixSameAsOtherImport() throws EXistException, IOException, SAXException, PermissionDeniedException, LockException {
    final String module1 = "xquery version \"1.0\";\n" + "module namespace impl = \"http://example.com/impl\";\n" + "declare function impl:f1($a as xs:string) as xs:string {\n" + "    $a\n" + "};\n";
    final String module2 = "xquery version \"1.0\";\n" + "module namespace impl = \"http://example.com/impl\";\n" + "declare function impl:f1($a as xs:string, $b as xs:string) as xs:string {\n" + "    fn:concat($a, ' ', $b)\n" + "};\n";
    final String query = "import module namespace impl = \"http://example.com/impl\" at \"xmldb:exist:///db/impl1.xqm\";\n" + "import module namespace impl = \"http://example.com/impl\" at \"xmldb:exist:///db/impl2.xqm\";\n" + "<result>\n" + "    <impl1>{impl:f1(\"to impl1\")}</impl1>" + "    <impl2>{impl:f1(\"to\", \"impl1\")}</impl2>" + "</result>\n";
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    final Source source = new StringSource(query);
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        // store modules
        storeModules(broker, transaction, "/db", Tuple("impl1.xqm", module1), Tuple("impl2.xqm", module2));
        // execute query
        try {
            final Tuple2<XQueryContext, Sequence> contextAndResult = withCompiledQuery(broker, source, compiledXQuery -> {
                final Sequence result = executeQuery(broker, compiledXQuery);
                return Tuple(compiledXQuery.getContext(), result);
            });
            transaction.commit();
            fail("expected XQST0033");
        } catch (final XPathException e) {
            transaction.commit();
            assertEquals(ErrorCodes.XQST0033, e.getErrorCode());
        }
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) StringSource(org.exist.source.StringSource) Txn(org.exist.storage.txn.Txn) Sequence(org.exist.xquery.value.Sequence) BrokerPool(org.exist.storage.BrokerPool) StringSource(org.exist.source.StringSource) StringInputSource(org.exist.util.StringInputSource) Source(org.exist.source.Source) Test(org.junit.Test)

Example 18 with StringSource

use of org.exist.source.StringSource in project exist by eXist-db.

the class ImportModuleTest method variablesBetweenModules.

@Test
public void variablesBetweenModules() throws EXistException, PermissionDeniedException, IOException, LockException, SAXException, XPathException {
    final String module1 = "xquery version \"1.0\";\n" + "module namespace mod1 = \"http://example.com/mod1\";\n" + "declare variable $mod1:var1 := \"mod1 var1\";\n" + "declare function mod1:test() {\n" + "    <function name=\"mod1:test\">\n" + "        <variable name=\"mod1:var1\">{$mod1:var1}</variable>\n" + "    </function>\n" + "};";
    final String module2 = "xquery version \"1.0\";\n" + "module namespace mod2 = \"http://example.com/mod2\";\n" + "declare variable $mod2:var1 := \"mod2 var1\";\n" + "import module namespace mod1 = \"http://example.com/mod1\" at \"xmldb:exist:///db/mod1.xqm\";\n" + "declare function mod2:test() {\n" + "    <function name=\"mod2:test\">\n" + "        <variable name=\"mod2:var1\">{$mod2:var1}</variable>\n" + "        { mod1:test() }\n" + "        <variable name=\"mod1:var1\">{$mod1:var1}</variable>\n" + "    </function>\n" + "};";
    final String query = "xquery version \"1.0\";\n" + " import module namespace mod2 = 'http://example.com/mod2' at 'xmldb:exist:///db/mod2.xqm';\n" + "<result>\n" + "    {mod2:test()}\n" + "</result>\n";
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    final Source source = new StringSource(query);
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        // store modules
        storeModules(broker, transaction, "/db", Tuple("mod1.xqm", module1), Tuple("mod2.xqm", module2));
        // execute query
        final Tuple2<XQueryContext, Sequence> contextAndResult = withCompiledQuery(broker, source, compiledXQuery -> {
            final Sequence result = executeQuery(broker, compiledXQuery);
            return Tuple(compiledXQuery.getContext(), result);
        });
        // check that the result was correct
        assertNotNull(contextAndResult._2);
        assertEquals(1, contextAndResult._2.getItemCount());
        final Element doc = (Element) contextAndResult._2.itemAt(0);
        assertNotNull(doc);
        final javax.xml.transform.Source actual = Input.fromDocument(doc.getOwnerDocument()).build();
        final javax.xml.transform.Source expected = Input.fromString("<result>" + "<function name=\"mod2:test\">" + "<variable name=\"mod2:var1\">mod2 var1</variable>" + "<function name=\"mod1:test\">" + "<variable name=\"mod1:var1\">mod1 var1</variable>" + "</function>" + "<variable name=\"mod1:var1\">mod1 var1</variable>" + "</function>" + "</result>").build();
        final Diff diff = DiffBuilder.compare(expected).withTest(actual).checkForSimilar().build();
        assertFalse(diff.toString(), diff.hasDifferences());
        transaction.commit();
    }
}
Also used : Diff(org.xmlunit.diff.Diff) Element(org.w3c.dom.Element) Txn(org.exist.storage.txn.Txn) Sequence(org.exist.xquery.value.Sequence) StringSource(org.exist.source.StringSource) StringInputSource(org.exist.util.StringInputSource) Source(org.exist.source.Source) DBBroker(org.exist.storage.DBBroker) StringSource(org.exist.source.StringSource) BrokerPool(org.exist.storage.BrokerPool) Test(org.junit.Test)

Example 19 with StringSource

use of org.exist.source.StringSource in project exist by eXist-db.

the class InternalModuleTest method requestResponseSessionVariables_4_x_x_Api.

/**
 * The $request:request, $session:session, and
 * $response:response variables were removed in eXist-db 5.0.0.
 */
@Test
public void requestResponseSessionVariables_4_x_x_Api() throws XMLDBException {
    final Source querySource = new StringSource("document{" + EOL + "  <vars>" + EOL + "    <request>{empty($request:request)}</request>" + EOL + "    <session>{empty($session:session)}</session>" + EOL + "    <response>{empty($response:response)}</response>" + EOL + "  </vars>" + EOL + "}");
    final EXistXQueryService queryService = (EXistXQueryService) existServer.getRoot().getService("XQueryService", "1.0");
    try {
        requestResponseSessionVariablesQuery_4_x_X_Api(queryService, querySource);
        fail("Expected XQuery error XPST0008");
    } catch (final XMLDBException e) {
        assertTrue(e.getCause() instanceof XPathException);
        final XPathException xpe = (XPathException) e.getCause();
        // TODO(AR) should be XPST0008, eXist-db has a bug with the error code, see: https://github.com/eXist-db/exist/issues/2060
        assertEquals(ErrorCodes.XPDY0002, xpe.getErrorCode());
    }
}
Also used : EXistXQueryService(org.exist.xmldb.EXistXQueryService) XMLDBException(org.xmldb.api.base.XMLDBException) StringSource(org.exist.source.StringSource) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) Test(org.junit.Test)

Example 20 with StringSource

use of org.exist.source.StringSource in project exist by eXist-db.

the class XQDocTask method execute.

@Override
public void execute() throws BuildException {
    registerDatabase();
    try {
        int p = uri.indexOf(XmldbURI.ROOT_COLLECTION);
        if (p == Constants.STRING_NOT_FOUND)
            throw new BuildException("invalid uri: '" + uri + "'");
        String baseURI = uri.substring(0, p);
        String path;
        if (p == uri.length() - 3)
            path = "";
        else
            path = uri.substring(p + 3);
        Collection root = null;
        if (createCollection) {
            root = DatabaseManager.getCollection(baseURI + XmldbURI.ROOT_COLLECTION, user, password);
            root = mkcol(root, baseURI, XmldbURI.ROOT_COLLECTION, path);
        } else
            root = DatabaseManager.getCollection(uri, user, password);
        EXistXQueryService service = (EXistXQueryService) root.getService("XQueryService", "1.0");
        Source source = new StringSource(XQUERY);
        service.declareVariable("collection", root.getName());
        service.declareVariable("uri", "");
        if (moduleURI != null) {
            service.declareVariable("uri", moduleURI);
            service.declareVariable("data", "");
            service.execute(source);
        } else {
            for (FileSet fileSet : fileSets) {
                DirectoryScanner scanner = fileSet.getDirectoryScanner(getProject());
                scanner.scan();
                String[] files = scanner.getIncludedFiles();
                log("Found " + files.length + " files to upload.\n");
                Path baseDir = scanner.getBasedir().toPath();
                for (String s : files) {
                    Path file = baseDir.resolve(s);
                    log("Storing " + s + " ...\n");
                    byte[] data = read(file);
                    try {
                        service.declareVariable("name", FileUtils.fileName(file));
                        service.declareVariable("data", data);
                        service.execute(source);
                    } catch (XMLDBException e) {
                        String msg = "XMLDB exception caught: " + e.getMessage();
                        if (failonerror)
                            throw new BuildException(msg, e);
                        else
                            log(msg, e, Project.MSG_ERR);
                    }
                }
            }
        }
    } catch (XMLDBException e) {
        String msg = "XMLDB exception caught: " + e.getMessage();
        if (failonerror)
            throw new BuildException(msg, e);
        else
            log(msg, e, Project.MSG_ERR);
    }
}
Also used : Path(java.nio.file.Path) FileSet(org.apache.tools.ant.types.FileSet) XMLDBException(org.xmldb.api.base.XMLDBException) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) EXistXQueryService(org.exist.xmldb.EXistXQueryService) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) Collection(org.xmldb.api.base.Collection) BuildException(org.apache.tools.ant.BuildException) StringSource(org.exist.source.StringSource)

Aggregations

StringSource (org.exist.source.StringSource)59 Source (org.exist.source.Source)53 Txn (org.exist.storage.txn.Txn)41 BrokerPool (org.exist.storage.BrokerPool)40 DBBroker (org.exist.storage.DBBroker)40 Sequence (org.exist.xquery.value.Sequence)40 Test (org.junit.Test)37 StringInputSource (org.exist.util.StringInputSource)32 Collection (org.exist.collections.Collection)8 DBSource (org.exist.source.DBSource)8 IOException (java.io.IOException)7 Map (java.util.Map)7 EXistException (org.exist.EXistException)7 XmldbURI (org.exist.xmldb.XmldbURI)7 Element (org.w3c.dom.Element)7 InputSource (org.xml.sax.InputSource)7 Diff (org.xmlunit.diff.Diff)7 XQueryPool (org.exist.storage.XQueryPool)6 XQueryContext (org.exist.xquery.XQueryContext)6 IntegerValue (org.exist.xquery.value.IntegerValue)6