Search in sources :

Example 1 with StringValue

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

the class XQueryTrigger method finish.

private void finish(int event, DBBroker broker, Txn transaction, XmldbURI src, XmldbURI dst, boolean isCollection) {
    // get the query
    final Source query = getQuerySource(broker);
    if (query == null) {
        return;
    }
    // avoid infinite recursion by allowing just one trigger per thread
    if (!TriggerStatePerThread.verifyUniqueTriggerPerThreadBeforeFinish(this, src)) {
        return;
    }
    final XQueryContext context = new XQueryContext(broker.getBrokerPool());
    CompiledXQuery compiledQuery = null;
    try {
        // compile the XQuery
        compiledQuery = service.compile(context, query);
        // declare external variables
        context.declareVariable(bindingPrefix + "type", EVENT_TYPE_FINISH);
        context.declareVariable(bindingPrefix + "event", new StringValue(eventToString(event)));
        if (isCollection) {
            context.declareVariable(bindingPrefix + "collection", new AnyURIValue(src));
        } else {
            context.declareVariable(bindingPrefix + "collection", new AnyURIValue(src.removeLastSegment()));
        }
        context.declareVariable(bindingPrefix + "uri", new AnyURIValue(src));
        if (dst == null) {
            context.declareVariable(bindingPrefix + "new-uri", Sequence.EMPTY_SEQUENCE);
        } else {
            context.declareVariable(bindingPrefix + "new-uri", new AnyURIValue(dst));
        }
        // For backward compatibility
        context.declareVariable(bindingPrefix + "eventType", EVENT_TYPE_FINISH);
        context.declareVariable(bindingPrefix + "triggerEvent", new StringValue(eventToString(event)));
        if (isCollection) {
            context.declareVariable(bindingPrefix + "collectionName", new AnyURIValue(src));
        } else {
            context.declareVariable(bindingPrefix + "collectionName", new AnyURIValue(src.removeLastSegment()));
            context.declareVariable(bindingPrefix + "documentName", new AnyURIValue(src));
        }
        // 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));
        }
    } catch (final XPathException | IOException | PermissionDeniedException e) {
        // Should never be reached
        LOG.error(e);
    }
    // execute the XQuery
    try {
        // TODO : should we provide another contextSet ?
        final NodeSet contextSet = NodeSet.EMPTY_SET;
        service.execute(broker, compiledQuery, contextSet);
    // TODO : should we have a special processing ?
    } catch (final XPathException e) {
        // Should never be reached
        LOG.error("Error during trigger finish", e);
    } catch (final PermissionDeniedException e) {
        // Should never be reached
        LOG.error(e);
    }
    TriggerStatePerThread.setTriggerRunningState(TriggerStatePerThread.NO_TRIGGER_RUNNING, this, null);
    TriggerStatePerThread.setTransaction(null);
    LOG.debug("Trigger fired for finish");
}
Also used : NodeSet(org.exist.dom.persistent.NodeSet) AnyURIValue(org.exist.xquery.value.AnyURIValue) 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)

Example 2 with StringValue

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

the class XQueryTrigger method prepare.

private void prepare(int event, DBBroker broker, Txn transaction, XmldbURI src, XmldbURI dst, boolean isCollection) throws TriggerException {
    // get the query
    final Source query = getQuerySource(broker);
    if (query == null) {
        return;
    }
    // avoid infinite recursion by allowing just one trigger per thread
    if (!TriggerStatePerThread.verifyUniqueTriggerPerThreadBeforePrepare(this, src)) {
        return;
    }
    TriggerStatePerThread.setTransaction(transaction);
    final XQueryContext context = new XQueryContext(broker.getBrokerPool());
    // TODO : further initialisations ?
    CompiledXQuery compiledQuery;
    try {
        // compile the XQuery
        compiledQuery = service.compile(context, query);
        // declare external variables
        context.declareVariable(bindingPrefix + "type", EVENT_TYPE_PREPARE);
        context.declareVariable(bindingPrefix + "event", new StringValue(eventToString(event)));
        if (isCollection) {
            context.declareVariable(bindingPrefix + "collection", new AnyURIValue(src));
        } else {
            context.declareVariable(bindingPrefix + "collection", new AnyURIValue(src.removeLastSegment()));
        }
        context.declareVariable(bindingPrefix + "uri", new AnyURIValue(src));
        if (dst == null) {
            context.declareVariable(bindingPrefix + "new-uri", Sequence.EMPTY_SEQUENCE);
        } else {
            context.declareVariable(bindingPrefix + "new-uri", new AnyURIValue(dst));
        }
        // For backward compatibility
        context.declareVariable(bindingPrefix + "eventType", EVENT_TYPE_PREPARE);
        context.declareVariable(bindingPrefix + "triggerEvent", new StringValue(eventToString(event)));
        if (isCollection) {
            context.declareVariable(bindingPrefix + "collectionName", new AnyURIValue(src));
        } else {
            context.declareVariable(bindingPrefix + "collectionName", new AnyURIValue(src.removeLastSegment()));
            context.declareVariable(bindingPrefix + "documentName", new AnyURIValue(src));
        }
        // 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));
        }
    } catch (final XPathException | IOException | PermissionDeniedException e) {
        TriggerStatePerThread.setTriggerRunningState(TriggerStatePerThread.NO_TRIGGER_RUNNING, this, null);
        TriggerStatePerThread.setTransaction(null);
        throw new TriggerException(PREPARE_EXCEPTION_MESSAGE, e);
    }
    // execute the XQuery
    try {
        // TODO : should we provide another contextSet ?
        final NodeSet contextSet = NodeSet.EMPTY_SET;
        service.execute(broker, compiledQuery, contextSet);
        // TODO : should we have a special processing ?
        LOG.debug("Trigger fired for prepare");
    } catch (final XPathException | PermissionDeniedException e) {
        TriggerStatePerThread.setTriggerRunningState(TriggerStatePerThread.NO_TRIGGER_RUNNING, this, null);
        TriggerStatePerThread.setTransaction(null);
        throw new TriggerException(PREPARE_EXCEPTION_MESSAGE, e);
    }
}
Also used : NodeSet(org.exist.dom.persistent.NodeSet) AnyURIValue(org.exist.xquery.value.AnyURIValue) IOException(java.io.IOException) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) DBSource(org.exist.source.DBSource) PermissionDeniedException(org.exist.security.PermissionDeniedException) StringValue(org.exist.xquery.value.StringValue)

Example 3 with StringValue

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

the class TryCatchExpression method addFunctionTrace.

private void addFunctionTrace(final Throwable t) throws XPathException {
    final LocalVariable localVar = new LocalVariable(QN_XQUERY_STACK_TRACE);
    localVar.setSequenceType(new SequenceType(Type.STRING, Cardinality.ZERO_OR_MORE));
    final Sequence trace;
    if (t != null && t instanceof XPathException) {
        final List<XPathException.FunctionStackElement> callStack = ((XPathException) t).getCallStack();
        if (callStack == null) {
            trace = Sequence.EMPTY_SEQUENCE;
        } else {
            final Sequence result = new ValueSequence();
            for (final XPathException.FunctionStackElement elt : callStack) {
                result.add(new StringValue("at " + elt.toString()));
            }
            trace = result;
        }
    } else {
        trace = Sequence.EMPTY_SEQUENCE;
    }
    localVar.setValue(trace);
    context.declareVariableBinding(localVar);
}
Also used : StringValue(org.exist.xquery.value.StringValue)

Example 4 with StringValue

use of org.exist.xquery.value.StringValue 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 5 with StringValue

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

the class GrammarTooling method eval.

/**
 * @see org.exist.xquery.BasicFunction#eval(Sequence[], Sequence)
 */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    final GrammarPool grammarpool = (GrammarPool) config.getProperty(XMLReaderObjectFactory.GRAMMAR_POOL);
    if (isCalledAs("clear-grammar-cache")) {
        final Sequence result = new ValueSequence();
        final int before = countTotalNumberOfGrammar(grammarpool);
        LOG.debug("Clearing {} grammars", before);
        clearGrammarPool(grammarpool);
        final int after = countTotalNumberOfGrammar(grammarpool);
        LOG.debug("Remained {} grammars", after);
        final int delta = before - after;
        result.add(new IntegerValue(delta));
        return result;
    } else if (isCalledAs("show-grammar-cache")) {
        context.pushDocumentContext();
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = writeReport(grammarpool, builder);
            return result;
        } finally {
            context.popDocumentContext();
        }
    } else if (isCalledAs("pre-parse-grammar")) {
        if (args[0].isEmpty()) {
            return Sequence.EMPTY_SEQUENCE;
        }
        // Setup for XML schema support only
        final XMLGrammarPreparser parser = new XMLGrammarPreparser();
        parser.registerPreparser(TYPE_XSD, null);
        final List<Grammar> allGrammars = new ArrayList<>();
        // iterate through the argument sequence and parse url
        for (final SequenceIterator i = args[0].iterate(); i.hasNext(); ) {
            String url = i.nextItem().getStringValue();
            // Fix database urls
            if (url.startsWith("/")) {
                url = "xmldb:exist://" + url;
            }
            LOG.debug("Parsing {}", url);
            // parse XSD grammar
            try {
                if (url.endsWith(".xsd")) {
                    final InputStream is = new URL(url).openStream();
                    final XMLInputSource xis = new XMLInputSource(null, url, url, is, null);
                    final Grammar schema = parser.preparseGrammar(TYPE_XSD, xis);
                    is.close();
                    allGrammars.add(schema);
                } else {
                    throw new XPathException(this, "Only XMLSchemas can be preparsed.");
                }
            } catch (final Exception ex) {
                LOG.debug(ex);
                throw new XPathException(this, ex);
            }
        }
        LOG.debug("Successfully parsed {} grammars.", allGrammars.size());
        // Send all XSD grammars to grammarpool
        Grammar[] grammars = new Grammar[allGrammars.size()];
        grammars = allGrammars.toArray(grammars);
        grammarpool.cacheGrammars(TYPE_XSD, grammars);
        // Construct result to end user
        final ValueSequence result = new ValueSequence();
        for (final Grammar one : grammars) {
            result.add(new StringValue(one.getGrammarDescription().getNamespace()));
        }
        return result;
    } else {
        // oh oh
        LOG.error("function not found error");
        throw new XPathException(this, "function not found");
    }
}
Also used : NodeImpl(org.exist.dom.memtree.NodeImpl) XMLInputSource(org.apache.xerces.xni.parser.XMLInputSource) XPathException(org.exist.xquery.XPathException) InputStream(java.io.InputStream) IntegerValue(org.exist.xquery.value.IntegerValue) ArrayList(java.util.ArrayList) GrammarPool(org.exist.validation.GrammarPool) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) Grammar(org.apache.xerces.xni.grammars.Grammar) URL(java.net.URL) XPathException(org.exist.xquery.XPathException) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) XMLGrammarPreparser(org.apache.xerces.parsers.XMLGrammarPreparser) SequenceIterator(org.exist.xquery.value.SequenceIterator) ValueSequence(org.exist.xquery.value.ValueSequence) StringValue(org.exist.xquery.value.StringValue)

Aggregations

StringValue (org.exist.xquery.value.StringValue)96 Sequence (org.exist.xquery.value.Sequence)49 XPathException (org.exist.xquery.XPathException)40 ValueSequence (org.exist.xquery.value.ValueSequence)27 IOException (java.io.IOException)11 PermissionDeniedException (org.exist.security.PermissionDeniedException)10 Item (org.exist.xquery.value.Item)10 XQueryContext (org.exist.xquery.XQueryContext)8 Txn (org.exist.storage.txn.Txn)7 AnyURIValue (org.exist.xquery.value.AnyURIValue)7 QName (org.exist.dom.QName)6 LockException (org.exist.util.LockException)6 NodeValue (org.exist.xquery.value.NodeValue)6 Path (java.nio.file.Path)5 EXistException (org.exist.EXistException)5 TriggerException (org.exist.collections.triggers.TriggerException)5 DocumentImpl (org.exist.dom.persistent.DocumentImpl)5 StoredNode (org.exist.dom.persistent.StoredNode)5 NotificationService (org.exist.storage.NotificationService)5 MimeType (org.exist.util.MimeType)5