Search in sources :

Example 46 with QName

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

the class LuceneIndexWorker method scanIndexByQName.

private Occurrences[] scanIndexByQName(List<QName> qnames, DocumentSet docs, NodeSet nodes, String start, String end, long max) throws IOException {
    final TreeMap<String, Occurrences> map = new TreeMap<>();
    index.withReader(reader -> {
        for (QName qname : qnames) {
            String field = LuceneUtil.encodeQName(qname, index.getBrokerPool().getSymbols());
            doScanIndex(docs, nodes, start, end, max, map, reader, field);
        }
        return null;
    });
    Occurrences[] occur = new Occurrences[map.size()];
    return map.values().toArray(occur);
}
Also used : QName(org.exist.dom.QName) Occurrences(org.exist.util.Occurrences)

Example 47 with QName

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

the class ExecuteFunction method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (args.length == 5 || args.length == 6) {
        // was a connection and PL/SQL statement specified?
        if (args[0].isEmpty() || args[1].isEmpty()) {
            return (Sequence.EMPTY_SEQUENCE);
        }
        // get the Connection
        long connectionUID = ((IntegerValue) args[0].itemAt(0)).getLong();
        Connection connection = SQLModule.retrieveConnection(context, connectionUID);
        if (connection == null) {
            return (Sequence.EMPTY_SEQUENCE);
        }
        // get the PL/SQL statement
        String plSql = args[1].getStringValue();
        // get the input parameters (if any)
        Element parameters = null;
        if (!args[2].isEmpty()) {
            parameters = (Element) args[2].itemAt(0);
        }
        // was a result set position specified?
        int resultSetPos = 0;
        if (!args[3].isEmpty()) {
            resultSetPos = ((IntegerValue) args[3].itemAt(0)).getInt();
        }
        boolean haveReturnCode = false;
        // default value of 1 for success
        int plSqlSuccess = 1;
        if (args.length == 6) {
            // a return code is expected so what is the value indicating success?
            plSqlSuccess = ((IntegerValue) args[5].itemAt(0)).getInt();
            haveReturnCode = true;
        }
        CallableStatement statement = null;
        ResultSet resultSet = null;
        try {
            MemTreeBuilder builder = context.getDocumentBuilder();
            int iRow = 0;
            statement = connection.prepareCall(plSql);
            if (haveReturnCode) {
                statement.registerOutParameter(1, Types.NUMERIC);
            }
            if (resultSetPos != 0) {
                statement.registerOutParameter(resultSetPos, OracleTypes.CURSOR);
            }
            if (!args[2].isEmpty()) {
                setParametersOnPreparedStatement(statement, parameters);
            }
            statement.execute();
            if (haveReturnCode) {
                int returnCode = statement.getInt(1);
                if (returnCode != plSqlSuccess) {
                    LOG.error(plSql + " failed [" + returnCode + "]");
                    return (Sequence.EMPTY_SEQUENCE);
                }
            }
            if (resultSetPos != 0) {
                // iterate through the result set building an XML document
                builder.startDocument();
                builder.startElement(new QName("result", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
                builder.addAttribute(new QName("count", null, null), String.valueOf(-1));
                resultSet = (ResultSet) statement.getObject(resultSetPos);
                ResultSetMetaData rsmd = resultSet.getMetaData();
                int iColumns = rsmd.getColumnCount();
                while (resultSet.next()) {
                    builder.startElement(new QName("row", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
                    builder.addAttribute(new QName("index", null, null), String.valueOf(resultSet.getRow()));
                    // get each tuple in the row
                    for (int i = 0; i < iColumns; i++) {
                        String columnName = rsmd.getColumnLabel(i + 1);
                        if (columnName != null) {
                            String colValue = resultSet.getString(i + 1);
                            String colElement = "field";
                            if (((BooleanValue) args[4].itemAt(0)).effectiveBooleanValue() && columnName.length() > 0) {
                                // use column names as the XML node
                                /**
                                 * Spaces in column names are replaced with
                                 * underscore's
                                 */
                                colElement = SQLUtils.escapeXmlAttr(columnName.replace(' ', '_'));
                            }
                            builder.startElement(new QName(colElement, OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
                            if (!((BooleanValue) args[4].itemAt(0)).effectiveBooleanValue() || columnName.length() <= 0) {
                                String name;
                                if (columnName.length() > 0) {
                                    name = SQLUtils.escapeXmlAttr(columnName);
                                } else {
                                    name = "Column: " + String.valueOf(i + 1);
                                }
                                builder.addAttribute(new QName("name", null, null), name);
                            }
                            builder.addAttribute(new QName("type", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), rsmd.getColumnTypeName(i + 1));
                            builder.addAttribute(new QName("type", Namespaces.SCHEMA_NS, "xs"), Type.getTypeName(SQLUtils.sqlTypeToXMLType(rsmd.getColumnType(i + 1))));
                            if (resultSet.wasNull()) {
                                // Add a null indicator attribute if the value was SQL Null
                                builder.addAttribute(new QName("null", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), "true");
                            }
                            if (colValue != null) {
                                builder.characters(SQLUtils.escapeXmlText(colValue));
                            }
                            builder.endElement();
                        }
                    }
                    builder.endElement();
                    iRow++;
                }
                builder.endElement();
                // Change the root element count attribute to have the correct value
                NodeValue node = (NodeValue) builder.getDocument().getDocumentElement();
                Node count = node.getNode().getAttributes().getNamedItem("count");
                if (count != null) {
                    count.setNodeValue(String.valueOf(iRow));
                }
                builder.endDocument();
                // return the XML result set
                return (node);
            } else {
                // there was no result set so just return an empty sequence
                return (Sequence.EMPTY_SEQUENCE);
            }
        } catch (SQLException sqle) {
            LOG.error("oracle:execute() Caught SQLException \"" + sqle.getMessage() + "\" for PL/SQL: \"" + plSql + "\"", sqle);
            // return details about the SQLException
            MemTreeBuilder builder = context.getDocumentBuilder();
            builder.startDocument();
            builder.startElement(new QName("exception", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
            boolean recoverable = false;
            if (sqle instanceof SQLRecoverableException) {
                recoverable = true;
            }
            builder.addAttribute(new QName("recoverable", null, null), String.valueOf(recoverable));
            builder.startElement(new QName("state", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
            String sqlState = sqle.getSQLState();
            if (sqlState != null) {
                builder.characters(sqle.getSQLState());
            } else {
                builder.characters("null");
            }
            builder.endElement();
            builder.startElement(new QName("message", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
            builder.characters(sqle.getMessage());
            builder.endElement();
            builder.startElement(new QName("stack-trace", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
            ByteArrayOutputStream bufStackTrace = new ByteArrayOutputStream();
            sqle.printStackTrace(new PrintStream(bufStackTrace));
            builder.characters(new String(bufStackTrace.toByteArray()));
            builder.endElement();
            builder.startElement(new QName("oracle", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
            builder.characters(SQLUtils.escapeXmlText(plSql));
            builder.endElement();
            int line = getLine();
            int column = getColumn();
            builder.startElement(new QName("xquery", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
            builder.addAttribute(new QName("line", null, null), String.valueOf(line));
            builder.addAttribute(new QName("column", null, null), String.valueOf(column));
            builder.endElement();
            builder.endElement();
            builder.endDocument();
            return (NodeValue) builder.getDocument().getDocumentElement();
        } finally {
            release(connection, statement, resultSet);
        }
    } else {
        throw new XPathException("Invalid number of arguments [" + args.length + "]");
    }
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) PrintStream(java.io.PrintStream) SQLRecoverableException(java.sql.SQLRecoverableException) SQLException(java.sql.SQLException) XPathException(org.exist.xquery.XPathException) QName(org.exist.dom.QName) IntegerValue(org.exist.xquery.value.IntegerValue) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Connection(java.sql.Connection) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) ResultSetMetaData(java.sql.ResultSetMetaData) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) CallableStatement(java.sql.CallableStatement) BooleanValue(org.exist.xquery.value.BooleanValue) ResultSet(java.sql.ResultSet)

Example 48 with QName

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

the class MessageFunctions method handlePart.

private void handlePart(Part part, MemTreeBuilder builder) throws MessagingException, IOException, XPathException, SAXException {
    Object content = part.getContent();
    if (content instanceof Multipart) {
        handleMultipart((Multipart) content, builder);
        return;
    }
    String disposition = part.getDisposition();
    String contentType = part.getContentType();
    // Check if plain
    if (contentType.contains("text/plain")) {
        builder.startElement(new QName("text", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        mimeParamsToAttributes(builder, part.getContentType());
        builder.characters(part.getContent().toString());
        builder.endElement();
    } else if (contentType.contains("text/html")) {
        builder.startElement(new QName("xhtml", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        mimeParamsToAttributes(builder, part.getContentType());
        // extract and clean up the html
        DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
        try (InputStream inputStream = part.getInputStream()) {
            DocumentImpl html = ModuleUtils.htmlToXHtml(context, new StreamSource(inputStream), null, null);
            ElementImpl rootElem = (ElementImpl) html.getDocumentElement();
            html.copyTo(rootElem, receiver);
            builder.endElement();
        }
    } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
        builder.startElement(new QName("attachment", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        builder.addAttribute(new QName("filename", null, null), part.getFileName());
        mimeParamsToAttributes(builder, part.getContentType());
        handleBinaryContent(part, builder);
        builder.endElement();
    } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
        builder.startElement(new QName("inline", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        MimeBodyPart mbp = (MimeBodyPart) part;
        builder.addAttribute(new QName("filename", null, null), mbp.getFileName());
        // fix content id so that it matches the cid: format within the html
        if (mbp.getContentID() != null) {
            builder.addAttribute(new QName("content-id", null, null), "cid:" + mbp.getContentID().replaceAll("^<|>$", ""));
        }
        mimeParamsToAttributes(builder, part.getContentType());
        handleBinaryContent(part, builder);
        builder.endElement();
    } else {
        // Should never happen
        builder.startElement(new QName("other", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        mimeParamsToAttributes(builder, part.getContentType());
        builder.addAttribute(new QName("disposition", null, null), part.getDisposition());
        builder.characters(part.getContent().toString());
        builder.endElement();
    }
}
Also used : ElementImpl(org.exist.dom.memtree.ElementImpl) QName(org.exist.dom.QName) StreamSource(javax.xml.transform.stream.StreamSource) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) DocumentImpl(org.exist.dom.memtree.DocumentImpl)

Example 49 with QName

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

the class NativeBroker method removeNode.

/**
 * Removes the Node Reference from the database.
 * The index will be updated later, i.e. after all nodes have been physically
 * removed. See {@link #endRemove(org.exist.storage.txn.Txn)}.
 * removeNode() just adds the node ids to the list in elementIndex
 * for later removal.
 */
@Override
public <T extends IStoredNode> void removeNode(final Txn transaction, final IStoredNode<T> node, final NodePath currentPath, final String content) {
    final DocumentImpl doc = node.getOwnerDocument();
    new DOMTransaction(this, domDb, () -> lockManager.acquireBtreeWriteLock(domDb.getLockName()), doc) {

        @Override
        public Object start() {
            final long address = node.getInternalAddress();
            if (StorageAddress.hasAddress(address)) {
                domDb.remove(transaction, new NodeRef(doc.getDocId(), node.getNodeId()), address);
            } else {
                domDb.remove(transaction, new NodeRef(doc.getDocId(), node.getNodeId()));
            }
            return null;
        }
    }.run();
    notifyRemoveNode(node, currentPath, content);
    final QName qname;
    switch(node.getNodeType()) {
        case Node.ELEMENT_NODE:
            qname = new QName(node.getQName(), ElementValue.ELEMENT);
            node.setQName(qname);
            final GeneralRangeIndexSpec spec1 = doc.getCollection().getIndexByPathConfiguration(this, currentPath);
            if (spec1 != null) {
                valueIndex.setDocument(doc);
                valueIndex.storeElement((ElementImpl) node, content, spec1.getType(), NativeValueIndex.IndexType.GENERIC, false);
            }
            final QNameRangeIndexSpec qnSpecElement = doc.getCollection().getIndexByQNameConfiguration(this, qname);
            if (qnSpecElement != null) {
                valueIndex.setDocument(doc);
                valueIndex.storeElement((ElementImpl) node, content, qnSpecElement.getType(), NativeValueIndex.IndexType.QNAME, false);
            }
            break;
        case Node.ATTRIBUTE_NODE:
            qname = new QName(node.getQName(), ElementValue.ATTRIBUTE);
            node.setQName(qname);
            currentPath.addComponent(qname);
            // Strange : does it mean that the node is added 2 times under 2 different identities ?
            final AttrImpl attr;
            attr = (AttrImpl) node;
            switch(attr.getType()) {
                case AttrImpl.ID:
                    valueIndex.setDocument(doc);
                    valueIndex.storeAttribute(attr, attr.getValue(), Type.ID, NativeValueIndex.IndexType.GENERIC, false);
                    break;
                case AttrImpl.IDREF:
                    valueIndex.setDocument(doc);
                    valueIndex.storeAttribute(attr, attr.getValue(), Type.IDREF, NativeValueIndex.IndexType.GENERIC, false);
                    break;
                case AttrImpl.IDREFS:
                    valueIndex.setDocument(doc);
                    final StringTokenizer tokenizer = new StringTokenizer(attr.getValue(), " ");
                    while (tokenizer.hasMoreTokens()) {
                        valueIndex.storeAttribute(attr, tokenizer.nextToken(), Type.IDREF, NativeValueIndex.IndexType.GENERIC, false);
                    }
                    break;
                default:
            }
            final RangeIndexSpec spec2 = doc.getCollection().getIndexByPathConfiguration(this, currentPath);
            if (spec2 != null) {
                valueIndex.setDocument(doc);
                valueIndex.storeAttribute(attr, null, spec2, false);
            }
            final QNameRangeIndexSpec qnSpecAttribute = doc.getCollection().getIndexByQNameConfiguration(this, qname);
            if (qnSpecAttribute != null) {
                valueIndex.setDocument(doc);
                valueIndex.storeAttribute(attr, null, qnSpecAttribute, false);
            }
            currentPath.removeLastComponent();
            break;
        case Node.TEXT_NODE:
            break;
    }
}
Also used : QName(org.exist.dom.QName) PooledObject(org.apache.commons.pool2.PooledObject) DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) DOMTransaction(org.exist.storage.dom.DOMTransaction)

Example 50 with QName

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

the class NodePath method reverseComponents.

protected void reverseComponents() {
    for (int i = 0; i < pos / 2; ++i) {
        QName tmp = components[i];
        components[i] = components[pos - 1 - i];
        components[pos - 1 - i] = tmp;
    }
}
Also used : QName(org.exist.dom.QName)

Aggregations

QName (org.exist.dom.QName)271 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 AttributesImpl (org.xml.sax.helpers.AttributesImpl)18 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