Search in sources :

Example 1 with DynamicQueryContext

use of net.sf.saxon.query.DynamicQueryContext in project camel by apache.

the class XQueryBuilder method createDynamicContext.

/**
     * Creates a dynamic context for the given exchange
     */
protected DynamicQueryContext createDynamicContext(Exchange exchange) throws Exception {
    Configuration config = getConfiguration();
    DynamicQueryContext dynamicQueryContext = new DynamicQueryContext(config);
    Message in = exchange.getIn();
    Item item = null;
    if (ObjectHelper.isNotEmpty(getHeaderName())) {
        item = in.getHeader(getHeaderName(), Item.class);
    } else {
        item = in.getBody(Item.class);
    }
    if (item != null) {
        dynamicQueryContext.setContextItem(item);
    } else {
        Object body = null;
        if (ObjectHelper.isNotEmpty(getHeaderName())) {
            body = in.getHeader(getHeaderName());
        } else {
            body = in.getBody();
        }
        // the underlying input stream, which we need to close to avoid locking files or other resources
        InputStream is = null;
        try {
            Source source;
            // only convert to input stream if really needed
            if (isInputStreamNeeded(exchange)) {
                if (ObjectHelper.isNotEmpty(getHeaderName())) {
                    is = exchange.getIn().getHeader(getHeaderName(), InputStream.class);
                } else {
                    is = exchange.getIn().getBody(InputStream.class);
                }
                source = getSource(exchange, is);
            } else {
                source = getSource(exchange, body);
            }
            // special for bean invocation
            if (source == null) {
                if (body instanceof BeanInvocation) {
                    // if its a null bean invocation then handle that
                    BeanInvocation bi = exchange.getContext().getTypeConverter().convertTo(BeanInvocation.class, body);
                    if (bi.getArgs() != null && bi.getArgs().length == 1 && bi.getArgs()[0] == null) {
                        // its a null argument from the bean invocation so use null as answer
                        source = null;
                    }
                }
            }
            if (source == null) {
                // indicate it was not possible to convert to a Source type
                throw new NoTypeConversionAvailableException(body, Source.class);
            }
            DocumentInfo doc = config.buildDocument(source);
            dynamicQueryContext.setContextItem(doc);
        } finally {
            // can deal if is is null
            IOHelper.close(is);
        }
    }
    configureQuery(dynamicQueryContext, exchange);
    // call the reset if the in message body is StreamCache
    MessageHelper.resetStreamCache(exchange.getIn());
    return dynamicQueryContext;
}
Also used : Item(net.sf.saxon.om.Item) Configuration(net.sf.saxon.Configuration) Message(org.apache.camel.Message) DynamicQueryContext(net.sf.saxon.query.DynamicQueryContext) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) InputStream(java.io.InputStream) BeanInvocation(org.apache.camel.component.bean.BeanInvocation) BytesSource(org.apache.camel.BytesSource) StringSource(org.apache.camel.StringSource) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) SAXSource(javax.xml.transform.sax.SAXSource) StAXSource(javax.xml.transform.stax.StAXSource) DocumentInfo(net.sf.saxon.om.DocumentInfo)

Example 2 with DynamicQueryContext

use of net.sf.saxon.query.DynamicQueryContext in project pentaho-platform by pentaho.

the class XQConnection method executeQuery.

/*
   * (non-Javadoc)
   * 
   * @see org.pentaho.connection.IPentahoConnection#executeQuery(java.lang.String)
   */
public IPentahoResultSet executeQuery(final String query, final String[] columnTypes) throws XPathException {
    XQueryExpression exp = sqc.compileQuery(query);
    DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
    try {
        resultSet = new XQResultSet(this, exp, dynamicContext, columnTypes);
    } catch (XPathException e) {
        if (e.getException() instanceof FileNotFoundException) {
            // $NON-NLS-1$
            logger.error(Messages.getInstance().getString("XQConnection.ERROR_0001_UNABLE_TO_READ", query));
        } else {
            // $NON-NLS-1$
            logger.error(Messages.getInstance().getString("XQConnection.ERROR_0002_XQUERY_EXCEPTION", query), e);
        }
    } catch (Throwable t) {
        // $NON-NLS-1$
        logger.error(Messages.getInstance().getErrorString("XQConnection.ERROR_0002_XQUERY_EXCEPTION", query), t);
    }
    lastQuery = query;
    return resultSet;
}
Also used : DynamicQueryContext(net.sf.saxon.query.DynamicQueryContext) XPathException(net.sf.saxon.trans.XPathException) FileNotFoundException(java.io.FileNotFoundException) XQueryExpression(net.sf.saxon.query.XQueryExpression)

Example 3 with DynamicQueryContext

use of net.sf.saxon.query.DynamicQueryContext in project ph-schematron by phax.

the class XQueryAsXPathFunctionConverter method loadXQuery.

/**
 * Load XQuery functions from an input stream. As this function is supposed to
 * work with Saxon HE, this method allows only for loading full XQuery modules
 * and not for XQuery libraries.
 *
 * @param aXQueryIS
 *        The Input Stream to read from. May not be <code>null</code>. Will be
 *        closed automatically in this method.
 * @return A non-<code>null</code> {@link MapBasedXPathFunctionResolver}
 *         containing all loaded functions.
 * @throws XPathException
 *         if the syntax of the expression is wrong, or if it references
 *         namespaces, variables, or functions that have not been declared, or
 *         any other static error is reported.
 * @throws IOException
 *         if a failure occurs reading the supplied input.
 */
@Nonnull
public MapBasedXPathFunctionResolver loadXQuery(@Nonnull @WillClose final InputStream aXQueryIS) throws XPathException, IOException {
    ValueEnforcer.notNull(aXQueryIS, "XQueryIS");
    try {
        final MapBasedXPathFunctionResolver aFunctionResolver = new MapBasedXPathFunctionResolver();
        // create a Configuration object
        final Configuration aConfiguration = new Configuration();
        final DynamicQueryContext aDynamicQueryContext = new DynamicQueryContext(aConfiguration);
        final StaticQueryContext aStaticQueryCtx = aConfiguration.newStaticQueryContext();
        // The base URI required for resolving within the XQuery
        aStaticQueryCtx.setBaseURI(m_sBaseURL);
        // null == auto detect
        final String sEncoding = null;
        final XQueryExpression exp = aStaticQueryCtx.compileQuery(aXQueryIS, sEncoding);
        final Controller aXQController = exp.newController(aDynamicQueryContext);
        // find all loaded methods and convert them to XPath functions
        final FunctionLibraryList aFuncLibList = exp.getExecutable().getFunctionLibrary();
        for (final FunctionLibrary aFuncLib : aFuncLibList.getLibraryList()) {
            // Ignore all Vendor, System etc. internal libraries
            if (aFuncLib instanceof FunctionLibraryList) {
                // This block works with Saxon HE 9.5.1-x :)
                // This is the custom function library list
                final FunctionLibraryList aRealFuncLib = (FunctionLibraryList) aFuncLib;
                for (final FunctionLibrary aNestedFuncLib : aRealFuncLib.getLibraryList()) {
                    // Currently the user functions are in ExecutableFunctionLibrary
                    if (aNestedFuncLib instanceof ExecutableFunctionLibrary)
                        for (final UserFunction aUserFunc : new IterableIterator<>(((ExecutableFunctionLibrary) aNestedFuncLib).iterateFunctions())) {
                            // Saxon 9.7 changes "getNumberOfArguments" to "getArity"
                            aFunctionResolver.addUniqueFunction(aUserFunc.getFunctionName().getNamespaceBinding().getURI(), aUserFunc.getFunctionName().getLocalPart(), aUserFunc.getArity(), new XPathFunctionFromUserFunction(aConfiguration, aXQController, aUserFunc));
                        }
                }
            } else if (aFuncLib instanceof XQueryFunctionLibrary) {
                // This block works with Saxon HE 9.6.0-x :)
                final XQueryFunctionLibrary aRealFuncLib = (XQueryFunctionLibrary) aFuncLib;
                for (final XQueryFunction aXQueryFunction : new IterableIterator<>(aRealFuncLib.getFunctionDefinitions())) {
                    // Ensure the function is compiled
                    aXQueryFunction.compile();
                    aFunctionResolver.addUniqueFunction(aXQueryFunction.getFunctionName().getNamespaceBinding().getURI(), aXQueryFunction.getFunctionName().getLocalPart(), aXQueryFunction.getNumberOfArguments(), new XPathFunctionFromUserFunction(aConfiguration, aXQController, aXQueryFunction.getUserFunction()));
                }
            }
        }
        return aFunctionResolver;
    } finally {
        StreamHelper.close(aXQueryIS);
    }
}
Also used : FunctionLibraryList(net.sf.saxon.functions.FunctionLibraryList) Configuration(net.sf.saxon.Configuration) XQueryFunctionLibrary(net.sf.saxon.query.XQueryFunctionLibrary) MapBasedXPathFunctionResolver(com.helger.xml.xpath.MapBasedXPathFunctionResolver) XQueryExpression(net.sf.saxon.query.XQueryExpression) ExecutableFunctionLibrary(net.sf.saxon.functions.ExecutableFunctionLibrary) FunctionLibrary(net.sf.saxon.functions.FunctionLibrary) XQueryFunctionLibrary(net.sf.saxon.query.XQueryFunctionLibrary) Controller(net.sf.saxon.Controller) StaticQueryContext(net.sf.saxon.query.StaticQueryContext) ExecutableFunctionLibrary(net.sf.saxon.functions.ExecutableFunctionLibrary) DynamicQueryContext(net.sf.saxon.query.DynamicQueryContext) UserFunction(net.sf.saxon.expr.instruct.UserFunction) XQueryFunction(net.sf.saxon.query.XQueryFunction) Nonnull(javax.annotation.Nonnull)

Example 4 with DynamicQueryContext

use of net.sf.saxon.query.DynamicQueryContext in project camel by apache.

the class XQueryBuilder method evaluateAsDOM.

public Node evaluateAsDOM(Exchange exchange) throws Exception {
    LOG.debug("evaluateAsDOM: {} for exchange: {}", expression, exchange);
    initialize(exchange);
    DOMResult result = new DOMResult();
    DynamicQueryContext context = createDynamicContext(exchange);
    XQueryExpression expression = getExpression();
    expression.pull(context, result, properties);
    return result.getNode();
}
Also used : DOMResult(javax.xml.transform.dom.DOMResult) DynamicQueryContext(net.sf.saxon.query.DynamicQueryContext) XQueryExpression(net.sf.saxon.query.XQueryExpression)

Example 5 with DynamicQueryContext

use of net.sf.saxon.query.DynamicQueryContext in project teiid by teiid.

the class XQueryEvaluator method evaluateXQuery.

public static SaxonXQueryExpression.Result evaluateXQuery(final SaxonXQueryExpression xquery, Object context, Map<String, Object> parameterValues, final RowProcessor processor, CommandContext commandContext) throws TeiidProcessingException, TeiidComponentException {
    DynamicQueryContext dynamicContext = new DynamicQueryContext(xquery.config);
    SaxonXQueryExpression.Result result = new SaxonXQueryExpression.Result();
    try {
        for (Map.Entry<String, Object> entry : parameterValues.entrySet()) {
            try {
                Object value = entry.getValue();
                Sequence s = null;
                if (value instanceof SQLXML) {
                    value = XMLSystemFunctions.convertToSource(value);
                    result.sources.add((Source) value);
                    Source source = wrapStax((Source) value);
                    s = xquery.config.buildDocumentTree(source).getRootNode();
                } else if (value instanceof java.util.Date) {
                    s = XQueryEvaluator.convertToAtomicValue(value);
                } else if (value instanceof BinaryType) {
                    s = new HexBinaryValue(((BinaryType) value).getBytesDirect());
                }
                dynamicContext.setParameter(StructuredQName.fromClarkName(entry.getKey()), s);
            } catch (TransformerException e) {
                throw new TeiidProcessingException(QueryPlugin.Event.TEIID30148, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30148, entry.getKey()));
            }
        }
        if (context != null) {
            Source source = XMLSystemFunctions.convertToSource(context);
            result.sources.add(source);
            source = wrapStax(source);
            if (xquery.contextRoot != null) {
                // create our own filter as this logic is not provided in the free saxon
                AugmentedSource sourceInput = AugmentedSource.makeAugmentedSource(source);
                sourceInput.addFilter(new FilterFactory() {

                    @Override
                    public ProxyReceiver makeFilter(Receiver arg0) {
                        return new PathMapFilter(xquery.contextRoot, arg0);
                    }
                });
                source = sourceInput;
                // use streamable processing instead
                if (xquery.streamingPath != null && processor != null) {
                    if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
                        // $NON-NLS-1$
                        LogManager.logDetail(LogConstants.CTX_DQP, "Using stream processing for evaluation of", xquery.xQueryString);
                    }
                    // set to non-blocking in case default expression evaluation blocks
                    boolean isNonBlocking = commandContext.isNonBlocking();
                    commandContext.setNonBlocking(true);
                    final StreamingTransform myTransform = new StreamingTransform() {

                        public Nodes transform(Element elem) {
                            processor.processRow(XQueryEvaluator.wrap(elem, xquery.config));
                            return NONE;
                        }
                    };
                    Builder builder = new Builder(new SaxonReader(xquery.config, sourceInput), false, new StreamingPathFilter(xquery.streamingPath, xquery.namespaceMap).createNodeFactory(null, myTransform));
                    try {
                        // the builder is hard wired to parse the source, but the api will throw an exception if the stream is null
                        builder.build(FAKE_IS);
                        return result;
                    } catch (ParsingException e) {
                        if (e.getCause() instanceof TeiidRuntimeException) {
                            RelationalNode.unwrapException((TeiidRuntimeException) e.getCause());
                        }
                        throw new TeiidProcessingException(QueryPlugin.Event.TEIID30151, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30151));
                    } catch (IOException e) {
                        throw new TeiidProcessingException(QueryPlugin.Event.TEIID30151, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30151));
                    } finally {
                        if (!isNonBlocking) {
                            commandContext.setNonBlocking(false);
                        }
                    }
                }
            }
            TreeInfo doc;
            try {
                doc = xquery.config.buildDocumentTree(source);
            } catch (XPathException e) {
                throw new TeiidProcessingException(QueryPlugin.Event.TEIID30151, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30151));
            }
            dynamicContext.setContextItem(doc.getRootNode());
        }
        try {
            result.iter = xquery.xQuery.iterator(dynamicContext);
            return result;
        } catch (TransformerException e) {
            throw new TeiidProcessingException(QueryPlugin.Event.TEIID30152, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30152));
        }
    } finally {
        if (result.iter == null) {
            result.close();
        }
    }
}
Also used : XPathException(net.sf.saxon.trans.XPathException) Element(nu.xom.Element) Builder(nu.xom.Builder) TeiidRuntimeException(org.teiid.core.TeiidRuntimeException) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) StAXSource(javax.xml.transform.stax.StAXSource) AugmentedSource(net.sf.saxon.lib.AugmentedSource) FilterFactory(net.sf.saxon.event.FilterFactory) StreamingPathFilter(nux.xom.xquery.StreamingPathFilter) StreamResult(javax.xml.transform.stream.StreamResult) Result(org.teiid.query.xquery.saxon.SaxonXQueryExpression.Result) QueryResult(net.sf.saxon.query.QueryResult) TeiidProcessingException(org.teiid.core.TeiidProcessingException) DynamicQueryContext(net.sf.saxon.query.DynamicQueryContext) ParsingException(nu.xom.ParsingException) TransformerException(javax.xml.transform.TransformerException) BinaryType(org.teiid.core.types.BinaryType) HexBinaryValue(net.sf.saxon.value.HexBinaryValue) Receiver(net.sf.saxon.event.Receiver) ProxyReceiver(net.sf.saxon.event.ProxyReceiver) Sequence(net.sf.saxon.om.Sequence) IOException(java.io.IOException) SQLXML(java.sql.SQLXML) Result(org.teiid.query.xquery.saxon.SaxonXQueryExpression.Result) StreamingTransform(nux.xom.xquery.StreamingTransform) TreeInfo(net.sf.saxon.om.TreeInfo) Map(java.util.Map) AugmentedSource(net.sf.saxon.lib.AugmentedSource) ProxyReceiver(net.sf.saxon.event.ProxyReceiver)

Aggregations

DynamicQueryContext (net.sf.saxon.query.DynamicQueryContext)5 XQueryExpression (net.sf.saxon.query.XQueryExpression)3 Source (javax.xml.transform.Source)2 StAXSource (javax.xml.transform.stax.StAXSource)2 StreamSource (javax.xml.transform.stream.StreamSource)2 Configuration (net.sf.saxon.Configuration)2 XPathException (net.sf.saxon.trans.XPathException)2 MapBasedXPathFunctionResolver (com.helger.xml.xpath.MapBasedXPathFunctionResolver)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 SQLXML (java.sql.SQLXML)1 Map (java.util.Map)1 Nonnull (javax.annotation.Nonnull)1 TransformerException (javax.xml.transform.TransformerException)1 DOMResult (javax.xml.transform.dom.DOMResult)1 DOMSource (javax.xml.transform.dom.DOMSource)1 SAXSource (javax.xml.transform.sax.SAXSource)1 StreamResult (javax.xml.transform.stream.StreamResult)1 Controller (net.sf.saxon.Controller)1