Search in sources :

Example 16 with XQueryContext

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

the class LuceneIndexTest method queryTranslation.

@Test
public void queryTranslation() throws EXistException, CollectionConfigurationException, PermissionDeniedException, SAXException, TriggerException, LockException, IOException, XPathException {
    configureAndStore(COLLECTION_CONFIG1, XML7, "test.xml");
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) {
        final XQuery xquery = pool.getXQueryService();
        assertNotNull(xquery);
        final XQueryContext context = new XQueryContext(broker.getBrokerPool());
        final CompiledXQuery compiled = xquery.compile(context, "declare variable $q external; " + "ft:query(//p, parse-xml($q)/query)");
        context.declareVariable("q", "<query><term>heiterkeit</term></query>");
        Sequence seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
        context.declareVariable("q", "<query>" + "   <bool>" + "       <term>heiterkeit</term><term>blablabla</term>" + "   </bool>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
        context.declareVariable("q", "<query>" + "   <bool>" + "       <term occur='should'>heiterkeit</term><term occur='should'>blablabla</term>" + "   </bool>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
        context.declareVariable("q", "<query>" + "   <bool>" + "       <term occur='must'>heiterkeit</term><term occur='must'>blablabla</term>" + "   </bool>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(0, seq.getItemCount());
        context.declareVariable("q", "<query>" + "   <bool>" + "       <term occur='must'>heiterkeit</term><term occur='not'>herzen</term>" + "   </bool>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(0, seq.getItemCount());
        context.declareVariable("q", "<query>" + "   <bool>" + "       <phrase occur='must'>wunderbare heiterkeit</phrase><term occur='must'>herzen</term>" + "   </bool>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
        context.declareVariable("q", "<query>" + "   <phrase slop='5'>heiterkeit seele eingenommen</phrase>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
        // phrase with wildcards
        context.declareVariable("q", "<query>" + "   <phrase slop='5'><term>heiter*</term><term>se?nnnle*</term></phrase>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
        context.declareVariable("q", "<query>" + "   <wildcard>?eiter*</wildcard>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
        context.declareVariable("q", "<query>" + "   <fuzzy max-edits='2'>selee</fuzzy>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
        context.declareVariable("q", "<query>" + "   <bool>" + "       <fuzzy occur='must' max-edits='2'>selee</fuzzy>" + "       <wildcard occur='should'>bla*</wildcard>" + "   </bool>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
        context.declareVariable("q", "<query>" + "   <regex>heit.*keit</regex>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
        context.declareVariable("q", "<query>" + "   <phrase><term>wunderbare</term><regex>heit.*keit</regex></phrase>" + "</query>");
        seq = xquery.execute(broker, compiled, null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) XQuery(org.exist.xquery.XQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQueryContext(org.exist.xquery.XQueryContext) Sequence(org.exist.xquery.value.Sequence) BrokerPool(org.exist.storage.BrokerPool)

Example 17 with XQueryContext

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

the class IPRangeRealm method authenticate.

@Override
public Subject authenticate(final String ipAddress, final Object credentials) throws AuthenticationException {
    // Elevaste to system privileges
    try (final DBBroker broker = getSecurityManager().database().get(Optional.of(getSecurityManager().getSystemSubject()))) {
        // Convert IP address
        final long ipToTest = ipToLong(InetAddress.getByName(ipAddress));
        // Get xquery service
        final XQuery queryService = broker.getBrokerPool().getXQueryService();
        if (queryService == null) {
            LOG.error("IPRange broker unable to retrieve XQueryService");
            return null;
        }
        // Construct XQuery
        final String query = "collection('/db/system/security/iprange/accounts')/account/" + "iprange[" + ipToTest + " ge number(start) and " + ipToTest + " le number(end)]/../name";
        final XQueryContext context = new XQueryContext(broker.getBrokerPool());
        final CompiledXQuery compiled = queryService.compile(context, query);
        final Properties outputProperties = new Properties();
        // Execute xQuery
        final Sequence result = queryService.execute(broker, compiled, null, outputProperties);
        final SequenceIterator i = result.iterate();
        // Get FIRST username when present
        final String username = i.hasNext() ? i.nextItem().getStringValue() : "";
        if (i.hasNext()) {
            LOG.warn("IP address {} matched multiple ipranges. Using first result only.", ipAddress);
        }
        if (!username.isEmpty()) {
            final Account account = getSecurityManager().getAccount(username);
            if (account != null) {
                LOG.info("IPRangeRealm trying {}", account.getName());
                return new SubjectAccreditedImpl((AbstractAccount) account, ipAddress);
            } else {
                LOG.info("IPRangeRealm couldn't resolve account for {}", username);
            }
        } else {
            LOG.info("IPRangeRealm xquery found no matches");
        }
        return null;
    } catch (final EXistException | UnknownHostException | XPathException | PermissionDeniedException e) {
        throw new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, e.getMessage());
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) XPathException(org.exist.xquery.XPathException) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQuery(org.exist.xquery.XQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQueryContext(org.exist.xquery.XQueryContext) Sequence(org.exist.xquery.value.Sequence) EXistException(org.exist.EXistException) Properties(java.util.Properties) DBBroker(org.exist.storage.DBBroker) SequenceIterator(org.exist.xquery.value.SequenceIterator) SubjectAccreditedImpl(org.exist.security.internal.SubjectAccreditedImpl)

Example 18 with XQueryContext

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

the class RedirectorServlet method executeQuery.

private Sequence executeQuery(final Source source, final RequestWrapper request, final ResponseWrapper response) throws EXistException, XPathException, PermissionDeniedException, IOException {
    final XQuery xquery = getPool().getXQueryService();
    final XQueryPool pool = getPool().getXQueryPool();
    try (final DBBroker broker = getPool().getBroker()) {
        final XQueryContext context;
        CompiledXQuery compiled = pool.borrowCompiledXQuery(broker, source);
        if (compiled == null) {
            // special header to indicate that the query is not returned from
            // cache
            response.setHeader("X-XQuery-Cached", "false");
            context = new XQueryContext(getPool());
            context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI.toString());
            compiled = xquery.compile(context, source);
        } else {
            response.setHeader("X-XQuery-Cached", "true");
            context = compiled.getContext();
            context.prepareForReuse();
        }
        try {
            return xquery.execute(broker, compiled, null, new Properties());
        } finally {
            context.runCleanupTasks();
            pool.returnCompiledXQuery(source, compiled);
        }
    }
}
Also used : XQueryPool(org.exist.storage.XQueryPool) DBBroker(org.exist.storage.DBBroker) XQuery(org.exist.xquery.XQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQueryContext(org.exist.xquery.XQueryContext)

Example 19 with XQueryContext

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

the class SanityReport method ping.

@Override
public long ping(boolean checkQueryEngine) {
    final long start = System.currentTimeMillis();
    lastPingRespTime = -1;
    lastActionInfo = "Ping";
    taskstatus.setStatus(TaskStatus.Status.PING_WAIT);
    // this will block forever.
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getGuestSubject()))) {
        if (checkQueryEngine) {
            final XQuery xquery = pool.getXQueryService();
            final XQueryPool xqPool = pool.getXQueryPool();
            CompiledXQuery compiled = xqPool.borrowCompiledXQuery(broker, TEST_XQUERY);
            if (compiled == null) {
                final XQueryContext context = new XQueryContext(pool);
                compiled = xquery.compile(context, TEST_XQUERY);
            } else {
                compiled.getContext().prepareForReuse();
            }
            try {
                xquery.execute(broker, compiled, null);
            } finally {
                compiled.getContext().runCleanupTasks();
                xqPool.returnCompiledXQuery(TEST_XQUERY, compiled);
            }
        }
    } catch (final Exception e) {
        lastPingRespTime = -2;
        taskstatus.setStatus(TaskStatus.Status.PING_ERROR);
        taskstatus.setStatusChangeTime();
        taskstatus.setReason(e.getMessage());
        changeStatus(taskstatus);
    } finally {
        lastPingRespTime = System.currentTimeMillis() - start;
        taskstatus.setStatus(TaskStatus.Status.PING_OK);
        taskstatus.setStatusChangeTime();
        taskstatus.setReason("ping response time: " + lastPingRespTime);
        changeStatus(taskstatus);
    }
    return lastPingRespTime;
}
Also used : XQueryPool(org.exist.storage.XQueryPool) DBBroker(org.exist.storage.DBBroker) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQuery(org.exist.xquery.XQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQueryContext(org.exist.xquery.XQueryContext) EXistException(org.exist.EXistException)

Example 20 with XQueryContext

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

the class AbstractTestRunner method executeQuery.

protected static Sequence executeQuery(final BrokerPool brokerPool, final Source query, final List<Function<XQueryContext, Tuple2<String, Object>>> externalVariableBindings) throws EXistException, PermissionDeniedException, XPathException, IOException, DatabaseConfigurationException {
    final SecurityManager securityManager = requireNonNull(brokerPool.getSecurityManager(), "securityManager is null");
    try (final DBBroker broker = brokerPool.get(Optional.of(securityManager.getSystemSubject()))) {
        final XQueryPool queryPool = brokerPool.getXQueryPool();
        CompiledXQuery compiledQuery = queryPool.borrowCompiledXQuery(broker, query);
        try {
            XQueryContext context;
            if (compiledQuery == null) {
                context = new XQueryContext(broker.getBrokerPool());
            } else {
                context = compiledQuery.getContext();
                context.prepareForReuse();
            }
            // setup misc. context
            context.setBaseURI(new AnyURIValue("/db"));
            if (query instanceof FileSource) {
                final Path queryPath = Paths.get(((FileSource) query).getPath().toAbsolutePath().toString());
                if (Files.isDirectory(queryPath)) {
                    context.setModuleLoadPath(queryPath.toString());
                } else {
                    context.setModuleLoadPath(queryPath.getParent().toString());
                }
            }
            // declare variables for the query
            for (final Function<XQueryContext, Tuple2<String, Object>> externalVariableBinding : externalVariableBindings) {
                final Tuple2<String, Object> nameValue = externalVariableBinding.apply(context);
                context.declareVariable(nameValue._1, nameValue._2);
            }
            final XQuery xqueryService = brokerPool.getXQueryService();
            // compile or update the context
            if (compiledQuery == null) {
                compiledQuery = xqueryService.compile(context, query);
            } else {
                compiledQuery.getContext().updateContext(context);
                context.getWatchDog().reset();
            }
            return xqueryService.execute(broker, compiledQuery, null);
        } finally {
            queryPool.returnCompiledXQuery(query, compiledQuery);
        }
    }
}
Also used : Path(java.nio.file.Path) SecurityManager(org.exist.security.SecurityManager) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQuery(org.exist.xquery.XQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) AnyURIValue(org.exist.xquery.value.AnyURIValue) FileSource(org.exist.source.FileSource) XQueryContext(org.exist.xquery.XQueryContext) XQueryPool(org.exist.storage.XQueryPool) DBBroker(org.exist.storage.DBBroker) Tuple2(com.evolvedbinary.j8fu.tuple.Tuple2)

Aggregations

XQueryContext (org.exist.xquery.XQueryContext)70 CompiledXQuery (org.exist.xquery.CompiledXQuery)37 Sequence (org.exist.xquery.value.Sequence)34 XQuery (org.exist.xquery.XQuery)33 DBBroker (org.exist.storage.DBBroker)24 Test (org.junit.Test)23 XPathException (org.exist.xquery.XPathException)18 BrokerPool (org.exist.storage.BrokerPool)17 IOException (java.io.IOException)11 Source (org.exist.source.Source)10 XQueryPool (org.exist.storage.XQueryPool)10 Node (org.w3c.dom.Node)10 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)8 PermissionDeniedException (org.exist.security.PermissionDeniedException)8 AnyURIValue (org.exist.xquery.value.AnyURIValue)8 URI (java.net.URI)7 StringValue (org.exist.xquery.value.StringValue)7 InputSource (org.xml.sax.InputSource)7 EXistException (org.exist.EXistException)6 QName (org.exist.dom.QName)6