Search in sources :

Example 1 with XQueryContext

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

the class XQueryStartupTrigger method executeQuery.

/**
 * Execute xquery on path
 *
 * @param broker eXist database broker
 * @param path path to query, formatted as xmldb:exist:///db/...
 */
private void executeQuery(DBBroker broker, String path) {
    XQueryContext context = null;
    try {
        // Get path to xquery
        Source source = SourceFactory.getSource(broker, null, path, false);
        if (source == null) {
            LOG.info("No XQuery found at '{}'", path);
        } else {
            // Setup xquery service
            XQuery service = broker.getBrokerPool().getXQueryService();
            context = new XQueryContext(broker.getBrokerPool());
            // Allow use of modules with relative paths
            String moduleLoadPath = StringUtils.substringBeforeLast(path, "/");
            context.setModuleLoadPath(moduleLoadPath);
            // Compile query
            CompiledXQuery compiledQuery = service.compile(context, source);
            LOG.info("Starting XQuery at '{}'", path);
            // Finish preparation
            context.prepareForExecution();
            // Execute
            Sequence result = service.execute(broker, compiledQuery, null);
            // Log results
            LOG.info("Result XQuery: '{}'", result.getStringValue());
        }
    } catch (Throwable t) {
        // Dirty, catch it all
        LOG.error("An error occurred during preparation/execution of the XQuery script {}: {}", path, t.getMessage(), t);
    } finally {
        if (context != null) {
            context.runCleanupTasks();
        }
    }
}
Also used : 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) Source(org.exist.source.Source)

Example 2 with XQueryContext

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

the class Compile method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // get the query expression
    final String expr = args[0].getStringValue();
    if (expr.trim().isEmpty()) {
        return new EmptySequence();
    }
    context.pushNamespaceContext();
    logger.debug("eval: {}", expr);
    // TODO(pkaminsk2): why replicate XQuery.compile here?
    String error = null;
    ErrorCodes.ErrorCode code = null;
    int line = -1;
    int column = -1;
    final XQueryContext pContext = new XQueryContext(context.getBroker().getBrokerPool());
    if (getArgumentCount() == 2 && args[1].hasOne()) {
        pContext.setModuleLoadPath(args[1].getStringValue());
    }
    final XQueryLexer lexer = new XQueryLexer(pContext, new StringReader(expr));
    final XQueryParser parser = new XQueryParser(lexer);
    // shares the context of the outer expression
    final XQueryTreeParser astParser = new XQueryTreeParser(pContext);
    try {
        parser.xpath();
        if (parser.foundErrors()) {
            logger.debug(parser.getErrorMessage());
            throw new XPathException(this, "error found while executing expression: " + parser.getErrorMessage());
        }
        final AST ast = parser.getAST();
        final PathExpr path = new PathExpr(pContext);
        astParser.xpath(ast, path);
        if (astParser.foundErrors()) {
            throw astParser.getLastException();
        }
        path.analyze(new AnalyzeContextInfo());
    } catch (final RecognitionException | TokenStreamException e) {
        error = e.toString();
    } catch (final XPathException e) {
        line = e.getLine();
        column = e.getColumn();
        code = e.getCode();
        error = e.getDetailMessage();
    } catch (final Exception e) {
        error = e.getMessage();
    } finally {
        context.popNamespaceContext();
        pContext.reset(false);
    }
    if (isCalledAs("compile")) {
        return error == null ? Sequence.EMPTY_SEQUENCE : new StringValue(error);
    } else {
        return response(pContext, error, code, line, column);
    }
}
Also used : EmptySequence(org.exist.xquery.value.EmptySequence) AST(antlr.collections.AST) XPathException(org.exist.xquery.XPathException) XQueryContext(org.exist.xquery.XQueryContext) XQueryParser(org.exist.xquery.parser.XQueryParser) XQueryLexer(org.exist.xquery.parser.XQueryLexer) AnalyzeContextInfo(org.exist.xquery.AnalyzeContextInfo) RecognitionException(antlr.RecognitionException) TokenStreamException(antlr.TokenStreamException) XPathException(org.exist.xquery.XPathException) ErrorCode(org.exist.xquery.ErrorCodes.ErrorCode) XQueryTreeParser(org.exist.xquery.parser.XQueryTreeParser) TokenStreamException(antlr.TokenStreamException) ErrorCodes(org.exist.xquery.ErrorCodes) StringReader(java.io.StringReader) StringValue(org.exist.xquery.value.StringValue) PathExpr(org.exist.xquery.PathExpr) RecognitionException(antlr.RecognitionException)

Example 3 with XQueryContext

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

the class ModuleInfo method eval.

/* (non-Javadoc)
	 * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
	 */
@SuppressWarnings("unchecked")
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if ("get-module-description".equals(getSignature().getName().getLocalPart())) {
        final String uri = args[0].getStringValue();
        final Module[] modules = context.getModules(uri);
        if (isEmpty(modules)) {
            throw new XPathException(this, "No module found matching namespace URI: " + uri);
        }
        final Sequence result = new ValueSequence();
        for (final Module module : modules) {
            result.add(new StringValue(module.getDescription()));
        }
        return result;
    } else if ("is-module-registered".equals(getSignature().getName().getLocalPart())) {
        final String uri = args[0].getStringValue();
        final Module[] modules = context.getModules(uri);
        return new BooleanValue(modules != null && modules.length > 0);
    } else if ("mapped-modules".equals(getSignature().getName().getLocalPart())) {
        final ValueSequence resultSeq = new ValueSequence();
        for (final Iterator<String> i = context.getMappedModuleURIs(); i.hasNext(); ) {
            resultSeq.add(new StringValue(i.next()));
        }
        return resultSeq;
    } else if ("is-module-mapped".equals(getSignature().getName().getLocalPart())) {
        final String uri = args[0].getStringValue();
        return new BooleanValue(((Map<String, String>) context.getBroker().getConfiguration().getProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP)).get(uri) != null);
    } else if ("map-module".equals(getSignature().getName().getLocalPart())) {
        if (!context.getSubject().hasDbaRole()) {
            final XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to call this function.");
            logger.error("Invalid user", xPathException);
            throw xPathException;
        }
        final String namespace = args[0].getStringValue();
        final String location = args[1].getStringValue();
        final Map<String, String> moduleMap = (Map<String, String>) context.getBroker().getConfiguration().getProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP);
        moduleMap.put(namespace, location);
        return Sequence.EMPTY_SEQUENCE;
    } else if ("unmap-module".equals(getSignature().getName().getLocalPart())) {
        if (!context.getSubject().hasDbaRole()) {
            final XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to call this function.");
            logger.error("Invalid user", xPathException);
            throw xPathException;
        }
        final String namespace = args[0].getStringValue();
        final Map<String, String> moduleMap = (Map<String, String>) context.getBroker().getConfiguration().getProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP);
        moduleMap.remove(namespace);
        return Sequence.EMPTY_SEQUENCE;
    } else if ("get-module-info".equals(getSignature().getName().getLocalPart())) {
        context.pushDocumentContext();
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            builder.startElement(MODULES_QNAME, null);
            if (getArgumentCount() == 1) {
                final Module[] modules = context.getModules(args[0].getStringValue());
                if (modules != null) {
                    outputModules(builder, modules);
                }
            } else {
                for (final Iterator<Module> i = context.getRootModules(); i.hasNext(); ) {
                    final Module module = i.next();
                    outputModule(builder, module);
                }
            }
            return builder.getDocument().getNode(1);
        } finally {
            context.popDocumentContext();
        }
    } else {
        final ValueSequence resultSeq = new ValueSequence();
        final XQueryContext tempContext = new XQueryContext(context.getBroker().getBrokerPool());
        for (final Iterator<Module> i = tempContext.getRootModules(); i.hasNext(); ) {
            final Module module = i.next();
            resultSeq.add(new StringValue(module.getNamespaceURI()));
        }
        if (tempContext.getRepository().isPresent()) {
            for (final URI uri : tempContext.getRepository().get().getJavaModules()) {
                resultSeq.add(new StringValue(uri.toString()));
            }
        }
        return resultSeq;
    }
}
Also used : XPathException(org.exist.xquery.XPathException) XQueryContext(org.exist.xquery.XQueryContext) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) URI(java.net.URI) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) BooleanValue(org.exist.xquery.value.BooleanValue) ValueSequence(org.exist.xquery.value.ValueSequence) Module(org.exist.xquery.Module) ExternalModule(org.exist.xquery.ExternalModule) StringValue(org.exist.xquery.value.StringValue) Map(java.util.Map)

Example 4 with XQueryContext

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

the class IdFunctionTest method sameRealAndEffectiveUsers.

/**
 * Test of eval method, of class IdFunction.
 * when real and effective users are the same
 */
@Test
public void sameRealAndEffectiveUsers() throws XPathException, XpathException {
    final XQueryContext mckContext = createMockBuilder(XQueryContext.class).addMockedMethod("pushDocumentContext").addMockedMethod("getDocumentBuilder", new Class[0]).addMockedMethod("popDocumentContext").addMockedMethod("getRealUser").addMockedMethod("getEffectiveUser").createMock();
    final Subject mckUser = EasyMock.createMock(Subject.class);
    final String username = "user1";
    mckContext.pushDocumentContext();
    expectLastCall().once();
    expect(mckContext.getDocumentBuilder()).andReturn(new MemTreeBuilder());
    mckContext.popDocumentContext();
    expectLastCall().once();
    expect(mckContext.getRealUser()).andReturn(mckUser).times(2);
    expect(mckUser.getName()).andReturn(username);
    expect(mckUser.getGroups()).andReturn(new String[] { "group1", "group2" });
    expect(mckUser.getId()).andReturn(1);
    expect(mckContext.getEffectiveUser()).andReturn(mckUser);
    expect(mckUser.getId()).andReturn(1);
    replay(mckUser, mckContext);
    final IdFunction idFunctions = new IdFunction(mckContext, IdFunction.FNS_ID);
    final Sequence result = idFunctions.eval(new Sequence[] { Sequence.EMPTY_SEQUENCE }, null);
    assertEquals(1, result.getItemCount());
    final XpathEngine xpathEngine = XMLUnit.newXpathEngine();
    final Map<String, String> namespaces = new HashMap<>();
    namespaces.put("sm", "http://exist-db.org/xquery/securitymanager");
    xpathEngine.setNamespaceContext(new SimpleNamespaceContext(namespaces));
    final DocumentImpl resultDoc = (DocumentImpl) result.itemAt(0);
    final String actualRealUsername = xpathEngine.evaluate("/sm:id/sm:real/sm:username", resultDoc);
    assertEquals(username, actualRealUsername);
    final String actualEffectiveUsername = xpathEngine.evaluate("/sm:id/sm:effective/sm:username", resultDoc);
    assertEquals("", actualEffectiveUsername);
    verify(mckUser, mckContext);
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) XpathEngine(org.custommonkey.xmlunit.XpathEngine) HashMap(java.util.HashMap) XQueryContext(org.exist.xquery.XQueryContext) Sequence(org.exist.xquery.value.Sequence) SimpleNamespaceContext(org.custommonkey.xmlunit.SimpleNamespaceContext) DocumentImpl(org.exist.dom.memtree.DocumentImpl) Subject(org.exist.security.Subject) Test(org.junit.Test)

Example 5 with XQueryContext

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

the class AbstractFieldConfig method compile.

protected CompiledXQuery compile(DBBroker broker, String code) {
    final XQuery xquery = broker.getBrokerPool().getXQueryService();
    final XQueryContext context = new XQueryContext(broker.getBrokerPool());
    try {
        return xquery.compile(context, code);
    } catch (XPathException | PermissionDeniedException e) {
        LOG.error("Failed to compile expression: {}: {}", code, e.getMessage(), e);
        isValid = false;
        return null;
    }
}
Also used : XPathException(org.exist.xquery.XPathException) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQuery(org.exist.xquery.XQuery) XQueryContext(org.exist.xquery.XQueryContext) PermissionDeniedException(org.exist.security.PermissionDeniedException)

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