Search in sources :

Example 71 with Source

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

the class ImportModuleTest method variableSameAsImportingModule.

/**
 * Checks that XQST0049 is raised if an imported module and the importing module contain a variable of the same name.
 */
@Test
public void variableSameAsImportingModule() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException {
    final String module = "xquery version \"1.0\";\n" + "module namespace impl = \"http://example.com/impl\";\n" + "declare variable $impl:f1 := \"impl1\";\n";
    final String query = "import module namespace impl = \"http://example.com/impl\"" + "        at \"xmldb:exist:///db/impl1.xqm\";\n" + "declare variable $impl:f1 := \"this\";\n" + "<result>\n" + "    <impl1>{$impl:f1}</impl1>" + "</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 module
        storeModules(broker, transaction, "/db", Tuple("impl1.xqm", module));
        // 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 XQST0049");
        } catch (final XPathException e) {
            transaction.commit();
            assertEquals(ErrorCodes.XQST0049, 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 72 with Source

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

the class ImportModuleTest method functionsCompositeFromMultipleLocationHintsWithDifferingPrefixes.

/**
 * Imports multiple XQuery Library Modules containing functions into the same target namespace.
 */
@Test
public void functionsCompositeFromMultipleLocationHintsWithDifferingPrefixes() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException, XPathException {
    final String module1 = "xquery version \"1.0\";\n" + "module namespace impl1 = \"http://example.com/impl\";\n" + "declare function impl1:f1($a as xs:string) as xs:string {\n" + "    $a\n" + "};\n";
    final String module2 = "xquery version \"1.0\";\n" + "module namespace impl2 = \"http://example.com/impl\";\n" + "declare function impl2:f1($a as xs:string, $b as xs:string) as xs:string {\n" + "    fn:concat($a, ' ', $b)\n" + "};\n";
    final String module3 = "xquery version \"1.0\";\n" + "module namespace impl3 = \"http://example.com/impl\";\n" + "declare function impl3:f2($a as xs:string) as xs:string {\n" + "    $a\n" + "};\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:f1(\"to impl1\")}</impl1>" + "    <impl2>{impl:f1(\"to\", \"impl2\")}</impl2>" + "    <impl3>{impl:f2(\"to impl3\")}</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>to impl1</impl1>" + "<impl2>to impl2</impl2>" + "<impl3>to 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 73 with Source

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

the class EmbeddedBinariesTest method executeXQuery.

@Override
protected QueryResultAccessor<Sequence, IOException> executeXQuery(final String query) throws Exception {
    final Source source = new StringSource(query);
    final BrokerPool brokerPool = existEmbeddedServer.getBrokerPool();
    final XQueryPool pool = brokerPool.getXQueryPool();
    final XQuery xquery = brokerPool.getXQueryService();
    try (final DBBroker broker = brokerPool.get(Optional.of(brokerPool.getSecurityManager().getSystemSubject()))) {
        final CompiledXQuery existingCompiled = pool.borrowCompiledXQuery(broker, source);
        final XQueryContext context;
        final CompiledXQuery compiled;
        if (existingCompiled == null) {
            context = new XQueryContext(brokerPool);
            compiled = xquery.compile(context, source);
        } else {
            context = existingCompiled.getContext();
            context.prepareForReuse();
            compiled = existingCompiled;
        }
        final Sequence results = xquery.execute(broker, compiled, null);
        return consumer2E -> {
            try {
                // context.runCleanupTasks();  //TODO(AR) shows the ordering issue with binary values (see comment below)
                consumer2E.accept(results);
            } finally {
                // TODO(AR) performing #runCleanupTasks causes the stream to be closed, so if we do so before we are finished with the results, serialization fails.
                context.runCleanupTasks();
                pool.returnCompiledXQuery(source, compiled);
            }
        };
    }
}
Also used : XQueryPool(org.exist.storage.XQueryPool) Txn(org.exist.storage.txn.Txn) BrokerPool(org.exist.storage.BrokerPool) StringSource(org.exist.source.StringSource) ManagedCollectionLock(org.exist.storage.lock.ManagedCollectionLock) StringInputSource(org.exist.util.StringInputSource) org.exist.xquery.value(org.exist.xquery.value) IOException(java.io.IOException) ExistEmbeddedServer(org.exist.test.ExistEmbeddedServer) MimeType(org.exist.util.MimeType) Source(org.exist.source.Source) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) DBBroker(org.exist.storage.DBBroker) Collection(org.exist.collections.Collection) XmldbURI(org.exist.xmldb.XmldbURI) Optional(java.util.Optional) XQueryPool(org.exist.storage.XQueryPool) Lock(org.exist.storage.lock.Lock) ClassRule(org.junit.ClassRule) DBBroker(org.exist.storage.DBBroker) StringSource(org.exist.source.StringSource) StringSource(org.exist.source.StringSource) StringInputSource(org.exist.util.StringInputSource) Source(org.exist.source.Source) BrokerPool(org.exist.storage.BrokerPool)

Example 74 with Source

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

the class InternalModuleTest method moduleVariables.

@Test
public void moduleVariables() throws XMLDBException {
    final Source querySource = new StringSource(getModuleVariableQuery("org.exist.xquery.InternalModuleTest$TestModuleWithVariables"));
    final EXistXQueryService queryService = (EXistXQueryService) existServer.getRoot().getService("XQueryService", "1.0");
    moduleVariablesQuery(queryService, querySource, COUNTER.get());
}
Also used : EXistXQueryService(org.exist.xmldb.EXistXQueryService) StringSource(org.exist.source.StringSource) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) Test(org.junit.Test)

Example 75 with Source

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

the class XQueryTrigger method getScript.

private CompiledXQuery getScript(boolean isBefore, DBBroker broker, Txn transaction, XmldbURI src) throws TriggerException {
    // get the query
    final Source query = getQuerySource(broker);
    if (query == null) {
        return null;
    }
    // avoid infinite recursion by allowing just one trigger per thread
    if (isBefore && !TriggerStatePerThread.verifyUniqueTriggerPerThreadBeforePrepare(this, src)) {
        return null;
    } else if (!isBefore && !TriggerStatePerThread.verifyUniqueTriggerPerThreadBeforeFinish(this, src)) {
        return null;
    }
    TriggerStatePerThread.setTransaction(transaction);
    final XQueryContext context = new XQueryContext(broker.getBrokerPool());
    if (query instanceof DBSource) {
        context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI_PREFIX + ((DBSource) query).getDocumentPath().removeLastSegment().toString());
    }
    CompiledXQuery compiledQuery;
    try {
        // compile the XQuery
        compiledQuery = service.compile(context, query);
        // declare user defined parameters as external variables
        for (Object o : userDefinedVariables.keySet()) {
            final String varName = (String) o;
            final String varValue = userDefinedVariables.getProperty(varName);
            context.declareVariable(bindingPrefix + varName, new StringValue(varValue));
        }
        // reset & prepareForExecution for execution
        compiledQuery.reset();
        context.getWatchDog().reset();
        // do any preparation before execution
        context.prepareForExecution();
        return compiledQuery;
    } catch (final XPathException | IOException | PermissionDeniedException e) {
        LOG.warn(e.getMessage(), e);
        TriggerStatePerThread.setTriggerRunningState(TriggerStatePerThread.NO_TRIGGER_RUNNING, this, null);
        TriggerStatePerThread.setTransaction(null);
        throw new TriggerException(PREPARE_EXCEPTION_MESSAGE, e);
    }
}
Also used : DBSource(org.exist.source.DBSource) PermissionDeniedException(org.exist.security.PermissionDeniedException) IOException(java.io.IOException) StringValue(org.exist.xquery.value.StringValue) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) DBSource(org.exist.source.DBSource)

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