Search in sources :

Example 36 with IntegerValue

use of org.exist.xquery.value.IntegerValue in project exist by eXist-db.

the class ImplicitConnectionCloseIT method getJndiConnectionFromModuleIsAutomaticallyClosed.

@Test
public void getJndiConnectionFromModuleIsAutomaticallyClosed() throws EXistException, XPathException, PermissionDeniedException, IOException, LockException, SAXException {
    final String moduleQuery = "module namespace mymodule = \"http://mymodule.com\";\n" + "import module namespace sql = \"http://exist-db.org/xquery/sql\";\n" + "declare function mymodule:get-handle() {\n" + "    sql:get-jndi-connection(\"" + JNDI_DS_NAME + "\", \"" + STUB_JDBC_USER + "\", \"" + STUB_JDBC_PASSWORD + "\")\n" + "};\n";
    final String mainQuery = "import module namespace mymodule = \"http://mymodule.com\" at \"xmldb:exist:///db/mymodule.xqm\";\n" + "mymodule:get-handle()";
    final Source mainQuerySource = new StringSource(mainQuery);
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        // store module
        try (final Collection collection = broker.openCollection(XmldbURI.create("/db"), Lock.LockMode.WRITE_LOCK)) {
            broker.storeDocument(transaction, XmldbURI.create("mymodule.xqm"), new StringInputSource(moduleQuery.getBytes(UTF_8)), MimeType.XQUERY_TYPE, collection);
        }
        final Tuple2<XQueryContext, ModuleContext> escapedContexts = withCompiledQuery(broker, mainQuerySource, mainCompiledQuery -> {
            final XQueryContext mainQueryContext = mainCompiledQuery.getContext();
            // get the context of the library module
            final Module[] libraryModules = mainQueryContext.getModules("http://mymodule.com");
            assertEquals(1, libraryModules.length);
            assertTrue(libraryModules[0] instanceof ExternalModule);
            final ExternalModule libraryModule = (ExternalModule) libraryModules[0];
            final XQueryContext libraryQueryContext = libraryModule.getContext();
            assertTrue(libraryQueryContext instanceof ModuleContext);
            // execute the query
            final Sequence result = executeQuery(broker, mainCompiledQuery);
            // check that the handle for the sql connection that was created was valid
            assertEquals(1, result.getItemCount());
            assertTrue(result.itemAt(0) instanceof IntegerValue);
            assertEquals(Type.LONG, result.itemAt(0).getType());
            final long connectionHandle = result.itemAt(0).toJavaObject(long.class);
            assertFalse(connectionHandle == 0);
            // intentionally escape the contexts from the lambda
            return Tuple(mainQueryContext, (ModuleContext) libraryQueryContext);
        });
        final XQueryContext escapedMainQueryContext = escapedContexts._1;
        final ModuleContext escapedLibraryQueryContext = escapedContexts._2;
        assertTrue(escapedMainQueryContext != escapedLibraryQueryContext);
        // check the connections were closed in the main module
        final int mainConnectionsCount = ModuleUtils.readContextMap(escapedMainQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
        assertEquals(0, mainConnectionsCount);
        // check the connections were closed in the library module
        final int libraryConnectionsCount = ModuleUtils.readContextMap(escapedLibraryQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
        assertEquals(0, libraryConnectionsCount);
        // check the connections from our StubDataSource, they should all be closed
        final Deque<StubDataSource> createdDataSources = StubDataSourceFactory.CREATED_DATA_SOURCES;
        assertEquals(1, createdDataSources.size());
        final StubDataSource stubDataSource = createdDataSources.peek();
        final Deque<StubConnection> createdConnections = stubDataSource.createdConnections;
        assertEquals(1, createdConnections.size());
        final StubConnection stubConnection = createdConnections.peek();
        assertTrue(stubConnection.isClosed());
        transaction.commit();
    }
}
Also used : IntegerValue(org.exist.xquery.value.IntegerValue) 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) DataSource(javax.sql.DataSource) DBBroker(org.exist.storage.DBBroker) StringInputSource(org.exist.util.StringInputSource) Collection(org.exist.collections.Collection) StringSource(org.exist.source.StringSource) BrokerPool(org.exist.storage.BrokerPool) Test(org.junit.Test)

Example 37 with IntegerValue

use of org.exist.xquery.value.IntegerValue in project exist by eXist-db.

the class GetJNDIConnectionFunction method eval.

/**
 * evaluate the call to the xquery get-jndi-connection() function, it is really the main entry point of this class.
 *
 * @param args            arguments from the get-jndi-connection() function call
 * @param contextSequence the Context Sequence to operate on (not used here internally!)
 * @return A xs:long representing a handle to the connection
 * @throws XPathException DOCUMENT ME!
 * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
 */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // was a JNDI name specified?
    if (args[0].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }
    try {
        Connection con = null;
        // get the JNDI source
        String jndiName = args[0].getStringValue();
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup(jndiName);
        // try and get the connection
        if (args.length == 1) {
            con = ds.getConnection();
        }
        if (args.length == 3) {
            String jndiUser = args[1].getStringValue();
            String jndiPassword = args[2].getStringValue();
            con = ds.getConnection(jndiUser, jndiPassword);
        }
        // store the connection and return the uid handle of the connection
        return (new IntegerValue(SQLModule.storeConnection(context, con), Type.LONG));
    } catch (Exception e) {
        throw (new XPathException(this, e.getMessage()));
    }
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) XQueryContext(org.exist.xquery.XQueryContext) XPathException(org.exist.xquery.XPathException) IntegerValue(org.exist.xquery.value.IntegerValue) Connection(java.sql.Connection) InitialContext(javax.naming.InitialContext) XPathException(org.exist.xquery.XPathException) DataSource(javax.sql.DataSource)

Example 38 with IntegerValue

use of org.exist.xquery.value.IntegerValue in project exist by eXist-db.

the class ConnectionPoolIT method getConnectionFromPoolIsAutomaticallyClosed.

@Test
public void getConnectionFromPoolIsAutomaticallyClosed() throws EXistException, XPathException, PermissionDeniedException, IOException {
    // NOTE: pool-1 is configured in src/test/resources-filtered/conf.xml
    final String mainQuery = "import module namespace sql = \"http://exist-db.org/xquery/sql\";\n" + "sql:get-connection-from-pool(\"pool-1\")";
    final Source mainQuerySource = new StringSource(mainQuery);
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    try (final DBBroker broker = pool.getBroker();
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        final XQueryContext escapedMainQueryContext = withCompiledQuery(broker, mainQuerySource, mainCompiledQuery -> {
            final XQueryContext mainQueryContext = mainCompiledQuery.getContext();
            // execute the query
            final Sequence result = executeQuery(broker, mainCompiledQuery);
            // check that the handle for the sql connection that was created was valid
            assertEquals(1, result.getItemCount());
            assertTrue(result.itemAt(0) instanceof IntegerValue);
            assertEquals(Type.LONG, result.itemAt(0).getType());
            final long connectionHandle = result.itemAt(0).toJavaObject(long.class);
            assertFalse(connectionHandle == 0);
            // intentionally escape the context from the lambda
            return mainQueryContext;
        });
        // check the connections map is empty
        final int connectionsCount = ModuleUtils.readContextMap(escapedMainQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
        assertEquals(0, connectionsCount);
        transaction.commit();
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) IntegerValue(org.exist.xquery.value.IntegerValue) XQueryContext(org.exist.xquery.XQueryContext) StringSource(org.exist.source.StringSource) Txn(org.exist.storage.txn.Txn) Sequence(org.exist.xquery.value.Sequence) Map(java.util.Map) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) BrokerPool(org.exist.storage.BrokerPool) Test(org.junit.Test)

Example 39 with IntegerValue

use of org.exist.xquery.value.IntegerValue in project exist by eXist-db.

the class JndiConnectionIT method getJndiConnectionFromModuleIsAutomaticallyClosed.

@Test
public void getJndiConnectionFromModuleIsAutomaticallyClosed() throws EXistException, XPathException, PermissionDeniedException, IOException, LockException, SAXException {
    final String moduleQuery = "module namespace mymodule = \"http://mymodule.com\";\n" + "import module namespace sql = \"http://exist-db.org/xquery/sql\";\n" + "declare function mymodule:get-handle() {\n" + "    sql:get-jndi-connection(\"" + JNDI_DS_NAME + "\", \"" + h2Database.getUser() + "\", \"" + h2Database.getPassword() + "\")\n" + "};\n";
    final String mainQuery = "import module namespace mymodule = \"http://mymodule.com\" at \"xmldb:exist:///db/mymodule.xqm\";\n" + "mymodule:get-handle()";
    final Source mainQuerySource = new StringSource(mainQuery);
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        // store module
        try (final Collection collection = broker.openCollection(XmldbURI.create("/db"), Lock.LockMode.WRITE_LOCK)) {
            broker.storeDocument(transaction, XmldbURI.create("mymodule.xqm"), new StringInputSource(moduleQuery.getBytes(UTF_8)), MimeType.XQUERY_TYPE, collection);
        }
        final Tuple2<XQueryContext, ModuleContext> escapedContexts = withCompiledQuery(broker, mainQuerySource, mainCompiledQuery -> {
            final XQueryContext mainQueryContext = mainCompiledQuery.getContext();
            // get the context of the library module
            final Module[] libraryModules = mainQueryContext.getModules("http://mymodule.com");
            assertEquals(1, libraryModules.length);
            assertTrue(libraryModules[0] instanceof ExternalModule);
            final ExternalModule libraryModule = (ExternalModule) libraryModules[0];
            final XQueryContext libraryQueryContext = libraryModule.getContext();
            assertTrue(libraryQueryContext instanceof ModuleContext);
            // execute the query
            final Sequence result = executeQuery(broker, mainCompiledQuery);
            // check that the handle for the sql connection that was created was valid
            assertEquals(1, result.getItemCount());
            assertTrue(result.itemAt(0) instanceof IntegerValue);
            assertEquals(Type.LONG, result.itemAt(0).getType());
            final long connectionHandle = result.itemAt(0).toJavaObject(long.class);
            assertFalse(connectionHandle == 0);
            // intentionally escape the contexts from the lambda
            return Tuple(mainQueryContext, (ModuleContext) libraryQueryContext);
        });
        final XQueryContext escapedMainQueryContext = escapedContexts._1;
        final ModuleContext escapedLibraryQueryContext = escapedContexts._2;
        assertTrue(escapedMainQueryContext != escapedLibraryQueryContext);
        // check the connections were closed in the main module
        final int mainConnectionsCount = ModuleUtils.readContextMap(escapedMainQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
        assertEquals(0, mainConnectionsCount);
        // check the connections were closed in the library module
        final int libraryConnectionsCount = ModuleUtils.readContextMap(escapedLibraryQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
        assertEquals(0, libraryConnectionsCount);
        transaction.commit();
    }
}
Also used : IntegerValue(org.exist.xquery.value.IntegerValue) 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) JdbcDataSource(org.h2.jdbcx.JdbcDataSource) DBBroker(org.exist.storage.DBBroker) StringInputSource(org.exist.util.StringInputSource) Collection(org.exist.collections.Collection) StringSource(org.exist.source.StringSource) Map(java.util.Map) BrokerPool(org.exist.storage.BrokerPool) Test(org.junit.Test)

Example 40 with IntegerValue

use of org.exist.xquery.value.IntegerValue in project exist by eXist-db.

the class JndiConnectionIT method getJndiConnectionIsAutomaticallyClosed.

@Test
public void getJndiConnectionIsAutomaticallyClosed() throws EXistException, XPathException, PermissionDeniedException, IOException {
    final String mainQuery = "import module namespace sql = \"http://exist-db.org/xquery/sql\";\n" + "sql:get-jndi-connection(\"" + JNDI_DS_NAME + "\", \"" + h2Database.getUser() + "\", \"" + h2Database.getPassword() + "\")";
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    final Source mainQuerySource = new StringSource(mainQuery);
    try (final DBBroker broker = pool.getBroker();
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        final XQueryContext escapedMainQueryContext = withCompiledQuery(broker, mainQuerySource, mainCompiledQuery -> {
            final XQueryContext mainQueryContext = mainCompiledQuery.getContext();
            // execute the query
            final Sequence result = executeQuery(broker, mainCompiledQuery);
            // check that the handle for the sql connection that was created was valid
            assertEquals(1, result.getItemCount());
            assertTrue(result.itemAt(0) instanceof IntegerValue);
            assertEquals(Type.LONG, result.itemAt(0).getType());
            final long connectionHandle = result.itemAt(0).toJavaObject(long.class);
            assertFalse(connectionHandle == 0);
            return mainQueryContext;
        });
        // check the connections map is empty
        final int connectionsCount = ModuleUtils.readContextMap(escapedMainQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
        assertEquals(0, connectionsCount);
        transaction.commit();
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) IntegerValue(org.exist.xquery.value.IntegerValue) StringSource(org.exist.source.StringSource) Txn(org.exist.storage.txn.Txn) Sequence(org.exist.xquery.value.Sequence) Map(java.util.Map) BrokerPool(org.exist.storage.BrokerPool) StringSource(org.exist.source.StringSource) StringInputSource(org.exist.util.StringInputSource) Source(org.exist.source.Source) JdbcDataSource(org.h2.jdbcx.JdbcDataSource) Test(org.junit.Test)

Aggregations

IntegerValue (org.exist.xquery.value.IntegerValue)63 Sequence (org.exist.xquery.value.Sequence)33 XPathException (org.exist.xquery.XPathException)32 BrokerPool (org.exist.storage.BrokerPool)11 DBBroker (org.exist.storage.DBBroker)11 Test (org.junit.Test)11 Txn (org.exist.storage.txn.Txn)8 MessagingException (jakarta.mail.MessagingException)7 StringInputSource (org.exist.util.StringInputSource)7 NamingException (javax.naming.NamingException)6 DirContext (javax.naming.directory.DirContext)6 QName (org.exist.dom.QName)6 Source (org.exist.source.Source)6 StringSource (org.exist.source.StringSource)6 InputStream (java.io.InputStream)5 Map (java.util.Map)5 StringValue (org.exist.xquery.value.StringValue)5 ValueSequence (org.exist.xquery.value.ValueSequence)5 Folder (jakarta.mail.Folder)4 Image (java.awt.Image)4