Search in sources :

Example 46 with Collection

use of org.exist.collections.Collection in project exist by eXist-db.

the class NGramIndexWorker method search.

public NodeSet search(final int contextId, final DocumentSet docs, final List<QName> qnames, final String query, final String ngram, final XQueryContext context, final NodeSet contextSet, final int axis) throws XPathException {
    final List<QName> searchQnames;
    if (qnames == null || qnames.isEmpty()) {
        searchQnames = getDefinedIndexes(context.getBroker(), docs);
    } else {
        searchQnames = qnames;
    }
    final NodeSet result = new ExtArrayNodeSet(docs.getDocumentCount(), 250);
    for (final Iterator<Collection> iter = docs.getCollectionIterator(); iter.hasNext(); ) {
        final int collectionId = iter.next().getId();
        for (final QName qname : searchQnames) {
            final NGramQNameKey key = new NGramQNameKey(collectionId, qname, index.getBrokerPool().getSymbols(), query);
            try (final ManagedLock<ReentrantLock> dbLock = lockManager.acquireBtreeReadLock(index.db.getLockName())) {
                final SearchCallback cb = new SearchCallback(contextId, query, ngram, docs, contextSet, context, result, axis == NodeSet.ANCESTOR);
                final int op = query.codePointCount(0, query.length()) < getN() ? IndexQuery.TRUNC_RIGHT : IndexQuery.EQ;
                index.db.query(new IndexQuery(op, key), cb);
            } catch (final LockException e) {
                LOG.warn("Failed to acquire lock for '{}'", FileUtils.fileName(index.db.getFile()), e);
            } catch (final IOException | BTreeException e) {
                LOG.error("{} in '{}'", e.getMessage(), FileUtils.fileName(index.db.getFile()), e);
            }
        }
    }
    // ensure result is ready to use
    result.iterate();
    return result;
}
Also used : ExtArrayNodeSet(org.exist.dom.persistent.ExtArrayNodeSet) NodeSet(org.exist.dom.persistent.NodeSet) ReentrantLock(java.util.concurrent.locks.ReentrantLock) IndexQuery(org.exist.storage.btree.IndexQuery) QName(org.exist.dom.QName) IOException(java.io.IOException) BTreeException(org.exist.storage.btree.BTreeException) ExtArrayNodeSet(org.exist.dom.persistent.ExtArrayNodeSet) Collection(org.exist.collections.Collection)

Example 47 with Collection

use of org.exist.collections.Collection in project exist by eXist-db.

the class LuceneMatchListenerTest method startDB.

@BeforeClass
public static void startDB() throws DatabaseConfigurationException, EXistException, PermissionDeniedException, IOException, TriggerException {
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    final TransactionManager transact = pool.getTransactionManager();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = transact.beginTransaction()) {
        final Collection root = broker.getOrCreateCollection(transaction, TestConstants.TEST_COLLECTION_URI);
        assertNotNull(root);
        broker.saveCollection(transaction, root);
        transact.commit(transaction);
    }
    final Map<String, String> m = new HashMap<>();
    m.put(Namespaces.EXIST_NS_PREFIX, Namespaces.EXIST_NS);
    final NamespaceContext ctx = new SimpleNamespaceContext(m);
    XMLUnit.setXpathNamespaceContext(ctx);
}
Also used : DBBroker(org.exist.storage.DBBroker) HashMap(java.util.HashMap) TransactionManager(org.exist.storage.txn.TransactionManager) NamespaceContext(org.custommonkey.xmlunit.NamespaceContext) SimpleNamespaceContext(org.custommonkey.xmlunit.SimpleNamespaceContext) Collection(org.exist.collections.Collection) Txn(org.exist.storage.txn.Txn) SimpleNamespaceContext(org.custommonkey.xmlunit.SimpleNamespaceContext) BrokerPool(org.exist.storage.BrokerPool) BeforeClass(org.junit.BeforeClass)

Example 48 with Collection

use of org.exist.collections.Collection in project exist by eXist-db.

the class ExistDocument method delete.

/**
 * Remove document from database.
 */
void delete() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Deleting {}", xmldbUri);
    }
    // Need to split path into collection and document name
    final XmldbURI collName = xmldbUri.removeLastSegment();
    final XmldbURI docName = xmldbUri.lastSegment();
    final TransactionManager txnManager = brokerPool.getTransactionManager();
    try (final DBBroker broker = brokerPool.get(Optional.ofNullable(subject));
        final Txn txn = txnManager.beginTransaction();
        final Collection collection = broker.openCollection(collName, LockMode.WRITE_LOCK)) {
        // Open collection if possible, else abort
        if (collection == null) {
            LOG.debug("Collection does not exist");
            txnManager.abort(txn);
            return;
        }
        // Open document if possible, else abort
        try (final LockedDocument lockedResource = collection.getDocumentWithLock(broker, docName, LockMode.WRITE_LOCK)) {
            if (lockedResource == null) {
                LOG.debug("No resource found for path: {}", xmldbUri);
                txnManager.abort(txn);
                return;
            }
            final DocumentImpl resource = lockedResource.getDocument();
            if (resource.getResourceType() == DocumentImpl.BINARY_FILE) {
                collection.removeBinaryResource(txn, broker, resource.getFileURI());
            } else {
                collection.removeXMLResource(txn, broker, resource.getFileURI());
            }
            // NOTE: early release of Collection lock inline with Asymmetrical Locking scheme
            collection.close();
            // Commit change
            txnManager.commit(txn);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Document deleted sucessfully");
            }
        }
    } catch (final LockException e) {
        LOG.error("Resource is locked.", e);
    } catch (final EXistException | IOException | TriggerException | PermissionDeniedException e) {
        LOG.error(e);
    } finally {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Finished delete");
        }
    }
}
Also used : Txn(org.exist.storage.txn.Txn) EXistException(org.exist.EXistException) IOException(java.io.IOException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) DBBroker(org.exist.storage.DBBroker) LockException(org.exist.util.LockException) TransactionManager(org.exist.storage.txn.TransactionManager) LockedDocument(org.exist.dom.persistent.LockedDocument) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) TriggerException(org.exist.collections.triggers.TriggerException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 49 with Collection

use of org.exist.collections.Collection in project exist by eXist-db.

the class ExistResourceFactory method getResourceType.

/*
     * Returns the resource type indicated by the path: either COLLECTION, DOCUMENT or NOT_EXISTING.
     */
private ResourceType getResourceType(BrokerPool brokerPool, XmldbURI xmldbUri) {
    ResourceType type = ResourceType.NOT_EXISTING;
    // MacOsX finder specific files
    String documentSeqment = xmldbUri.lastSegment().toString();
    if (documentSeqment.startsWith("._") || documentSeqment.equals(".DS_Store")) {
    // LOG.debug(String.format("Ignoring MacOSX file '%s'", xmldbUri.lastSegment().toString()));
    // return ResourceType.IGNORABLE;
    }
    // Documents that start with a dot
    if (documentSeqment.startsWith(".")) {
    // LOG.debug(String.format("Ignoring '.' file '%s'", xmldbUri.lastSegment().toString()));
    // return ResourceType.IGNORABLE;
    }
    // is performed.
    try (final DBBroker broker = brokerPool.get(Optional.of(brokerPool.getSecurityManager().getSystemSubject()));
        final Collection collection = broker.openCollection(xmldbUri, LockMode.READ_LOCK)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Path: {}", xmldbUri);
        }
        // First check if resource is a collection
        if (collection != null) {
            type = ResourceType.COLLECTION;
        } else {
            // If it is not a collection, check if it is a document
            try (final LockedDocument lockedDoc = broker.getXMLResource(xmldbUri, LockMode.READ_LOCK)) {
                if (lockedDoc != null) {
                    // Document is found
                    type = ResourceType.DOCUMENT;
                } else {
                    // No document and no collection.
                    type = ResourceType.NOT_EXISTING;
                }
            }
        }
    } catch (final Exception ex) {
        LOG.error("Error determining nature of resource {}", xmldbUri.toString(), ex);
        type = ResourceType.NOT_EXISTING;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Resource type={}", type.toString());
    }
    return type;
}
Also used : DBBroker(org.exist.storage.DBBroker) LockedDocument(org.exist.dom.persistent.LockedDocument) Collection(org.exist.collections.Collection) URISyntaxException(java.net.URISyntaxException) EXistException(org.exist.EXistException)

Example 50 with Collection

use of org.exist.collections.Collection in project exist by eXist-db.

the class ExistCollection method initMetadata.

/**
 * Initialize Collection, authenticate() is required first
 */
@Override
public void initMetadata() {
    if (subject == null) {
        LOG.error("User not initialized yet");
        return;
    }
    // check if initialization is required
    if (isInitialized) {
        LOG.debug("Already initialized");
        return;
    }
    try (final DBBroker broker = brokerPool.get(Optional.of(subject));
        final Collection collection = broker.openCollection(xmldbUri, LockMode.READ_LOCK)) {
        if (collection == null) {
            LOG.error("Collection for {} cannot be opened for metadata", xmldbUri);
            return;
        }
        // Retrieve some meta data
        permissions = collection.getPermissionsNoLock();
        readAllowed = permissions.validate(subject, Permission.READ);
        writeAllowed = permissions.validate(subject, Permission.WRITE);
        executeAllowed = permissions.validate(subject, Permission.EXECUTE);
        creationTime = collection.getCreated();
        // Collection does not have more information.
        lastModified = creationTime;
        ownerUser = permissions.getOwner().getUsername();
        ownerGroup = permissions.getGroup().getName();
    } catch (final PermissionDeniedException | EXistException pde) {
        LOG.error(pde);
    }
    // Set flag
    isInitialized = true;
}
Also used : DBBroker(org.exist.storage.DBBroker) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) EXistException(org.exist.EXistException)

Aggregations

Collection (org.exist.collections.Collection)297 Txn (org.exist.storage.txn.Txn)160 XmldbURI (org.exist.xmldb.XmldbURI)99 DBBroker (org.exist.storage.DBBroker)89 TransactionManager (org.exist.storage.txn.TransactionManager)86 BrokerPool (org.exist.storage.BrokerPool)69 StringInputSource (org.exist.util.StringInputSource)57 Test (org.junit.Test)57 EXistException (org.exist.EXistException)43 PermissionDeniedException (org.exist.security.PermissionDeniedException)43 DocumentImpl (org.exist.dom.persistent.DocumentImpl)42 IOException (java.io.IOException)33 LockedDocument (org.exist.dom.persistent.LockedDocument)31 SAXException (org.xml.sax.SAXException)26 InputStream (java.io.InputStream)19 Path (java.nio.file.Path)19 Permission (org.exist.security.Permission)19 LockException (org.exist.util.LockException)16 TriggerException (org.exist.collections.triggers.TriggerException)15 BinaryDocument (org.exist.dom.persistent.BinaryDocument)15