Search in sources :

Example 1 with Sequence

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

the class ResourceFunctionExecutorImpl method execute.

@Override
public Sequence execute(final ResourceFunction resourceFunction, final Iterable<TypedArgumentValue> arguments, final HttpRequest request) throws RestXqServiceException {
    final RestXqServiceCompiledXQueryCache cache = RestXqServiceCompiledXQueryCacheImpl.getInstance();
    CompiledXQuery xquery = null;
    ProcessMonitor processMonitor = null;
    try (final DBBroker broker = getBrokerPool().getBroker()) {
        // ensure we can execute the function before going any further
        checkSecurity(broker, resourceFunction.getXQueryLocation());
        // get a compiled query service from the cache
        xquery = cache.getCompiledQuery(broker, resourceFunction.getXQueryLocation());
        // find the function that we will execute
        final UserDefinedFunction fn = findFunction(xquery, resourceFunction.getFunctionSignature());
        final XQueryContext xqueryContext = xquery.getContext();
        // set the request object - can later be used by the EXQuery Request Module
        xqueryContext.setAttribute(EXQ_REQUEST_ATTR, request);
        // TODO this is a workaround?
        declareVariables(xqueryContext);
        // START workaround: evaluate global variables in modules, as they are reset by XQueryContext.reset()
        final Expression rootExpr = xqueryContext.getRootExpression();
        for (int i = 0; i < rootExpr.getSubExpressionCount(); i++) {
            final Expression subExpr = rootExpr.getSubExpression(i);
            if (subExpr instanceof VariableDeclaration) {
                subExpr.eval(null);
            }
        }
        // END workaround
        // setup monitoring
        processMonitor = broker.getBrokerPool().getProcessMonitor();
        xqueryContext.getProfiler().traceQueryStart();
        processMonitor.queryStarted(xqueryContext.getWatchDog());
        // create a function call
        try (final FunctionReference fnRef = new FunctionReference(new FunctionCall(xqueryContext, fn))) {
            // convert the arguments
            final org.exist.xquery.value.Sequence[] fnArgs = convertToExistFunctionArguments(xqueryContext, fn, arguments);
            // execute the function call
            fnRef.analyze(new AnalyzeContextInfo());
            // if setUid/setGid, determine the effectiveSubject to use for execution
            final Optional<EffectiveSubject> effectiveSubject = getEffectiveSubject(xquery);
            try {
                // switch to effective user if setUid/setGid
                effectiveSubject.ifPresent(broker::pushSubject);
                final org.exist.xquery.value.Sequence result = fnRef.evalFunction(null, null, fnArgs);
                // copy for closure
                final CompiledXQuery xquery1 = xquery;
                // return a sequence adapter which returns the query when it is finished with the results
                return new SequenceAdapter(result, () -> {
                    if (xquery1 != null) {
                        // return the compiled query to the pool
                        cache.returnCompiledQuery(resourceFunction.getXQueryLocation(), xquery1);
                    }
                });
            } finally {
                // switch back from effective user if setUid/setGid
                if (effectiveSubject.isPresent()) {
                    broker.popSubject();
                }
            }
        }
    } catch (final URISyntaxException | EXistException | XPathException | PermissionDeniedException use) {
        // if an error occurred we should return the compiled query
        if (xquery != null) {
            // return the compiled query to the pool
            cache.returnCompiledQuery(resourceFunction.getXQueryLocation(), xquery);
        }
        throw new RestXqServiceException(use.getMessage(), use);
    } finally {
        // clear down monitoring
        if (processMonitor != null) {
            xquery.getContext().getProfiler().traceQueryEnd(xquery.getContext());
            processMonitor.queryCompleted(xquery.getContext().getWatchDog());
        }
    }
}
Also used : RestXqServiceCompiledXQueryCache(org.exist.extensions.exquery.restxq.RestXqServiceCompiledXQueryCache) RestXqServiceException(org.exquery.restxq.RestXqServiceException) SequenceAdapter(org.exist.extensions.exquery.restxq.impl.adapters.SequenceAdapter) URISyntaxException(java.net.URISyntaxException) FunctionReference(org.exist.xquery.value.FunctionReference) EffectiveSubject(org.exist.security.EffectiveSubject) org.exist.xquery(org.exist.xquery) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exquery.xquery.Sequence) EXistException(org.exist.EXistException) ProcessMonitor(org.exist.storage.ProcessMonitor) DBBroker(org.exist.storage.DBBroker) PermissionDeniedException(org.exist.security.PermissionDeniedException)

Example 2 with Sequence

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

the class ResourceFunctionExecutorImpl method convertToExistSequence.

private org.exist.xquery.value.Sequence convertToExistSequence(final XQueryContext xqueryContext, final TypedArgumentValue argument, final int fnParameterType) throws RestXqServiceException, XPathException {
    final org.exist.xquery.value.Sequence sequence = new ValueSequence();
    for (final TypedValue value : (Sequence<Object>) argument.getTypedValue()) {
        final org.exquery.xquery.Type destinationType = TypeAdapter.toExQueryType(fnParameterType);
        final Class destinationClass;
        switch(fnParameterType) {
            case Type.ITEM:
                destinationClass = Item.class;
                break;
            case Type.DOCUMENT:
                // TODO test this
                destinationClass = DocumentImpl.class;
                break;
            case Type.STRING:
                destinationClass = StringValue.class;
                break;
            case Type.INT:
            case Type.INTEGER:
                destinationClass = IntegerValue.class;
                break;
            case Type.FLOAT:
                destinationClass = FloatValue.class;
                break;
            case Type.DOUBLE:
                destinationClass = DoubleValue.class;
                break;
            case Type.DECIMAL:
                destinationClass = DecimalValue.class;
                break;
            case Type.DATE:
                destinationClass = DateValue.class;
                break;
            case Type.DATE_TIME:
                destinationClass = DateTimeValue.class;
                break;
            case Type.TIME:
                destinationClass = TimeValue.class;
                break;
            case Type.QNAME:
                destinationClass = QNameValue.class;
                break;
            case Type.ANY_URI:
                destinationClass = AnyURIValue.class;
                break;
            case Type.BOOLEAN:
                destinationClass = BooleanValue.class;
                break;
            default:
                destinationClass = Item.class;
        }
        final TypedValue<? extends Item> val = convertToType(xqueryContext, argument.getArgumentName(), value, destinationType, destinationClass);
        sequence.add(val.getValue());
    }
    return sequence;
}
Also used : org.exist.xquery(org.exist.xquery) ValueSequence(org.exist.xquery.value.ValueSequence) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exquery.xquery.Sequence) TypedValue(org.exquery.xquery.TypedValue)

Example 3 with Sequence

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

the class ResourceFunctionExecutorImpl method convertToExistFunctionArguments.

/**
 * Creates converts function arguments from EXQuery to eXist-db types
 *
 * @param xqueryContext The XQuery Context of the XQuery containing the Function Call
 * @param fn The Function in the XQuery to create a Function Call for
 * @param arguments The arguments to be passed to the Function when its invoked
 *
 * @return The arguments ready to pass to the Function Call when it is invoked
 */
private org.exist.xquery.value.Sequence[] convertToExistFunctionArguments(final XQueryContext xqueryContext, final UserDefinedFunction fn, final Iterable<TypedArgumentValue> arguments) throws XPathException, RestXqServiceException {
    final List<org.exist.xquery.value.Sequence> fnArgs = new ArrayList<>();
    for (final SequenceType argumentType : fn.getSignature().getArgumentTypes()) {
        final FunctionParameterSequenceType fnParameter = (FunctionParameterSequenceType) argumentType;
        org.exist.xquery.value.Sequence fnArg = null;
        boolean found = false;
        for (final TypedArgumentValue argument : arguments) {
            final String argumentName = argument.getArgumentName();
            if (argumentName != null && argumentName.equals(fnParameter.getAttributeName())) {
                fnArg = convertToExistSequence(xqueryContext, argument, fnParameter.getPrimaryType());
                found = true;
                break;
            }
        }
        if (!found) {
            // value is not always provided, e.g. by PathAnnotation, so use empty sequence
            // TODO do we need to check the cardinality of the receiving arg to make sure it permits ZERO?
            // argumentType.getCardinality();
            // create the empty sequence
            fnArg = org.exist.xquery.value.Sequence.EMPTY_SEQUENCE;
        }
        fnArgs.add(fnArg);
    }
    return fnArgs.toArray(new org.exist.xquery.value.Sequence[0]);
}
Also used : org.exist.xquery(org.exist.xquery) ArrayList(java.util.ArrayList) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exquery.xquery.Sequence) SequenceType(org.exist.xquery.value.SequenceType) FunctionParameterSequenceType(org.exist.xquery.value.FunctionParameterSequenceType) TypedArgumentValue(org.exquery.xquery.TypedArgumentValue) FunctionParameterSequenceType(org.exist.xquery.value.FunctionParameterSequenceType)

Example 4 with Sequence

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

the class RestXqServiceImpl method extractRequestBody.

@Override
protected Sequence extractRequestBody(final HttpRequest request) throws RestXqServiceException {
    // TODO don't use close shield input stream and move parsing of form parameters from HttpServletRequestAdapter into RequestBodyParser
    InputStream is;
    FilterInputStreamCache cache = null;
    try {
        // first, get the content of the request
        is = new CloseShieldInputStream(request.getInputStream());
        if (is.available() <= 0) {
            return null;
        }
        // if marking is not supported, we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt)
        if (!is.markSupported()) {
            cache = FilterInputStreamCacheFactory.getCacheInstance(() -> {
                final Configuration configuration = getBrokerPool().getConfiguration();
                return (String) configuration.getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY);
            }, is);
            is = new CachingFilterInputStream(cache);
        }
        is.mark(Integer.MAX_VALUE);
    } catch (final IOException ioe) {
        throw new RestXqServiceException(RestXqErrorCodes.RQDY0014, ioe);
    }
    Sequence result = null;
    try {
        // was there any POST content?
        if (is != null && is.available() > 0) {
            String contentType = request.getContentType();
            // 1) determine if exists mime database considers this binary data
            if (contentType != null) {
                // strip off any charset encoding info
                if (contentType.contains(";")) {
                    contentType = contentType.substring(0, contentType.indexOf(";"));
                }
                MimeType mimeType = MimeTable.getInstance().getContentType(contentType);
                if (mimeType != null && !mimeType.isXMLType()) {
                    // binary data
                    try {
                        final BinaryValue binaryValue = BinaryValueFromInputStream.getInstance(binaryValueManager, new Base64BinaryValueType(), is);
                        if (binaryValue != null) {
                            result = new SequenceImpl<>(new BinaryTypedValue(binaryValue));
                        }
                    } catch (final XPathException xpe) {
                        throw new RestXqServiceException(RestXqErrorCodes.RQDY0014, xpe);
                    }
                }
            }
            if (result == null) {
                // 2) not binary, try and parse as an XML document
                final DocumentImpl doc = parseAsXml(is);
                if (doc != null) {
                    result = new SequenceImpl<>(new DocumentTypedValue(doc));
                }
            }
            if (result == null) {
                String encoding = request.getCharacterEncoding();
                // 3) not a valid XML document, return a string representation of the document
                if (encoding == null) {
                    encoding = "UTF-8";
                }
                try {
                    // reset the stream, as we need to reuse for string parsing
                    is.reset();
                    final StringValue str = parseAsString(is, encoding);
                    if (str != null) {
                        result = new SequenceImpl<>(new StringTypedValue(str));
                    }
                } catch (final IOException ioe) {
                    throw new RestXqServiceException(RestXqErrorCodes.RQDY0014, ioe);
                }
            }
        }
    } catch (IOException e) {
        throw new RestXqServiceException(e.getMessage());
    } finally {
        if (cache != null) {
            try {
                cache.invalidate();
            } catch (final IOException ioe) {
                LOG.error(ioe.getMessage(), ioe);
            }
        }
        if (is != null) {
            /*
                 * Do NOT close the stream if its a binary value,
                 * because we will need it later for serialization
                 */
            boolean isBinaryType = false;
            if (result != null) {
                try {
                    final Type type = result.head().getType();
                    isBinaryType = (type == Type.BASE64_BINARY || type == Type.HEX_BINARY);
                } catch (final IndexOutOfBoundsException ioe) {
                    LOG.warn("Called head on an empty HTTP Request body sequence", ioe);
                }
            }
            if (!isBinaryType) {
                try {
                    is.close();
                } catch (final IOException ioe) {
                    LOG.error(ioe.getMessage(), ioe);
                }
            }
        }
    }
    if (result != null) {
        return result;
    } else {
        return Sequence.EMPTY_SEQUENCE;
    }
}
Also used : RestXqServiceException(org.exquery.restxq.RestXqServiceException) Configuration(org.exist.util.Configuration) DocumentTypedValue(org.exist.extensions.exquery.xdm.type.impl.DocumentTypedValue) XPathException(org.exist.xquery.XPathException) BinaryValueFromInputStream(org.exist.xquery.value.BinaryValueFromInputStream) CloseShieldInputStream(org.apache.commons.io.input.CloseShieldInputStream) CachingFilterInputStream(org.exist.util.io.CachingFilterInputStream) InputStream(java.io.InputStream) BinaryValue(org.exist.xquery.value.BinaryValue) Base64BinaryValueType(org.exist.xquery.value.Base64BinaryValueType) IOException(java.io.IOException) Sequence(org.exquery.xquery.Sequence) FilterInputStreamCache(org.exist.util.io.FilterInputStreamCache) DocumentImpl(org.exist.dom.memtree.DocumentImpl) MimeType(org.exist.util.MimeType) BinaryTypedValue(org.exist.extensions.exquery.xdm.type.impl.BinaryTypedValue) StringTypedValue(org.exist.extensions.exquery.xdm.type.impl.StringTypedValue) MimeType(org.exist.util.MimeType) Base64BinaryValueType(org.exist.xquery.value.Base64BinaryValueType) Type(org.exquery.xquery.Type) CachingFilterInputStream(org.exist.util.io.CachingFilterInputStream) StringValue(org.exist.xquery.value.StringValue) CloseShieldInputStream(org.apache.commons.io.input.CloseShieldInputStream)

Aggregations

Sequence (org.exquery.xquery.Sequence)4 org.exist.xquery (org.exist.xquery)3 ValueSequence (org.exist.xquery.value.ValueSequence)3 RestXqServiceException (org.exquery.restxq.RestXqServiceException)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 URISyntaxException (java.net.URISyntaxException)1 ArrayList (java.util.ArrayList)1 CloseShieldInputStream (org.apache.commons.io.input.CloseShieldInputStream)1 EXistException (org.exist.EXistException)1 DocumentImpl (org.exist.dom.memtree.DocumentImpl)1 RestXqServiceCompiledXQueryCache (org.exist.extensions.exquery.restxq.RestXqServiceCompiledXQueryCache)1 SequenceAdapter (org.exist.extensions.exquery.restxq.impl.adapters.SequenceAdapter)1 BinaryTypedValue (org.exist.extensions.exquery.xdm.type.impl.BinaryTypedValue)1 DocumentTypedValue (org.exist.extensions.exquery.xdm.type.impl.DocumentTypedValue)1 StringTypedValue (org.exist.extensions.exquery.xdm.type.impl.StringTypedValue)1 EffectiveSubject (org.exist.security.EffectiveSubject)1 PermissionDeniedException (org.exist.security.PermissionDeniedException)1 DBBroker (org.exist.storage.DBBroker)1 ProcessMonitor (org.exist.storage.ProcessMonitor)1