Search in sources :

Example 11 with MemTreeBuilder

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

the class LuceneIndexWorker method search.

/**
 * SOLR
 *
 * @param context the xquery context
 * @param toBeMatchedURIs the URIs to match
 * @param queryText the query
 * @param fieldsToGet the fields to get
 * @param options the search options
 *
 * @return search report
 *
 * @throws XPathException if an error occurs executing the query
 * @throws IOException if an I/O error occurs
 */
public NodeImpl search(final XQueryContext context, final List<String> toBeMatchedURIs, String queryText, String[] fieldsToGet, QueryOptions options) throws XPathException, IOException {
    return index.withSearcher(searcher -> {
        // Get analyzer : to be retrieved from configuration
        final Analyzer searchAnalyzer = new StandardAnalyzer(LuceneIndex.LUCENE_VERSION_IN_USE);
        // Setup query Version, default field, analyzer
        final QueryParserWrapper parser = getQueryParser("", searchAnalyzer, null);
        options.configureParser(parser.getConfiguration());
        final Query query = parser.parse(queryText);
        // extract all used fields from query
        final String[] fields;
        if (fieldsToGet == null) {
            fields = LuceneUtil.extractFields(query, searcher.searcher.getIndexReader());
        } else {
            fields = fieldsToGet;
        }
        final PlainTextHighlighter highlighter = new PlainTextHighlighter(query, searcher.searcher.getIndexReader());
        context.pushDocumentContext();
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            builder.startDocument();
            // start root element
            final int nodeNr = builder.startElement("", "results", "results", null);
            // Perform actual search
            final BinarySearchCollector collector = new BinarySearchCollector(toBeMatchedURIs, builder, fields, searchAnalyzer, highlighter);
            searcher.searcher.search(query, collector);
            // finish root element
            builder.endElement();
            // TODO check
            return builder.getDocument().getNode(nodeNr);
        } finally {
            context.popDocumentContext();
        }
    });
}
Also used : DrillDownQuery(org.apache.lucene.facet.DrillDownQuery) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) Analyzer(org.apache.lucene.analysis.Analyzer)

Example 12 with MemTreeBuilder

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

the class RegistryFunctions method serializeDependenciesTree.

private Sequence serializeDependenciesTree(final Map<String, Set<String>> dependenciesTree) {
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = getContext().getDocumentBuilder();
        builder.startDocument();
        builder.startElement(DEPENDENCIES, null);
        for (final Map.Entry<String, Set<String>> dependencyTree : dependenciesTree.entrySet()) {
            serializeDependencyTree(builder, dependencyTree);
        }
        builder.endElement();
        builder.endDocument();
        return builder.getDocument();
    } finally {
        context.popDocumentContext();
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder)

Example 13 with MemTreeBuilder

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

the class RegistryFunctions method serializeMissingDependencies.

private Sequence serializeMissingDependencies(final Map<String, Set<String>> missingDependencies) {
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = getContext().getDocumentBuilder();
        builder.startDocument();
        builder.startElement(MISSING_DEPENDENCIES, null);
        for (final Map.Entry<String, Set<String>> missingDependency : missingDependencies.entrySet()) {
            serializeMissingDependency(builder, missingDependency);
        }
        builder.endElement();
        builder.endDocument();
        return builder.getDocument();
    } finally {
        context.popDocumentContext();
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder)

Example 14 with MemTreeBuilder

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

the class RegistryFunctionsTest method outputMethod.

@Test
public void outputMethod() throws SerializationAnnotationException, TransformerException, IOException, SAXException {
    // test setup
    final String methodStr = "html5";
    final MethodAnnotation method = new MethodAnnotation();
    method.setName(SerializationAnnotationName.method.getQName());
    method.setLiterals(new Literal[] { new Literal() {

        @Override
        public Type getType() {
            return Type.STRING;
        }

        @Override
        public String getValue() {
            return methodStr;
        }
    } });
    method.initialise();
    // execute serialize method
    final MemTreeBuilder builder = new MemTreeBuilder();
    builder.startDocument();
    RegistryFunctions.serializeSerializationAnnotation(builder, method);
    builder.endDocument();
    // assert result
    final String xmlResult = documentToString(builder.getDocument());
    final Source srcExpected = Input.fromString("<method xmlns=\"http://www.w3.org/2010/xslt-xquery-serialization\">" + methodStr + "</method>").build();
    final Source srcActual = Input.fromString(xmlResult).build();
    final Diff diff = DiffBuilder.compare(srcExpected).withTest(srcActual).checkForIdentical().build();
    assertFalse(diff.toString(), diff.hasDifferences());
}
Also used : Type(org.exquery.xquery.Type) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) Diff(org.xmlunit.diff.Diff) Literal(org.exquery.xquery.Literal) MethodAnnotation(org.exquery.serialization.annotation.MethodAnnotation) Override(java.lang.Override) DOMSource(javax.xml.transform.dom.DOMSource) Test(org.junit.Test)

Example 15 with MemTreeBuilder

use of org.exist.dom.memtree.MemTreeBuilder 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)

Aggregations

MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)81 QName (org.exist.dom.QName)28 XPathException (org.exist.xquery.XPathException)23 Sequence (org.exist.xquery.value.Sequence)19 DocumentBuilderReceiver (org.exist.dom.memtree.DocumentBuilderReceiver)17 SAXException (org.xml.sax.SAXException)16 NodeValue (org.exist.xquery.value.NodeValue)15 IOException (java.io.IOException)14 NodeImpl (org.exist.dom.memtree.NodeImpl)14 Item (org.exist.xquery.value.Item)8 SequenceIterator (org.exist.xquery.value.SequenceIterator)8 Test (org.junit.Test)8 XQueryContext (org.exist.xquery.XQueryContext)7 ValueSequence (org.exist.xquery.value.ValueSequence)7 AttributesImpl (org.xml.sax.helpers.AttributesImpl)7 DocumentImpl (org.exist.dom.memtree.DocumentImpl)6 BrokerPool (org.exist.storage.BrokerPool)6 InputSource (org.xml.sax.InputSource)6 MalformedURLException (java.net.MalformedURLException)5 Path (java.nio.file.Path)5