Search in sources :

Example 41 with EXistException

use of org.exist.EXistException in project exist by eXist-db.

the class ConsistencyCheckTask method execute.

@Override
public void execute(final DBBroker broker, final Txn transaction) throws EXistException {
    final Agent agentInstance = AgentFactory.getInstance();
    final BrokerPool brokerPool = broker.getBrokerPool();
    final TaskStatus endStatus = new TaskStatus(TaskStatus.Status.STOPPED_OK);
    agentInstance.changeStatus(brokerPool, new TaskStatus(TaskStatus.Status.INIT));
    if (paused) {
        LOG.info("Consistency check is paused.");
        agentInstance.changeStatus(brokerPool, new TaskStatus(TaskStatus.Status.PAUSED));
        return;
    }
    brokerPool.getProcessMonitor().startJob(ProcessMonitor.ACTION_BACKUP, null, monitor);
    PrintWriter report = null;
    try {
        boolean doBackup = createBackup;
        // TODO: don't use the direct access feature for now. needs more testing
        List<ErrorReport> errors = null;
        if (!incremental || incrementalCheck) {
            LOG.info("Starting consistency check...");
            report = openLog();
            final CheckCallback cb = new CheckCallback(report);
            final ConsistencyCheck check = new ConsistencyCheck(broker, transaction, false, checkDocs);
            agentInstance.changeStatus(brokerPool, new TaskStatus(TaskStatus.Status.RUNNING_CHECK));
            errors = check.checkAll(cb);
            if (!errors.isEmpty()) {
                endStatus.setStatus(TaskStatus.Status.STOPPED_ERROR);
                endStatus.setReason(errors);
                LOG.error("Errors found: {}", errors.size());
                doBackup = true;
                if (fatalErrorsFound(errors)) {
                    LOG.error("Fatal errors were found: pausing the consistency check task.");
                    paused = true;
                }
            }
            LOG.info("Finished consistency check");
        }
        if (doBackup) {
            LOG.info("Starting backup...");
            final SystemExport sysexport = new SystemExport(broker, transaction, logCallback, monitor, false);
            lastExportedBackup = sysexport.export(exportDir, incremental, maxInc, createZip, errors);
            agentInstance.changeStatus(brokerPool, new TaskStatus(TaskStatus.Status.RUNNING_BACKUP));
            if (lastExportedBackup != null) {
                LOG.info("Created backup to file: {}", lastExportedBackup.toAbsolutePath().toString());
            }
            LOG.info("Finished backup");
        }
    } catch (final TerminatedException | PermissionDeniedException e) {
        throw new EXistException(e.getMessage(), e);
    } finally {
        if (report != null) {
            report.close();
        }
        agentInstance.changeStatus(brokerPool, endStatus);
        brokerPool.getProcessMonitor().endJob();
    }
}
Also used : Agent(org.exist.management.Agent) EXistException(org.exist.EXistException) TaskStatus(org.exist.management.TaskStatus) ConsistencyCheck(org.exist.backup.ConsistencyCheck) ErrorReport(org.exist.backup.ErrorReport) PermissionDeniedException(org.exist.security.PermissionDeniedException) SystemExport(org.exist.backup.SystemExport) TerminatedException(org.exist.xquery.TerminatedException) PrintWriter(java.io.PrintWriter)

Example 42 with EXistException

use of org.exist.EXistException in project exist by eXist-db.

the class SourceFactory method getSource_fromFile.

/**
 * Get the resource source from the filesystem.
 *
 * @param contextPath the context path of the resource.
 * @param location the location of the resource (relative to the {@code contextPath}).
 * @param checkXQEncoding where we need to check the encoding of the XQuery.
 *
 * @return the source, or null if there is no such resource in the db indicated by {@code path}.
 */
@Nullable
private static Source getSource_fromFile(final String contextPath, final String location, final boolean checkXQEncoding) {
    String locationPath = location.replaceAll("^(file:)?/*(.*)$", "$2");
    Source source = null;
    try {
        final Path p = Paths.get(contextPath, locationPath);
        if (Files.isReadable(p)) {
            locationPath = p.toUri().toASCIIString();
            source = new FileSource(p, checkXQEncoding);
        }
    } catch (final InvalidPathException e) {
    // continue trying
    }
    if (source == null) {
        try {
            final Path p2 = Paths.get(locationPath);
            if (Files.isReadable(p2)) {
                locationPath = p2.toUri().toASCIIString();
                source = new FileSource(p2, checkXQEncoding);
            }
        } catch (final InvalidPathException e) {
        // continue trying
        }
    }
    if (source == null && contextPath != null) {
        try {
            final Path p3 = Paths.get(contextPath).toAbsolutePath().resolve(locationPath);
            if (Files.isReadable(p3)) {
                locationPath = p3.toUri().toASCIIString();
                source = new FileSource(p3, checkXQEncoding);
            }
        } catch (final InvalidPathException e) {
        // continue trying
        }
    }
    if (source == null) {
        /*
             * Try to load as an absolute path
             */
        try {
            final Path p4 = Paths.get("/" + locationPath);
            if (Files.isReadable(p4)) {
                locationPath = p4.toUri().toASCIIString();
                source = new FileSource(p4, checkXQEncoding);
            }
        } catch (final InvalidPathException e) {
        // continue trying
        }
    }
    if (source == null && contextPath != null) {
        /*
             * Try to load from the folder of the contextPath
             */
        try {
            final Path p5 = Paths.get(contextPath).resolveSibling(locationPath);
            if (Files.isReadable(p5)) {
                locationPath = p5.toUri().toASCIIString();
                source = new FileSource(p5, checkXQEncoding);
            }
        } catch (final InvalidPathException e) {
        // continue trying
        }
    }
    if (source == null && contextPath != null) {
        /*
             * Try to load from the parent folder of the contextPath URL
             */
        try {
            Path p6 = null;
            if (contextPath.startsWith("file:/")) {
                try {
                    p6 = Paths.get(new URI(contextPath)).resolveSibling(locationPath);
                } catch (final URISyntaxException e) {
                // continue trying
                }
            }
            if (p6 == null) {
                p6 = Paths.get(contextPath.replaceFirst("^file:/*(/.*)$", "$1")).resolveSibling(locationPath);
            }
            if (Files.isReadable(p6)) {
                locationPath = p6.toUri().toASCIIString();
                source = new FileSource(p6, checkXQEncoding);
            }
        } catch (final InvalidPathException e) {
        // continue trying
        }
    }
    if (source == null && contextPath != null) {
        /*
             * Try to load from the contextPath URL folder
             */
        try {
            Path p7 = null;
            if (contextPath.startsWith("file:/")) {
                try {
                    p7 = Paths.get(new URI(contextPath)).resolve(locationPath);
                } catch (final URISyntaxException e) {
                // continue trying
                }
            }
            if (p7 == null) {
                p7 = Paths.get(contextPath.replaceFirst("^file:/*(/.*)$", "$1")).resolve(locationPath);
            }
            if (Files.isReadable(p7)) {
                locationPath = p7.toUri().toASCIIString();
                source = new FileSource(p7, checkXQEncoding);
            }
        } catch (final InvalidPathException e) {
        // continue trying
        }
    }
    if (source == null) {
        /*
             * Lastly we try to load it using EXIST_HOME as the reference point
             */
        Path p8 = null;
        try {
            p8 = FileUtils.resolve(BrokerPool.getInstance().getConfiguration().getExistHome(), locationPath);
            if (Files.isReadable(p8)) {
                locationPath = p8.toUri().toASCIIString();
                source = new FileSource(p8, checkXQEncoding);
            }
        } catch (final EXistException e) {
            LOG.warn(e);
        } catch (final InvalidPathException e) {
        // continue and abort below
        }
    }
    return source;
}
Also used : Path(java.nio.file.Path) URISyntaxException(java.net.URISyntaxException) EXistException(org.exist.EXistException) XmldbURI(org.exist.xmldb.XmldbURI) URI(java.net.URI) InvalidPathException(java.nio.file.InvalidPathException) Nullable(javax.annotation.Nullable)

Example 43 with EXistException

use of org.exist.EXistException in project exist by eXist-db.

the class DataBackup method execute.

@Override
public void execute(final DBBroker broker, final Txn transaction) throws EXistException {
    if (!(broker instanceof NativeBroker)) {
        throw new EXistException("DataBackup system task can only be used with the native storage backend");
    }
    LOG.debug("Backing up data files ...");
    final String creationDate = creationDateFormat.format(Calendar.getInstance().getTime());
    final Path outFilename = dest.resolve(creationDate + ".zip");
    this.lastBackup = Optional.of(outFilename);
    // Create the ZIP file
    LOG.debug("Archiving data files into: {}", outFilename);
    try (final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(outFilename)))) {
        out.setLevel(Deflater.NO_COMPRESSION);
        final Callback cb = new Callback(out);
        broker.backupToArchive(cb);
    // close the zip file
    } catch (final IOException e) {
        LOG.error("An IO error occurred while backing up data files: {}", e.getMessage(), e);
    }
}
Also used : Path(java.nio.file.Path) ZipOutputStream(java.util.zip.ZipOutputStream) EXistException(org.exist.EXistException) IOException(java.io.IOException) BufferedOutputStream(java.io.BufferedOutputStream)

Example 44 with EXistException

use of org.exist.EXistException in project exist by eXist-db.

the class SecurityManagerImpl method attach.

/**
 * Initialize the security manager.
 *
 * Checks if the file users.xml exists in the system collection of the database.
 * If not, it is created with two default users: admin and guest.
 *
 * @param broker the database broker
 */
@Override
public void attach(final DBBroker broker, final Txn transaction) throws EXistException {
    // TODO: check that db is same?
    db = broker.getDatabase();
    Collection systemCollection = null;
    try {
        systemCollection = broker.getCollection(XmldbURI.SYSTEM_COLLECTION_URI);
        if (systemCollection == null) {
            systemCollection = broker.getOrCreateCollection(transaction, XmldbURI.SYSTEM_COLLECTION_URI);
            if (systemCollection == null) {
                return;
            }
            systemCollection.setPermissions(broker, Permission.DEFAULT_SYSTEM_COLLECTION_PERM);
            broker.saveCollection(transaction, systemCollection);
        }
    } catch (final Exception e) {
        LOG.error("Setting /db/system permissions failed: {}", e.getMessage(), e);
    }
    try {
        collection = broker.getCollection(SECURITY_COLLECTION_URI);
        if (collection == null) {
            collection = broker.getOrCreateCollection(transaction, SECURITY_COLLECTION_URI);
            if (collection == null) {
                LOG.error("Collection '/db/system/security' can't be created. Database may be corrupt!");
                return;
            }
            collection.setPermissions(broker, Permission.DEFAULT_SYSTEM_SECURITY_COLLECTION_PERM);
            broker.saveCollection(transaction, collection);
        }
    } catch (final Exception e) {
        e.printStackTrace();
        LOG.error("Loading security configuration failed: {}", e.getMessage(), e);
    }
    final Configuration _config_ = Configurator.parse(this, broker, collection, CONFIG_FILE_URI);
    configuration = Configurator.configure(this, _config_);
    for (final Realm realm : realms) {
        realm.start(broker, transaction);
    }
}
Also used : Configuration(org.exist.config.Configuration) Collection(org.exist.collections.Collection) AbstractRealm(org.exist.security.AbstractRealm) Realm(org.exist.security.realm.Realm) ConfigurationException(org.exist.config.ConfigurationException) PermissionDeniedException(org.exist.security.PermissionDeniedException) AuthenticationException(org.exist.security.AuthenticationException) BrokerPoolServiceException(org.exist.storage.BrokerPoolServiceException) EXistException(org.exist.EXistException)

Example 45 with EXistException

use of org.exist.EXistException in project exist by eXist-db.

the class DatabaseResources method executeQuery.

public Sequence executeQuery(String queryPath, Map<String, String> params, Subject user) {
    final String namespace = params.get(TARGETNAMESPACE);
    final String publicId = params.get(PUBLICID);
    final String catalogPath = params.get(CATALOG);
    final String collection = params.get(COLLECTION);
    if (logger.isDebugEnabled()) {
        logger.debug("collection={} namespace={} publicId={} catalogPath={}", collection, namespace, publicId, catalogPath);
    }
    Sequence result = null;
    try (final DBBroker broker = brokerPool.get(Optional.ofNullable(user))) {
        final XQuery xquery = brokerPool.getXQueryService();
        final XQueryContext context = new XQueryContext(brokerPool);
        if (collection != null) {
            context.declareVariable(COLLECTION, collection);
        }
        if (namespace != null) {
            context.declareVariable(TARGETNAMESPACE, namespace);
        }
        if (publicId != null) {
            context.declareVariable(PUBLICID, publicId);
        }
        if (catalogPath != null) {
            context.declareVariable(CATALOG, catalogPath);
        }
        CompiledXQuery compiled = xquery.compile(context, new ClassLoaderSource(queryPath));
        result = xquery.execute(broker, compiled, null);
    } catch (final EXistException | XPathException | IOException | PermissionDeniedException ex) {
        logger.error("Problem executing xquery", ex);
        result = null;
    }
    return result;
}
Also used : ClassLoaderSource(org.exist.source.ClassLoaderSource) DBBroker(org.exist.storage.DBBroker) XPathException(org.exist.xquery.XPathException) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQuery(org.exist.xquery.XQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQueryContext(org.exist.xquery.XQueryContext) PermissionDeniedException(org.exist.security.PermissionDeniedException) Sequence(org.exist.xquery.value.Sequence) EXistException(org.exist.EXistException) IOException(java.io.IOException)

Aggregations

EXistException (org.exist.EXistException)218 PermissionDeniedException (org.exist.security.PermissionDeniedException)80 IOException (java.io.IOException)63 DBBroker (org.exist.storage.DBBroker)58 Txn (org.exist.storage.txn.Txn)46 XmldbURI (org.exist.xmldb.XmldbURI)42 Collection (org.exist.collections.Collection)41 SAXException (org.xml.sax.SAXException)32 LockException (org.exist.util.LockException)31 DocumentImpl (org.exist.dom.persistent.DocumentImpl)28 Subject (org.exist.security.Subject)23 XPathException (org.exist.xquery.XPathException)22 LockedDocument (org.exist.dom.persistent.LockedDocument)21 TriggerException (org.exist.collections.triggers.TriggerException)20 Path (java.nio.file.Path)19 URISyntaxException (java.net.URISyntaxException)18 BrokerPool (org.exist.storage.BrokerPool)18 TransactionManager (org.exist.storage.txn.TransactionManager)18 InputSource (org.xml.sax.InputSource)18 Sequence (org.exist.xquery.value.Sequence)17