Search in sources :

Example 1 with XMLReaderPool

use of org.exist.util.XMLReaderPool in project exist by eXist-db.

the class AppRestoreUtils method getAppsFromBackup.

/**
 * Inspect all collections which may belong to apps in the backup descriptor. Return a list
 * of {@link AppDetail} objects containing the symbolic path, name and version of every app
 * found.
 *
 * The method attempts to be fail safe to make sure even bad backups can be restored. Errors
 * reading package descriptors are thus only logged and should not abort the process.
 *
 * @param broker the broker to use for parsing the descriptor and obtaining the app root
 * @param descriptors a queue of backup descriptors to inspect
 * @return list of application details
 */
private static List<AppDetail> getAppsFromBackup(final DBBroker broker, final Deque<BackupDescriptor> descriptors) {
    final String appRoot = getAppRoot(broker);
    final List<AppDetail> result = new ArrayList<>();
    final XMLReaderPool parserPool = broker.getBrokerPool().getParserPool();
    for (final BackupDescriptor descriptor : descriptors) {
        final BackupDescriptor apps = descriptor.getChildBackupDescriptor(appRoot);
        if (apps != null) {
            getAppsFromSubColl(result, parserPool, apps);
        }
        final BackupDescriptor system = descriptor.getChildBackupDescriptor("system");
        if (system != null) {
            final BackupDescriptor repo = system.getChildBackupDescriptor("repo");
            if (repo != null) {
                getAppsFromSubColl(result, parserPool, repo);
            }
        }
    }
    return result;
}
Also used : XMLReaderPool(org.exist.util.XMLReaderPool) BackupDescriptor(org.exist.backup.BackupDescriptor)

Example 2 with XMLReaderPool

use of org.exist.util.XMLReaderPool in project exist by eXist-db.

the class Restore method restore.

public void restore(final DBBroker broker, @Nullable final Txn transaction, final String newAdminPass, final Path f, final RestoreListener listener, final boolean overwriteApps) throws EXistException, IOException, SAXException, PermissionDeniedException {
    // set the admin password
    if (newAdminPass != null) {
        setAdminCredentials(broker, newAdminPass);
    }
    // get the backup descriptors, can be more than one if it was an incremental backup
    final Deque<BackupDescriptor> descriptors = getBackupDescriptors(f);
    final Set<String> appsToSkip = overwriteApps ? Collections.emptySet() : AppRestoreUtils.checkApps(broker, descriptors);
    // count all files
    long totalNrOfFiles = 0;
    for (BackupDescriptor backupDescriptor : descriptors) {
        totalNrOfFiles += backupDescriptor.getNumberOfFiles();
    }
    // continue restore
    final XMLReaderPool parserPool = broker.getBrokerPool().getParserPool();
    XMLReader reader = null;
    try {
        reader = parserPool.borrowXMLReader();
        listener.started(totalNrOfFiles);
        while (!descriptors.isEmpty()) {
            final BackupDescriptor descriptor = descriptors.pop();
            if (appsToSkip.contains(descriptor.getSymbolicPath())) {
                listener.skipResources("Skipping app path " + descriptor.getSymbolicPath() + ". Newer version " + "is already installed.", descriptor.getNumberOfFiles());
            } else {
                final EXistInputSource is = descriptor.getInputSource();
                is.setEncoding(UTF_8.displayName());
                final RestoreHandler handler = new RestoreHandler(broker, transaction, descriptor, listener, appsToSkip);
                reader.setContentHandler(handler);
                reader.parse(is);
            }
        }
    } finally {
        listener.finished();
        if (reader != null) {
            parserPool.returnXMLReader(reader);
        }
    }
}
Also used : EXistInputSource(org.exist.util.EXistInputSource) RestoreHandler(org.exist.backup.restore.RestoreHandler) XMLReaderPool(org.exist.util.XMLReaderPool) XMLReader(org.xml.sax.XMLReader)

Example 3 with XMLReaderPool

use of org.exist.util.XMLReaderPool in project exist by eXist-db.

the class Eval method loadVarFromURI.

private NodeImpl loadVarFromURI(final String uri) throws XPathException {
    XMLReader xr = null;
    final XMLReaderPool parserPool = context.getBroker().getBrokerPool().getParserPool();
    try {
        final URL url = new URL(uri);
        final InputStreamReader isr = new InputStreamReader(url.openStream(), UTF_8);
        final InputSource src = new InputSource(isr);
        xr = parserPool.borrowXMLReader();
        final SAXAdapter adapter = new SAXAdapter(context);
        xr.setContentHandler(adapter);
        xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
        xr.parse(src);
        isr.close();
        return adapter.getDocument();
    } catch (final SAXException | IOException e) {
        throw new XPathException(this, e);
    } finally {
        if (xr != null) {
            parserPool.returnXMLReader(xr);
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) InputStreamReader(java.io.InputStreamReader) SAXAdapter(org.exist.dom.memtree.SAXAdapter) IOException(java.io.IOException) XMLReaderPool(org.exist.util.XMLReaderPool) XMLReader(org.xml.sax.XMLReader) URL(java.net.URL) SAXException(org.xml.sax.SAXException)

Example 4 with XMLReaderPool

use of org.exist.util.XMLReaderPool in project exist by eXist-db.

the class RewriteConfig method parseConfig.

private Document parseConfig(final Path file) throws ParserConfigurationException, SAXException, IOException {
    try (final InputStream is = new BufferedInputStream(Files.newInputStream(file))) {
        final InputSource src = new InputSource(is);
        final XMLReaderPool parserPool = urlRewrite.getBrokerPool().getParserPool();
        XMLReader xr = null;
        try {
            xr = parserPool.borrowXMLReader();
            final SAXAdapter adapter = new SAXAdapter();
            xr.setContentHandler(adapter);
            xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
            xr.parse(src);
            return adapter.getDocument();
        } finally {
            if (xr != null) {
                parserPool.returnXMLReader(xr);
            }
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) SAXAdapter(org.exist.dom.memtree.SAXAdapter) XMLReaderPool(org.exist.util.XMLReaderPool) XMLReader(org.xml.sax.XMLReader)

Example 5 with XMLReaderPool

use of org.exist.util.XMLReaderPool in project exist by eXist-db.

the class ExecuteFunction method resultAsElement.

private ElementImpl resultAsElement(final boolean makeNodeFromColumnName, final boolean executeResult, final Statement stmt) throws SQLException, XPathException {
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("result", NAMESPACE_URI, PREFIX), null);
        builder.addAttribute(new QName("count", null, null), "-1");
        builder.addAttribute(new QName("updateCount", null, null), String.valueOf(stmt.getUpdateCount()));
        int rowCount = 0;
        ResultSet rs = null;
        try {
            if (executeResult) {
                rs = stmt.getResultSet();
            }
            // for executing Stored Procedures that return results (e.g. SQL Server)
            if (rs == null) {
                try {
                    rs = stmt.getGeneratedKeys();
                } catch (final SQLException e) {
                // no-op - getGeneratedKeys is not always supported
                }
            }
            if (rs != null) {
                /* SQL Query returned results */
                // iterate through the result set building an XML document
                final ResultSetMetaData rsmd = rs.getMetaData();
                final int iColumns = rsmd.getColumnCount();
                while (rs.next()) {
                    builder.startElement(new QName("row", NAMESPACE_URI, PREFIX), null);
                    builder.addAttribute(new QName("index", null, null), String.valueOf(rs.getRow()));
                    // get each tuple in the row
                    for (int i = 0; i < iColumns; i++) {
                        final String columnName = rsmd.getColumnLabel(i + 1);
                        if (columnName != null) {
                            String colElement = "field";
                            if (makeNodeFromColumnName && !columnName.isEmpty()) {
                                // 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, NAMESPACE_URI, PREFIX), null);
                            if (!makeNodeFromColumnName || columnName.length() <= 0) {
                                final String name;
                                if (!columnName.isEmpty()) {
                                    name = SQLUtils.escapeXmlAttr(columnName);
                                } else {
                                    name = "Column: " + (i + 1);
                                }
                                builder.addAttribute(new QName("name", null, null), name);
                            }
                            builder.addAttribute(new QName(TYPE_ATTRIBUTE_NAME, NAMESPACE_URI, PREFIX), rsmd.getColumnTypeName(i + 1));
                            builder.addAttribute(new QName(TYPE_ATTRIBUTE_NAME, Namespaces.SCHEMA_NS, "xs"), Type.getTypeName(SQLUtils.sqlTypeToXMLType(rsmd.getColumnType(i + 1))));
                            // get the content
                            if (rsmd.getColumnType(i + 1) == Types.SQLXML) {
                                // parse sqlxml value
                                try {
                                    final SQLXML sqlXml = rs.getSQLXML(i + 1);
                                    if (rs.wasNull()) {
                                        // Add a null indicator attribute if the value was SQL Null
                                        builder.addAttribute(new QName("null", NAMESPACE_URI, PREFIX), "true");
                                    } else {
                                        try (final Reader charStream = sqlXml.getCharacterStream()) {
                                            final InputSource src = new InputSource(charStream);
                                            final XMLReaderPool parserPool = context.getBroker().getBrokerPool().getParserPool();
                                            XMLReader reader = null;
                                            try {
                                                reader = parserPool.borrowXMLReader();
                                                final SAXAdapter adapter = new AppendingSAXAdapter(builder);
                                                reader.setContentHandler(adapter);
                                                reader.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
                                                reader.parse(src);
                                            } finally {
                                                if (reader != null) {
                                                    parserPool.returnXMLReader(reader);
                                                }
                                            }
                                        }
                                    }
                                } catch (final Exception e) {
                                    throw new XPathException("Could not parse column of type SQLXML: " + e.getMessage(), e);
                                }
                            } else {
                                // otherwise assume string value
                                final String colValue = rs.getString(i + 1);
                                if (rs.wasNull()) {
                                    // Add a null indicator attribute if the value was SQL Null
                                    builder.addAttribute(new QName("null", NAMESPACE_URI, PREFIX), "true");
                                } else {
                                    if (colValue != null) {
                                        builder.characters(colValue);
                                    }
                                }
                            }
                            builder.endElement();
                        }
                    }
                    builder.endElement();
                    rowCount++;
                }
            }
            // close `result` element
            builder.endElement();
            // Change the root element count attribute to have the correct value
            final ElementImpl docElement = (ElementImpl) builder.getDocument().getDocumentElement();
            final Node count = docElement.getNode().getAttributes().getNamedItem("count");
            if (count != null) {
                count.setNodeValue(String.valueOf(rowCount));
            }
            builder.endDocument();
            return docElement;
        } finally {
            // close record set
            if (rs != null) {
                try {
                    rs.close();
                } catch (final SQLException se) {
                    LOG.warn("Unable to close JDBC RecordSet: {}", se.getMessage(), se);
                }
            }
        }
    } finally {
        context.popDocumentContext();
    }
}
Also used : InputSource(org.xml.sax.InputSource) SQLException(java.sql.SQLException) QName(org.exist.dom.QName) Node(org.w3c.dom.Node) XMLReader(org.xml.sax.XMLReader) Reader(java.io.Reader) SQLException(java.sql.SQLException) SQLRecoverableException(java.sql.SQLRecoverableException) IOException(java.io.IOException) ResultSetMetaData(java.sql.ResultSetMetaData) SQLXML(java.sql.SQLXML) ResultSet(java.sql.ResultSet) XMLReaderPool(org.exist.util.XMLReaderPool) XMLReader(org.xml.sax.XMLReader)

Aggregations

XMLReaderPool (org.exist.util.XMLReaderPool)11 XMLReader (org.xml.sax.XMLReader)10 InputSource (org.xml.sax.InputSource)8 IOException (java.io.IOException)7 SAXAdapter (org.exist.dom.memtree.SAXAdapter)6 SAXException (org.xml.sax.SAXException)4 StringReader (java.io.StringReader)3 InputStream (java.io.InputStream)2 EXistInputSource (org.exist.util.EXistInputSource)2 BufferedInputStream (java.io.BufferedInputStream)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 HttpURLConnection (java.net.HttpURLConnection)1 URL (java.net.URL)1 URLConnection (java.net.URLConnection)1 ResultSet (java.sql.ResultSet)1 ResultSetMetaData (java.sql.ResultSetMetaData)1 SQLException (java.sql.SQLException)1 SQLRecoverableException (java.sql.SQLRecoverableException)1 SQLXML (java.sql.SQLXML)1