Package org.exist.memtree

Examples of org.exist.memtree.MemTreeBuilder


        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();
            contenthandler = new DocumentBuilderReceiver(instanceBuilder, true); // (namespace?)

        } 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.GRAMMER_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 ((DocumentImpl) instanceBuilder.getDocument()).getNode(0);

            } else {

                final MemTreeBuilder builder = context.getDocumentBuilder();
                final NodeImpl result = Shared.writeReport(report, builder);
                return result;
            }

        }
View Full Code Here


                {adminPass = args[1].getStringValue();}
        String adminPassAfter = null;
        if (args[2].hasOne())
                {adminPassAfter = args[2].getStringValue();}

        MemTreeBuilder builder = null;
        if (NAME.equals( mySignature.getName() )) {
            builder = context.getDocumentBuilder();
          builder.startDocument();
          builder.startElement(IMPORT_ELEMENT, null);
        }
       
        try {
          final SystemImport restore = new SystemImport(context.getDatabase());
            final RestoreListener listener = new XMLRestoreListener(builder);
            restore.restore(listener, org.exist.security.SecurityManager.DBA_USER, adminPass, adminPassAfter, new File(dirOrFile), XmldbURI.EMBEDDED_SERVER_URI.toString());
        } catch (final Exception e) {
            throw new XPathException(this, "restore failed with exception: " + e.getMessage(), e);
        }
       
        if (builder == null) {
          return Sequence.EMPTY_SEQUENCE;
        } else {
          builder.endElement();
          builder.endDocument();
          return (NodeValue) builder.getDocument().getDocumentElement();
        }
    }
View Full Code Here

            final Sequence result = new ValueSequence();
            result.add(new BooleanValue(report.isValid()));
            return result;

        } else  /* isCalledAs("jing-report") */{
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = Shared.writeReport(report, builder);
            return result;
        }
    }
View Full Code Here

          {incremental = args[1].effectiveBooleanValue();}
        boolean zip = false;
        if (args[2].hasOne())
          {zip = args[2].effectiveBooleanValue();}
       
        MemTreeBuilder builder = null;
        if (NAME.equals( mySignature.getName() )) {
          builder = context.getDocumentBuilder();
          builder.startDocument();
          builder.startElement(EXPORT_ELEMENT, null);
        }
       
        try {
          final SystemExport export = new SystemExport(context.getBroker(), new Callback(builder), null, true);
            export.export(dirOrFile, incremental, zip, null);
        } catch (final Exception e) {
            throw new XPathException(this, "restore failed with exception: " + e.getMessage(), e);
        }
        if (builder == null) {
          return Sequence.EMPTY_SEQUENCE;
        } else {
          builder.endElement();
          builder.endDocument();
          return (NodeValue) builder.getDocument().getDocumentElement();
        }
    }
View Full Code Here

        try {
            final Sequence contentSeq = content.eval(contextSequence, contextItem);
            if (contentSeq.isEmpty())
                {result = Sequence.EMPTY_SEQUENCE;}
            else {
                final MemTreeBuilder builder = context.getDocumentBuilder();
                context.proceed(this, builder);
                final StringBuilder buf = new StringBuilder();
                for(final SequenceIterator i = contentSeq.iterate(); i.hasNext(); ) {
                    context.proceed(this, builder);
                    final Item next = i.nextItem();
                    if(buf.length() > 0)
                        {buf.append(' ');}
                    buf.append(next.toString());
                }
                if (buf.indexOf("--") != Constants.STRING_NOT_FOUND ||
                        buf.toString().endsWith("-")) {
                    throw new XPathException(this, ErrorCodes.XQDY0072,
                        "'" + buf.toString() + "' is not a valid comment");
                }
                final int nodeNr = builder.comment(buf.toString());
                result = builder.getDocument().getNode(nodeNr);
            }
        } finally {
            if (newDocumentContext)
                {context.popDocumentContext();}
        }
View Full Code Here

     * @param parser Parser to read xml elements from
     * @return item
     * @throws XMLStreamException
     */
    public static Item streamToDOM(int rootType, XMLStreamReader parser) throws XMLStreamException {
        final MemTreeBuilder builder = new MemTreeBuilder();
        builder.startDocument();
        int event;
        boolean finish = false;
        while ((event = parser.next()) != XMLStreamConstants.END_DOCUMENT) {
            switch (event) {
                case XMLStreamConstants.START_ELEMENT :
                    final AttributesImpl attribs = new AttributesImpl();
                    for (int i = 0; i < parser.getAttributeCount(); i++) {
                        final javax.xml.namespace.QName qn = parser.getAttributeName(i);
                        attribs.addAttribute(qn.getNamespaceURI(), qn.getLocalPart(), qn.getPrefix() + ':' + qn.getLocalPart(),
                                parser.getAttributeType(i), parser.getAttributeValue(i));
                    }
                   builder.startElement(QName.fromJavaQName(parser.getName()), attribs);
//                    for (int i = 0; i < parser.getNamespaceCount(); i++) {
//                        builder.namespaceNode(parser.getNamespacePrefix(i), parser.getNamespaceURI(i));
//                    }
                    break;
                case XMLStreamConstants.END_ELEMENT :
                    if (NAMESPACE.equals(parser.getNamespaceURI()) && VALUE_ELEMENT.equals(parser.getLocalName()))
                        {finish = true;}
                    else
                        {builder.endElement();}
                    break;
                case XMLStreamConstants.CHARACTERS :
                    builder.characters(parser.getText());
                    break;
            }
            if (finish) {break;}
        }
        builder.endDocument();
        if (rootType == Type.DOCUMENT)
            {return builder.getDocument();}
        else if (rootType == Type.ELEMENT)
            {return (NodeImpl) builder.getDocument().getDocumentElement();}
        else
            {return (NodeImpl) builder.getDocument().getFirstChild();}
    }
View Full Code Here

    public static Node streamToNode(Reader reader) throws XMLStreamException {
      final XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        factory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
        final XMLStreamReader parser = factory.createXMLStreamReader(reader);
        final MemTreeBuilder builder = new MemTreeBuilder();
        builder.startDocument();
        int event;
        boolean finish = false;
        while ((event = parser.next()) != XMLStreamConstants.END_DOCUMENT) {
            switch (event) {
                case XMLStreamConstants.START_ELEMENT :
                    final AttributesImpl attribs = new AttributesImpl();
                    for (int i = 0; i < parser.getAttributeCount(); i++) {
                        final javax.xml.namespace.QName qn = parser.getAttributeName(i);
                        attribs.addAttribute(qn.getNamespaceURI(), qn.getLocalPart(), qn.getPrefix() + ':' + qn.getLocalPart(),
                                parser.getAttributeType(i), parser.getAttributeValue(i));
                    }
                   builder.startElement(QName.fromJavaQName(parser.getName()), attribs);
//                    for (int i = 0; i < parser.getNamespaceCount(); i++) {
//                        builder.namespaceNode(parser.getNamespacePrefix(i), parser.getNamespaceURI(i));
//                    }
                    break;
                case XMLStreamConstants.END_ELEMENT :
                    if (NAMESPACE.equals(parser.getNamespaceURI()) && VALUE_ELEMENT.equals(parser.getLocalName()))
                        {finish = true;}
                    else
                        {builder.endElement();}
                    break;
                case XMLStreamConstants.CHARACTERS :
                    builder.characters(parser.getText());
                    break;
            }
            if (finish) {break;}
        }
        builder.endDocument();
        return builder.getDocument().getDocumentElement();
    }
View Full Code Here

                "CONTEXT ITEM", contextItem.toSequence());}
        }
        if (newDocumentContext)
            {context.pushDocumentContext();}
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            context.proceed(this, builder);
            final Sequence nameSeq = name.eval(contextSequence, contextItem);
            //TODO : get rid of getLength()
            if (!nameSeq.hasOne())
                {throw new XPathException(this, ErrorCodes.XPTY0004,
                    "The name expression should evaluate to a single value");}
            final Item nameItem = nameSeq.itemAt(0);
            if (!(nameItem.getType() == Type.STRING || nameItem.getType() == Type.NCNAME ||
                    nameItem.getType() == Type.UNTYPED_ATOMIC))
                {throw new XPathException(this, ErrorCodes.XPTY0004,
                        "The name expression should evaluate to a " + Type.getTypeName(Type.STRING) +
                        " or a " + Type.getTypeName(Type.NCNAME) +
                        " or a " + Type.getTypeName(Type.UNTYPED_ATOMIC) +
                        ". Got: " + Type.getTypeName(nameItem.getType()));}
            if(!XMLChar.isValidNCName(nameSeq.getStringValue()))
                {throw new XPathException(this, ErrorCodes.XQDY0041,
                    nameSeq.getStringValue() + "' is not a valid processing instruction name", nameSeq);}
            if (nameSeq.getStringValue().equalsIgnoreCase("XML"))
                {throw new XPathException(this, ErrorCodes.XQDY0064,
                    nameSeq.getStringValue() + "' is not a valid processing instruction name", nameSeq);}
            String contentString;
            final Sequence contentSeq = content.eval(contextSequence, contextItem);
            if (contentSeq.isEmpty())
          {contentString = "";}
            else {
                final StringBuilder buf = new StringBuilder();
                for(final SequenceIterator i = contentSeq.iterate(); i.hasNext(); ) {
                    context.proceed(this, builder);
                    final Item next = i.nextItem();
                    if(buf.length() > 0)
                        {buf.append(' ');}
                    buf.append(next.getStringValue());
                }
                while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0)))
                    buf.deleteCharAt(0);
                contentString = buf.toString();
            }
            if (contentString.indexOf("?>") != Constants.STRING_NOT_FOUND)
                {throw new XPathException(this, ErrorCodes.XQDY0026, contentString + "' is not a valid processing intruction content", contentSeq);}
            final int nodeNo = builder.processingInstruction(nameSeq.getStringValue(), contentString);
            final Sequence result = ((DocumentImpl)builder.getDocument()).getNode(nodeNo);
            if (context.getProfiler().isEnabled())
                {context.getProfiler().end(this, "", result);}
            return result;
        } finally {
            if (newDocumentContext)
View Full Code Here

                {context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);}
            if (contextItem != null)
                {context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());}
        }
       
        final MemTreeBuilder builder = context.getDocumentBuilder();
    context.proceed(this, builder);

        final Sequence prefixSeq = qnameExpr.eval(contextSequence, contextItem);
        if (!(Type.subTypeOf(prefixSeq.getItemType(), Type.STRING) || prefixSeq.getItemType() == Type.UNTYPED_ATOMIC)) {
            throw new XPathException(this, ErrorCodes.XPTY0004, "Prefix needs to be xs:string or xs:untypedAtomic");
        }
        String prefix = "";
        if (!prefixSeq.isEmpty()) {
            prefix = prefixSeq.getStringValue();
            if (!(prefix.length() == 0 || XMLChar.isValidNCName(prefix))) {
                throw new XPathException(this, ErrorCodes.XQDY0074, "Prefix cannot be cast to xs:NCName");
            }
        }
        final Sequence uriSeq = content.eval(contextSequence, contextItem);
        final String value = uriSeq.getStringValue();

        if (prefix.equals("xmlns")) {
            throw new XPathException(this, ErrorCodes.XQDY0101, "Cannot bind xmlns prefix");
        } else if (prefix.equals("xml") && !value.equals(Namespaces.XML_NS)) {
            throw new XPathException(this, ErrorCodes.XQDY0101, "Cannot bind xml prefix to another namespace");
        } else if (value.equals(Namespaces.XML_NS) && !prefix.equals("xml")) {
            throw new XPathException(this, ErrorCodes.XQDY0101, "Cannot bind prefix to XML namespace");
        } else if (value.equals(Namespaces.XMLNS_NS)) {
            throw new XPathException(this, ErrorCodes.XQDY0101, "Cannot bind prefix to xmlns namespace");
        } else if (value.length() == 0) {
            throw new XPathException(this, ErrorCodes.XQDY0101, "Cannot bind prefix to empty or zero-length namespace");
        }

        //context.declareInScopeNamespace(prefix, value);
        final int nodeNr = builder.namespaceNode(prefix, value);
        final Sequence result = ((DocumentImpl)builder.getDocument()).getNamespaceNode(nodeNr);
       
        if (context.getProfiler().isEnabled())
            {context.getProfiler().end(this, "", result);}
       
        return result;
View Full Code Here

TOP

Related Classes of org.exist.memtree.MemTreeBuilder

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.