Search in sources :

Example 1 with QName

use of org.exist.dom.QName in project exist by eXist-db.

the class SystemExport method writeXML.

/**
 * Serialize a document to XML, based on {@link XMLStreamReader}.
 *
 * @param doc      the document to serialize
 * @param receiver the output handler
 */
private void writeXML(final DocumentImpl doc, final Receiver receiver) {
    try {
        char[] ch;
        int nsdecls;
        final NamespaceSupport nsSupport = new NamespaceSupport();
        final NodeList children = doc.getChildNodes();
        final DocumentType docType = doc.getDoctype();
        if (docType != null) {
            receiver.documentType(docType.getName(), docType.getPublicId(), docType.getSystemId());
        }
        for (int i = 0; i < children.getLength(); i++) {
            final StoredNode child = (StoredNode) children.item(i);
            final int thisLevel = child.getNodeId().getTreeLevel();
            final int childLevel = child.getNodeType() == Node.ELEMENT_NODE ? thisLevel + 1 : thisLevel;
            final XMLStreamReader reader = broker.getXMLStreamReader(child, false);
            while (reader.hasNext()) {
                final int status = reader.next();
                switch(status) {
                    case XMLStreamReader.START_DOCUMENT:
                    case XMLStreamReader.END_DOCUMENT:
                        break;
                    case XMLStreamReader.START_ELEMENT:
                        nsdecls = reader.getNamespaceCount();
                        for (int ni = 0; ni < nsdecls; ni++) {
                            receiver.startPrefixMapping(reader.getNamespacePrefix(ni), reader.getNamespaceURI(ni));
                        }
                        final AttrList attribs = new AttrList();
                        for (int j = 0; j < reader.getAttributeCount(); j++) {
                            final QName qn = new QName(reader.getAttributeLocalName(j), reader.getAttributeNamespace(j), reader.getAttributePrefix(j));
                            attribs.addAttribute(qn, reader.getAttributeValue(j));
                        }
                        receiver.startElement(new QName(reader.getLocalName(), reader.getNamespaceURI(), reader.getPrefix()), attribs);
                        break;
                    case XMLStreamReader.END_ELEMENT:
                        receiver.endElement(new QName(reader.getLocalName(), reader.getNamespaceURI(), reader.getPrefix()));
                        nsdecls = reader.getNamespaceCount();
                        for (int ni = 0; ni < nsdecls; ni++) {
                            receiver.endPrefixMapping(reader.getNamespacePrefix(ni));
                        }
                        final NodeId otherId = (NodeId) reader.getProperty(ExtendedXMLStreamReader.PROPERTY_NODE_ID);
                        final int otherLevel = otherId.getTreeLevel();
                        if (childLevel != thisLevel && otherLevel == thisLevel) {
                            // exit-while
                            break;
                        }
                        break;
                    case XMLStreamReader.CHARACTERS:
                        receiver.characters(reader.getText());
                        break;
                    case XMLStreamReader.CDATA:
                        ch = reader.getTextCharacters();
                        receiver.cdataSection(ch, 0, ch.length);
                        break;
                    case XMLStreamReader.COMMENT:
                        ch = reader.getTextCharacters();
                        receiver.comment(ch, 0, ch.length);
                        break;
                    case XMLStreamReader.PROCESSING_INSTRUCTION:
                        receiver.processingInstruction(reader.getPITarget(), reader.getPIData());
                        break;
                }
                if (child.getNodeType() == Node.COMMENT_NODE || child.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
                    break;
                }
            }
            nsSupport.reset();
        }
    } catch (final IOException | SAXException | XMLStreamException e) {
        e.printStackTrace();
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) ExtendedXMLStreamReader(org.exist.stax.ExtendedXMLStreamReader) QName(org.exist.dom.QName) NodeList(org.w3c.dom.NodeList) NamespaceSupport(org.xml.sax.helpers.NamespaceSupport) DocumentType(org.w3c.dom.DocumentType) SAXException(org.xml.sax.SAXException) AttrList(org.exist.util.serializer.AttrList) XMLStreamException(javax.xml.stream.XMLStreamException) NodeId(org.exist.numbering.NodeId)

Example 2 with QName

use of org.exist.dom.QName in project exist by eXist-db.

the class ListBackups method eval.

public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    if (!context.getEffectiveUser().hasDbaRole()) {
        throw new XPathException("You must be a DBA to list available backups");
    }
    final String exportDir = args[0].getStringValue();
    Path dir = Paths.get(exportDir);
    if (!dir.isAbsolute()) {
        dir = ((Path) context.getBroker().getConfiguration().getProperty(BrokerPool.PROPERTY_DATA_DIR)).resolve(exportDir);
    }
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        final int nodeNr = builder.startElement(DIRECTORY_ELEMENT, null);
        if (Files.isDirectory(dir) && Files.isReadable(dir)) {
            final Pattern pattern = Pattern.compile(BackupDirectory.FILE_REGEX);
            final Matcher matcher = pattern.matcher("");
            final List<Path> files = FileUtils.list(dir);
            for (final Path file : files) {
                matcher.reset(FileUtils.fileName(file));
                if (matcher.matches()) {
                    final BackupDescriptor descriptor;
                    try {
                        if (FileUtils.fileName(file).endsWith(".zip")) {
                            descriptor = new ZipArchiveBackupDescriptor(file);
                        } else {
                            final Path descriptorFile = file.resolve("db").resolve(BackupDescriptor.COLLECTION_DESCRIPTOR);
                            descriptor = new FileSystemBackupDescriptor(file, descriptorFile);
                        }
                        final Properties properties = descriptor.getProperties();
                        if (properties != null) {
                            final AttributesImpl attrs = new AttributesImpl();
                            attrs.addAttribute("", "file", "file", "CDATA", FileUtils.fileName(file));
                            builder.startElement(BACKUP_ELEMENT, attrs);
                            for (final Object o : properties.keySet()) {
                                final String key = o.toString();
                                builder.startElement(new QName(key, Namespaces.EXIST_NS, ""), null);
                                builder.characters((String) properties.get(key));
                                builder.endElement();
                            }
                            builder.endElement();
                        }
                    } catch (final IOException e) {
                    }
                }
            }
        }
        builder.endElement();
        return (builder.getDocument().getNode(nodeNr));
    } catch (final IOException ioe) {
        throw new XPathException(this, ioe);
    } finally {
        context.popDocumentContext();
    }
}
Also used : Path(java.nio.file.Path) Pattern(java.util.regex.Pattern) ZipArchiveBackupDescriptor(org.exist.backup.ZipArchiveBackupDescriptor) Matcher(java.util.regex.Matcher) QName(org.exist.dom.QName) IOException(java.io.IOException) Properties(java.util.Properties) FileSystemBackupDescriptor(org.exist.backup.FileSystemBackupDescriptor) ZipArchiveBackupDescriptor(org.exist.backup.ZipArchiveBackupDescriptor) BackupDescriptor(org.exist.backup.BackupDescriptor) AttributesImpl(org.xml.sax.helpers.AttributesImpl) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) FileSystemBackupDescriptor(org.exist.backup.FileSystemBackupDescriptor)

Example 3 with QName

use of org.exist.dom.QName in project exist by eXist-db.

the class Configurator method serializeByReference.

protected static void serializeByReference(final Configurable instance, final SAXSerializer serializer, final String fieldAsElementName, final String referenceBy) throws SAXException {
    Object value = ((ReferenceImpl) instance).getName();
    // final Configurable resolved = ((ReferenceImpl) instance).resolve();
    // final Method getMethod = searchForGetMethod(resolved.getClass(), referenceBy);
    // Object value;
    // 
    // try {
    // value = getMethod.invoke(resolved);
    // 
    // } catch (final IllegalArgumentException iae) {
    // LOG.error(iae.getMessage(), iae);
    // //TODO : throw exception ? -pb
    // return;
    // 
    // } catch (final IllegalAccessException iae) {
    // LOG.error(iae.getMessage(), iae);
    // //TODO : throw exception ? -pb
    // return;
    // 
    // } catch (final InvocationTargetException ite) {
    // LOG.error(ite.getMessage(), ite);
    // //TODO : throw exception ? -pb
    // return;
    // }
    final QName qnConfig = new QName(fieldAsElementName, Configuration.NS);
    if (value == null) {
        final String comment = "<" + qnConfig + " " + referenceBy + "=''/>";
        final char[] ch = comment.toCharArray();
        serializer.characters(EOL.toCharArray(), 0, EOL.length());
        serializer.comment(ch, 0, ch.length);
    } else {
        serializer.startElement(qnConfig, null);
        serializer.attribute(new QName(referenceBy, null), value.toString());
        serializer.endElement(qnConfig);
    }
}
Also used : QName(org.exist.dom.QName)

Example 4 with QName

use of org.exist.dom.QName in project exist by eXist-db.

the class Configurator method serialize.

protected static void serialize(final Configurable instance, final SAXSerializer serializer) throws ConfigurationException {
    final Class<?> clazz = instance.getClass();
    if (!clazz.isAnnotationPresent(ConfigurationClass.class)) {
        // UNDERSTAND: throw exception
        return;
    }
    final String configName = clazz.getAnnotation(ConfigurationClass.class).value();
    try {
        // open tag
        final QName qnConfig = new QName(configName, Configuration.NS);
        serializer.startElement(qnConfig, null);
        boolean simple = true;
        // store field's values as attributes or elements depends on annotation
        final AFields annotatedFields = getConfigurationAnnotatedFields(instance.getClass());
        try {
            // pass one - extract just attributes
            for (final AField<ConfigurationFieldAsAttribute> attr : annotatedFields.getAttributes()) {
                final Field field = attr.getField();
                field.setAccessible(true);
                // skip elements
                if (field.isAnnotationPresent(ConfigurationFieldAsElement.class)) {
                    continue;
                }
                // skip null values
                if (field.get(instance) == null) {
                    continue;
                }
                // now we just have attributes
                final String value = extractFieldValue(field, instance);
                serializer.attribute(new QName(attr.getAnnotation().value(), null), value);
            }
            // pass two - just elements or text nodes
            for (final AField<ConfigurationFieldAsElement> element : annotatedFields.getElements()) {
                simple = true;
                final Field field = element.getField();
                field.setAccessible(true);
                // skip attributes
                if (!field.isAnnotationPresent(ConfigurationFieldAsElement.class)) {
                    continue;
                }
                // ignore mapped fields for now, TODO: need to code back mapping.
                if (field.isAnnotationPresent(NewClass.class)) {
                    continue;
                }
                String referenceBy = null;
                if (field.isAnnotationPresent(ConfigurationReferenceBy.class)) {
                    referenceBy = field.getAnnotation(ConfigurationReferenceBy.class).value();
                }
                // skip null values
                if (field.get(instance) == null) {
                    final String tagName = element.getAnnotation().value();
                    String comment = "<" + tagName;
                    if (referenceBy != null) {
                        comment += " " + referenceBy + "=\"\"/>";
                    } else {
                        comment += "></" + tagName + ">";
                    }
                    serializer.characters(EOL.toCharArray(), 0, EOL.length());
                    final char[] ch = comment.toCharArray();
                    serializer.comment(ch, 0, ch.length);
                    continue;
                }
                String value = null;
                final String typeName = field.getType().getName();
                if ("java.util.List".equals(typeName)) {
                    serializeList(instance, element, serializer);
                    continue;
                } else if (implementsInterface(field.getType(), Configurable.class)) {
                    final Configurable subInstance = (Configurable) field.get(instance);
                    serialize(subInstance, serializer);
                    continue;
                } else if ("java.util.Map".equals(typeName)) {
                    serializeMap(element.getAnnotation().value(), (Map<String, String>) field.get(instance), serializer);
                    continue;
                } else {
                    value = extractFieldValue(field, instance);
                    if (value == null) {
                        LOG.error("field '{}' has unsupported type [{}] - skipped", field.getName(), typeName);
                    // TODO : throw exception ? -pb
                    }
                }
                if (value != null && value.length() > 0) {
                    if (simple) {
                        final QName qnSimple = new QName(element.getAnnotation().value(), Configuration.NS);
                        serializer.startElement(qnSimple, null);
                        serializer.characters(value);
                        serializer.endElement(new QName(element.getAnnotation().value(), null));
                    } else {
                        serializer.characters(value);
                    }
                } else {
                    final String tagName = element.getAnnotation().value();
                    String comment = "<" + tagName;
                    if (referenceBy != null) {
                        comment += " " + referenceBy + "=\"\"/>";
                    } else {
                        comment += "></" + tagName + ">";
                    }
                    serializer.characters(EOL.toCharArray(), 0, EOL.length());
                    final char[] ch = comment.toCharArray();
                    serializer.comment(ch, 0, ch.length);
                }
            }
        } catch (final IllegalArgumentException | IllegalAccessException e) {
            throw new ConfigurationException(e.getMessage(), e);
        }
        // close tag
        serializer.endElement(qnConfig);
    } catch (final SAXException saxe) {
        throw new ConfigurationException(saxe.getMessage(), saxe);
    }
}
Also used : QName(org.exist.dom.QName) SAXException(org.xml.sax.SAXException) Field(java.lang.reflect.Field) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 5 with QName

use of org.exist.dom.QName in project exist by eXist-db.

the class ElementImpl method setAttributeNS.

@Override
public void setAttributeNS(final String namespaceURI, final String qualifiedName, final String value) throws DOMException {
    final QName qname;
    try {
        if (document.context != null) {
            qname = QName.parse(document.context, qualifiedName, namespaceURI);
        } else {
            qname = QName.parse(namespaceURI, qualifiedName);
        }
    } catch (final IllegalQNameException e) {
        final short errCode;
        if (e.getValidity() == ILLEGAL_FORMAT.val || (e.getValidity() & QName.Validity.INVALID_NAMESPACE.val) == QName.Validity.INVALID_NAMESPACE.val) {
            errCode = DOMException.NAMESPACE_ERR;
        } else {
            errCode = DOMException.INVALID_CHARACTER_ERR;
        }
        throw new DOMException(errCode, "qualified name is invalid");
    }
    // check the QName is valid for use
    final byte validity = qname.isValid(false);
    if ((validity & QName.Validity.INVALID_LOCAL_PART.val) == QName.Validity.INVALID_LOCAL_PART.val) {
        throw new DOMException(DOMException.INVALID_CHARACTER_ERR, "qualified name is invalid");
    } else if ((validity & QName.Validity.INVALID_NAMESPACE.val) == QName.Validity.INVALID_NAMESPACE.val) {
        throw new DOMException(DOMException.NAMESPACE_ERR, "qualified name is invalid");
    }
    setAttribute(qname, value, qn -> getAttributeNodeNS(qn.getNamespaceURI(), qn.getLocalPart()));
}
Also used : QName(org.exist.dom.QName) IllegalQNameException(org.exist.dom.QName.IllegalQNameException)

Aggregations

QName (org.exist.dom.QName)260 Test (org.junit.Test)54 Sequence (org.exist.xquery.value.Sequence)39 DBBroker (org.exist.storage.DBBroker)31 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)28 IOException (java.io.IOException)23 Document (org.w3c.dom.Document)23 DocumentSet (org.exist.dom.persistent.DocumentSet)20 Text (org.w3c.dom.Text)20 NameTest (org.exist.xquery.NameTest)17 XPathException (org.exist.xquery.XPathException)17 BrokerPool (org.exist.storage.BrokerPool)15 IllegalQNameException (org.exist.dom.QName.IllegalQNameException)13 Node (org.w3c.dom.Node)12 ReentrantLock (java.util.concurrent.locks.ReentrantLock)11 NodeSet (org.exist.dom.persistent.NodeSet)11 SAXException (org.xml.sax.SAXException)11 DefaultDocumentSet (org.exist.dom.persistent.DefaultDocumentSet)10 MutableDocumentSet (org.exist.dom.persistent.MutableDocumentSet)10 PermissionDeniedException (org.exist.security.PermissionDeniedException)10