Search in sources :

Example 6 with XPathException

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

the class JSONSerializer method serialize.

public void serialize(Sequence sequence, Writer writer) throws SAXException {
    JsonFactory factory = new JsonFactory();
    try {
        JsonGenerator generator = factory.createGenerator(writer);
        generator.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
        if ("yes".equals(outputProperties.getProperty(OutputKeys.INDENT, "no"))) {
            generator.useDefaultPrettyPrinter();
        }
        if ("yes".equals(outputProperties.getProperty(EXistOutputKeys.ALLOW_DUPLICATE_NAMES, "yes"))) {
            generator.enable(JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION);
        } else {
            generator.disable(JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION);
        }
        serializeSequence(sequence, generator);
        generator.close();
    } catch (IOException | XPathException e) {
        throw new SAXException(e.getMessage(), e);
    }
}
Also used : XPathException(org.exist.xquery.XPathException) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException)

Example 7 with XPathException

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

the class BinaryDoc method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    final Sequence emptyParamReturnValue = (isCalledAs(FS_BINARY_DOC_NAME) || isCalledAs(FS_BINARY_DOC_CONTENT_DIGEST_NAME)) ? Sequence.EMPTY_SEQUENCE : BooleanValue.FALSE;
    if (args[0].isEmpty()) {
        return emptyParamReturnValue;
    }
    final String path = args[0].getStringValue();
    try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(XmldbURI.xmldbUriFor(path), LockMode.READ_LOCK)) {
        if (lockedDoc == null) {
            return emptyParamReturnValue;
        }
        final DocumentImpl doc = lockedDoc.getDocument();
        if (doc.getResourceType() != DocumentImpl.BINARY_FILE) {
            return emptyParamReturnValue;
        } else if (isCalledAs(FS_BINARY_DOC_NAME)) {
            try (final Txn transaction = context.getBroker().continueOrBeginTransaction()) {
                final BinaryDocument bin = (BinaryDocument) doc;
                final InputStream is = context.getBroker().getBinaryResource(transaction, bin);
                final Base64BinaryDocument b64doc = Base64BinaryDocument.getInstance(context, is);
                b64doc.setUrl(path);
                transaction.commit();
                return b64doc;
            }
        } else if (isCalledAs(FS_BINARY_DOC_CONTENT_DIGEST_NAME)) {
            final String algorithm = args[1].getStringValue();
            final DigestType digestType;
            try {
                digestType = DigestType.forCommonName(algorithm);
            } catch (final IllegalArgumentException e) {
                throw new XPathException(this, "Invalid algorithm: " + algorithm, e);
            }
            try (final Txn transaction = context.getBroker().getBrokerPool().getTransactionManager().beginTransaction()) {
                final BinaryDocument bin = (BinaryDocument) doc;
                final MessageDigest messageDigest = context.getBroker().getBinaryResourceContentDigest(transaction, bin, digestType);
                final InputStream is = new UnsynchronizedByteArrayInputStream(messageDigest.getValue());
                final Sequence result = BinaryValueFromInputStream.getInstance(context, new HexBinaryValueType(), is);
                transaction.commit();
                return result;
            }
        } else {
            return BooleanValue.TRUE;
        }
    } catch (final URISyntaxException e) {
        logger.error("Invalid resource URI", e);
        throw new XPathException(this, "Invalid resource uri", e);
    } catch (final PermissionDeniedException e) {
        logger.error("{}: permission denied to read resource", path, e);
        throw new XPathException(this, path + ": permission denied to read resource");
    } catch (final IOException | TransactionException e) {
        logger.error("{}: I/O error while reading resource", path, e);
        throw new XPathException(this, path + ": I/O error while reading resource", e);
    }
}
Also used : XPathException(org.exist.xquery.XPathException) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) InputStream(java.io.InputStream) Txn(org.exist.storage.txn.Txn) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) BinaryDocument(org.exist.dom.persistent.BinaryDocument) TransactionException(org.exist.storage.txn.TransactionException) DigestType(org.exist.util.crypto.digest.DigestType) LockedDocument(org.exist.dom.persistent.LockedDocument) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) PermissionDeniedException(org.exist.security.PermissionDeniedException) MessageDigest(org.exist.util.crypto.digest.MessageDigest)

Example 8 with XPathException

use of org.exist.xquery.XPathException 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 9 with XPathException

use of org.exist.xquery.XPathException 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)

Example 10 with XPathException

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

the class Jaxv method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // Check input parameters
    if (args.length != 2 && args.length != 3) {
        return Sequence.EMPTY_SEQUENCE;
    }
    final ValidationReport report = new ValidationReport();
    StreamSource instance = null;
    StreamSource[] grammars = null;
    String schemaLang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
    try {
        report.start();
        // Get inputstream for instance document
        instance = Shared.getStreamSource(args[0].itemAt(0), context);
        // Validate using resource speciefied in second parameter
        grammars = Shared.getStreamSource(args[1], context);
        // Check input
        for (final StreamSource grammar : grammars) {
            final String grammarUrl = grammar.getSystemId();
            if (grammarUrl != null && !grammarUrl.endsWith(".xsd") && !grammarUrl.endsWith(".rng")) {
                throw new XPathException("Only XML schemas (.xsd) and RELAXNG grammars (.rng) are supported" + ", depending on the used XML parser.");
            }
        }
        // Fetch third argument if available, and override defailt value
        if (args.length == 3) {
            schemaLang = args[2].getStringValue();
        }
        // Get language specific factory
        SchemaFactory factory = null;
        try {
            factory = SchemaFactory.newInstance(schemaLang);
        } catch (final IllegalArgumentException ex) {
            final String msg = "Schema language '" + schemaLang + "' is not supported. " + ex.getMessage();
            LOG.error(msg);
            throw new XPathException(msg);
        }
        // Create grammar
        final Schema schema = factory.newSchema(grammars);
        // Setup validator
        final Validator validator = schema.newValidator();
        validator.setErrorHandler(report);
        // Perform validation
        validator.validate(instance);
    } catch (final MalformedURLException ex) {
        LOG.error(ex.getMessage());
        report.setException(ex);
    } catch (final Throwable ex) {
        LOG.error(ex);
        report.setException(ex);
    } finally {
        report.stop();
        Shared.closeStreamSource(instance);
        Shared.closeStreamSources(grammars);
    }
    // Create response
    if (isCalledAs("jaxv")) {
        final Sequence result = new ValueSequence();
        result.add(new BooleanValue(report.isValid()));
        return result;
    } else /* isCalledAs("jaxv-report") */
    {
        context.pushDocumentContext();
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = Shared.writeReport(report, builder);
            return result;
        } finally {
            context.popDocumentContext();
        }
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) MalformedURLException(java.net.MalformedURLException) NodeImpl(org.exist.dom.memtree.NodeImpl) XPathException(org.exist.xquery.XPathException) StreamSource(javax.xml.transform.stream.StreamSource) Schema(javax.xml.validation.Schema) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) ValidationReport(org.exist.validation.ValidationReport) BooleanValue(org.exist.xquery.value.BooleanValue) ValueSequence(org.exist.xquery.value.ValueSequence) Validator(javax.xml.validation.Validator)

Aggregations

XPathException (org.exist.xquery.XPathException)306 Sequence (org.exist.xquery.value.Sequence)86 IOException (java.io.IOException)61 SAXException (org.xml.sax.SAXException)43 StringValue (org.exist.xquery.value.StringValue)40 PermissionDeniedException (org.exist.security.PermissionDeniedException)34 NodeValue (org.exist.xquery.value.NodeValue)34 DBBroker (org.exist.storage.DBBroker)32 IntegerValue (org.exist.xquery.value.IntegerValue)32 ValueSequence (org.exist.xquery.value.ValueSequence)27 Item (org.exist.xquery.value.Item)26 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)24 EXistException (org.exist.EXistException)23 Path (java.nio.file.Path)22 XmldbURI (org.exist.xmldb.XmldbURI)22 BrokerPool (org.exist.storage.BrokerPool)21 Txn (org.exist.storage.txn.Txn)21 XQueryContext (org.exist.xquery.XQueryContext)21 Element (org.w3c.dom.Element)21 XQuery (org.exist.xquery.XQuery)20