Search in sources :

Example 31 with Source

use of org.exist.source.Source 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 32 with Source

use of org.exist.source.Source 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 33 with Source

use of org.exist.source.Source 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)

Example 34 with Source

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

the class XMLTestRunner method run.

@Override
public void run(final RunNotifier notifier) {
    try {
        final String pkgName = getClass().getPackage().getName().replace('.', '/');
        final Source query = new ClassLoaderSource(pkgName + "/xml-test-runner.xq");
        final List<java.util.function.Function<XQueryContext, Tuple2<String, Object>>> externalVariableDeclarations = Arrays.asList(context -> new Tuple2<>("doc", doc), context -> new Tuple2<>("id", Sequence.EMPTY_SEQUENCE), // set callback functions for notifying junit!
        context -> new Tuple2<>("test-ignored-function", new FunctionReference(new FunctionCall(context, new ExtTestIgnoredFunction(context, getSuiteName(), notifier)))), context -> new Tuple2<>("test-started-function", new FunctionReference(new FunctionCall(context, new ExtTestStartedFunction(context, getSuiteName(), notifier)))), context -> new Tuple2<>("test-failure-function", new FunctionReference(new FunctionCall(context, new ExtTestFailureFunction(context, getSuiteName(), notifier)))), context -> new Tuple2<>("test-assumption-failed-function", new FunctionReference(new FunctionCall(context, new ExtTestAssumptionFailedFunction(context, getSuiteName(), notifier)))), context -> new Tuple2<>("test-error-function", new FunctionReference(new FunctionCall(context, new ExtTestErrorFunction(context, getSuiteName(), notifier)))), context -> new Tuple2<>("test-finished-function", new FunctionReference(new FunctionCall(context, new ExtTestFinishedFunction(context, getSuiteName(), notifier)))));
        // NOTE: at this stage EXIST_EMBEDDED_SERVER_CLASS_INSTANCE in XSuite will be usable
        final BrokerPool brokerPool = XSuite.EXIST_EMBEDDED_SERVER_CLASS_INSTANCE.getBrokerPool();
        executeQuery(brokerPool, query, externalVariableDeclarations);
    } catch (final DatabaseConfigurationException | IOException | EXistException | PermissionDeniedException | XPathException e) {
        // TODO(AR) what to do here?
        throw new RuntimeException(e);
    }
}
Also used : ClassLoaderSource(org.exist.source.ClassLoaderSource) XPathException(org.exist.xquery.XPathException) IOException(java.io.IOException) EXistException(org.exist.EXistException) ClassLoaderSource(org.exist.source.ClassLoaderSource) Source(org.exist.source.Source) InputSource(org.xml.sax.InputSource) DatabaseConfigurationException(org.exist.util.DatabaseConfigurationException) FunctionReference(org.exist.xquery.value.FunctionReference) PermissionDeniedException(org.exist.security.PermissionDeniedException) FunctionCall(org.exist.xquery.FunctionCall) BrokerPool(org.exist.storage.BrokerPool)

Example 35 with Source

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

the class XQueryTestRunner method run.

@Override
public void run(final RunNotifier notifier) {
    try {
        final String pkgName = getClass().getPackage().getName().replace('.', '/');
        final Source query = new ClassLoaderSource(pkgName + "/xquery-test-runner.xq");
        final URI testModuleUri = path.toAbsolutePath().toUri();
        final String suiteName = getSuiteName();
        final List<java.util.function.Function<XQueryContext, Tuple2<String, Object>>> externalVariableDeclarations = Arrays.asList(context -> new Tuple2<>("test-module-uri", new AnyURIValue(testModuleUri)), // set callback functions for notifying junit!
        context -> new Tuple2<>("test-ignored-function", new FunctionReference(new FunctionCall(context, new ExtTestIgnoredFunction(context, suiteName, notifier)))), context -> new Tuple2<>("test-started-function", new FunctionReference(new FunctionCall(context, new ExtTestStartedFunction(context, suiteName, notifier)))), context -> new Tuple2<>("test-failure-function", new FunctionReference(new FunctionCall(context, new ExtTestFailureFunction(context, suiteName, notifier)))), context -> new Tuple2<>("test-assumption-failed-function", new FunctionReference(new FunctionCall(context, new ExtTestAssumptionFailedFunction(context, suiteName, notifier)))), context -> new Tuple2<>("test-error-function", new FunctionReference(new FunctionCall(context, new ExtTestErrorFunction(context, suiteName, notifier)))), context -> new Tuple2<>("test-finished-function", new FunctionReference(new FunctionCall(context, new ExtTestFinishedFunction(context, suiteName, notifier)))));
        // NOTE: at this stage EXIST_EMBEDDED_SERVER_CLASS_INSTANCE in XSuite will be usable
        final BrokerPool brokerPool = XSuite.EXIST_EMBEDDED_SERVER_CLASS_INSTANCE.getBrokerPool();
        executeQuery(brokerPool, query, externalVariableDeclarations);
    } catch (final DatabaseConfigurationException | IOException | EXistException | PermissionDeniedException | XPathException e) {
        // TODO(AR) what to do here?
        throw new RuntimeException(e);
    }
}
Also used : URI(java.net.URI) ClassLoaderSource(org.exist.source.ClassLoaderSource) Source(org.exist.source.Source) FileSource(org.exist.source.FileSource) DatabaseConfigurationException(org.exist.util.DatabaseConfigurationException) FunctionReference(org.exist.xquery.value.FunctionReference) ClassLoaderSource(org.exist.source.ClassLoaderSource) AnyURIValue(org.exist.xquery.value.AnyURIValue) IOException(java.io.IOException) EXistException(org.exist.EXistException) java.util(java.util) PermissionDeniedException(org.exist.security.PermissionDeniedException) BrokerPool(org.exist.storage.BrokerPool)

Aggregations

Source (org.exist.source.Source)83 StringSource (org.exist.source.StringSource)62 Sequence (org.exist.xquery.value.Sequence)43 BrokerPool (org.exist.storage.BrokerPool)42 DBBroker (org.exist.storage.DBBroker)42 Txn (org.exist.storage.txn.Txn)40 Test (org.junit.Test)35 StringInputSource (org.exist.util.StringInputSource)32 DBSource (org.exist.source.DBSource)23 IOException (java.io.IOException)19 PermissionDeniedException (org.exist.security.PermissionDeniedException)19 InputSource (org.xml.sax.InputSource)15 EXistException (org.exist.EXistException)12 XmldbURI (org.exist.xmldb.XmldbURI)11 XQueryPool (org.exist.storage.XQueryPool)9 XQueryContext (org.exist.xquery.XQueryContext)9 FileSource (org.exist.source.FileSource)8 CompiledXQuery (org.exist.xquery.CompiledXQuery)8 XQuery (org.exist.xquery.XQuery)8 Collection (org.exist.collections.Collection)7