Search in sources :

Example 16 with Sequence

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

Example 17 with Sequence

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

the class Jaxp method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    XMLEntityResolver entityResolver = null;
    GrammarPool grammarPool = null;
    final ValidationReport report = new ValidationReport();
    ContentHandler contenthandler = null;
    MemTreeBuilder instanceBuilder = null;
    InputSource instance = null;
    if (isCalledAs("jaxp-parse")) {
        instanceBuilder = context.getDocumentBuilder();
        // (namespace?)
        contenthandler = new DocumentBuilderReceiver(instanceBuilder, true);
    } else {
        contenthandler = new ValidationContentHandler();
    }
    try {
        report.start();
        // Get initialized parser
        final XMLReader xmlReader = getXMLReader();
        // Setup validation reporting
        xmlReader.setContentHandler(contenthandler);
        xmlReader.setErrorHandler(report);
        // Get inputstream for instance document
        instance = Shared.getInputSource(args[0].itemAt(0), context);
        // Handle catalog
        if (args.length == 2) {
            LOG.debug("No Catalog specified");
        } else if (args[2].isEmpty()) {
            // Use system catalog
            LOG.debug("Using system catalog.");
            final Configuration config = brokerPool.getConfiguration();
            entityResolver = (eXistXMLCatalogResolver) config.getProperty(XMLReaderObjectFactory.CATALOG_RESOLVER);
            setXmlReaderEnitityResolver(xmlReader, entityResolver);
        } else {
            // Get URL for catalog
            final String[] catalogUrls = Shared.getUrls(args[2]);
            final String singleUrl = catalogUrls[0];
            if (singleUrl.endsWith("/")) {
                // Search grammar in collection specified by URL. Just one collection is used.
                LOG.debug("Search for grammar in {}", singleUrl);
                entityResolver = new SearchResourceResolver(catalogUrls[0], brokerPool);
                setXmlReaderEnitityResolver(xmlReader, entityResolver);
            } else if (singleUrl.endsWith(".xml")) {
                LOG.debug("Using catalogs {}", getStrings(catalogUrls));
                entityResolver = new eXistXMLCatalogResolver();
                ((eXistXMLCatalogResolver) entityResolver).setCatalogList(catalogUrls);
                setXmlReaderEnitityResolver(xmlReader, entityResolver);
            } else {
                LOG.error("Catalog URLs should end on / or .xml");
            }
        }
        // Use grammarpool
        final boolean useCache = ((BooleanValue) args[1].itemAt(0)).getValue();
        if (useCache) {
            LOG.debug("Grammar caching enabled.");
            final Configuration config = brokerPool.getConfiguration();
            grammarPool = (GrammarPool) config.getProperty(XMLReaderObjectFactory.GRAMMAR_POOL);
            xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_GRAMMARPOOL, grammarPool);
        }
        // Jaxp document
        LOG.debug("Start parsing document");
        xmlReader.parse(instance);
        LOG.debug("Stopped parsing document");
        // Distill namespace from document
        if (contenthandler instanceof ValidationContentHandler) {
            report.setNamespaceUri(((ValidationContentHandler) contenthandler).getNamespaceUri());
        }
    } catch (final MalformedURLException ex) {
        LOG.error(ex.getMessage());
        report.setException(ex);
    } catch (final IOException ex) {
        LOG.error(ex.getCause());
        report.setException(ex);
    } catch (final Throwable ex) {
        LOG.error(ex);
        report.setException(ex);
    } finally {
        report.stop();
        Shared.closeInputSource(instance);
    }
    // Create response
    if (isCalledAs("jaxp")) {
        final Sequence result = new ValueSequence();
        result.add(new BooleanValue(report.isValid()));
        return result;
    } else /* isCalledAs("jaxp-report or jaxp-parse ") */
    {
        if (report.getThrowable() != null) {
            throw new XPathException(report.getThrowable().getMessage(), report.getThrowable());
        }
        if (contenthandler instanceof DocumentBuilderReceiver) {
            // DocumentBuilderReceiver dbr = (DocumentBuilderReceiver) contenthandler;
            return instanceBuilder.getDocument().getNode(0);
        } else {
            context.pushDocumentContext();
            try {
                final MemTreeBuilder builder = context.getDocumentBuilder();
                return Shared.writeReport(report, builder);
            } finally {
                context.popDocumentContext();
            }
        }
    }
}
Also used : ValidationContentHandler(org.exist.validation.ValidationContentHandler) InputSource(org.xml.sax.InputSource) SearchResourceResolver(org.exist.validation.resolver.SearchResourceResolver) MalformedURLException(java.net.MalformedURLException) org.exist.validation.resolver.eXistXMLCatalogResolver(org.exist.validation.resolver.eXistXMLCatalogResolver) Configuration(org.exist.util.Configuration) XPathException(org.exist.xquery.XPathException) XMLEntityResolver(org.apache.xerces.xni.parser.XMLEntityResolver) GrammarPool(org.exist.validation.GrammarPool) IOException(java.io.IOException) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) ContentHandler(org.xml.sax.ContentHandler) ValidationContentHandler(org.exist.validation.ValidationContentHandler) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) ValidationReport(org.exist.validation.ValidationReport) BooleanValue(org.exist.xquery.value.BooleanValue) ValueSequence(org.exist.xquery.value.ValueSequence) XMLReader(org.xml.sax.XMLReader)

Example 18 with Sequence

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

the class LockFunction method eval.

/* (non-Javadoc)
     * @see org.exist.xquery.Function#eval(org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
     */
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
    final Sequence docsArg = getArgument(0).eval(contextSequence, contextItem);
    final DocumentSet docs = docsArg.getDocumentSet();
    try (final ManagedLocks<ManagedDocumentLock> managedLocks = docs.lock(context.getBroker(), exclusive)) {
        return getArgument(1).eval(contextSequence, contextItem);
    } catch (final LockException e) {
        throw new XPathException(this, "Could not lock document set", e);
    }
}
Also used : ManagedDocumentLock(org.exist.storage.lock.ManagedDocumentLock) LockException(org.exist.util.LockException) Sequence(org.exist.xquery.value.Sequence) DocumentSet(org.exist.dom.persistent.DocumentSet)

Example 19 with Sequence

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

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

the class IndexType method eval.

/*
     * (non-Javadoc)
     * 
     * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[],
     *      org.exist.xquery.value.Sequence)
     */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().start(this);
        context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
        if (contextSequence != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
        }
    }
    Sequence result;
    if (args[0].isEmpty()) {
        result = Sequence.EMPTY_SEQUENCE;
    } else {
        final NodeSet nodes = args[0].toNodeSet();
        // Remember it is the default value when no index is defined
        if (nodes.getIndexType() == Type.ANY_TYPE) {
            result = Sequence.EMPTY_SEQUENCE;
        } else {
            result = new StringValue(Type.getTypeName(nodes.getIndexType()));
        }
    }
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().end(this, "", result);
    }
    return result;
}
Also used : NodeSet(org.exist.dom.persistent.NodeSet) Sequence(org.exist.xquery.value.Sequence) StringValue(org.exist.xquery.value.StringValue)

Aggregations

Sequence (org.exist.xquery.value.Sequence)427 DBBroker (org.exist.storage.DBBroker)179 BrokerPool (org.exist.storage.BrokerPool)158 Test (org.junit.Test)114 XQuery (org.exist.xquery.XQuery)108 XPathException (org.exist.xquery.XPathException)86 Txn (org.exist.storage.txn.Txn)81 Item (org.exist.xquery.value.Item)68 ValueSequence (org.exist.xquery.value.ValueSequence)55 StringValue (org.exist.xquery.value.StringValue)49 Source (org.exist.source.Source)45 QName (org.exist.dom.QName)42 StringSource (org.exist.source.StringSource)42 SequenceIterator (org.exist.xquery.value.SequenceIterator)40 StringInputSource (org.exist.util.StringInputSource)37 CompiledXQuery (org.exist.xquery.CompiledXQuery)36 XQueryContext (org.exist.xquery.XQueryContext)35 IntegerValue (org.exist.xquery.value.IntegerValue)33 InputSource (org.xml.sax.InputSource)23 Diff (org.xmlunit.diff.Diff)21