Search in sources :

Example 91 with XmldbURI

use of org.exist.xmldb.XmldbURI in project exist by eXist-db.

the class UserXQueryJob method executeXQuery.

private void executeXQuery(final BrokerPool pool, final DBBroker broker, final Source source, final Properties params) throws PermissionDeniedException, XPathException, JobExecutionException {
    XQueryPool xqPool = null;
    CompiledXQuery compiled = null;
    XQueryContext context = null;
    try {
        // execute the xquery
        final XQuery xquery = pool.getXQueryService();
        xqPool = pool.getXQueryPool();
        // try and get a pre-compiled query from the pool
        compiled = xqPool.borrowCompiledXQuery(broker, source);
        if (compiled == null) {
            context = new XQueryContext(pool);
        } else {
            context = compiled.getContext();
            context.prepareForReuse();
        }
        if (source instanceof DBSource) {
            final XmldbURI collectionUri = ((DBSource) source).getDocumentPath().removeLastSegment();
            context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI.append(collectionUri.getCollectionPath()).toString());
            context.setStaticallyKnownDocuments(new XmldbURI[] { collectionUri });
        }
        if (compiled == null) {
            try {
                compiled = xquery.compile(context, source);
            } catch (final IOException e) {
                abort("Failed to read query from " + xqueryResource);
            }
        }
        // declare any parameters as external variables
        if (params != null) {
            String bindingPrefix = params.getProperty("bindingPrefix");
            if (bindingPrefix == null) {
                bindingPrefix = "local";
            }
            for (final Entry param : params.entrySet()) {
                final String key = (String) param.getKey();
                final String value = (String) param.getValue();
                context.declareVariable(bindingPrefix + ":" + key, new StringValue(value));
            }
        }
        xquery.execute(broker, compiled, null);
    } finally {
        if (context != null) {
            context.runCleanupTasks();
        }
        // return the compiled query to the pool
        if (xqPool != null && source != null && compiled != null) {
            xqPool.returnCompiledXQuery(source, compiled);
        }
    }
}
Also used : XQueryPool(org.exist.storage.XQueryPool) Entry(java.util.Map.Entry) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQuery(org.exist.xquery.XQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQueryContext(org.exist.xquery.XQueryContext) DBSource(org.exist.source.DBSource) IOException(java.io.IOException) StringValue(org.exist.xquery.value.StringValue) XmldbURI(org.exist.xmldb.XmldbURI)

Example 92 with XmldbURI

use of org.exist.xmldb.XmldbURI in project exist by eXist-db.

the class AbstractRealm method initialiseRealmStorage.

private void initialiseRealmStorage(final DBBroker broker, final Txn transaction) throws EXistException {
    final XmldbURI realmCollectionURL = SecurityManager.SECURITY_COLLECTION_URI.append(getId());
    try {
        collectionRealm = Utils.getOrCreateCollection(broker, transaction, realmCollectionURL);
        collectionAccounts = Utils.getOrCreateCollection(broker, transaction, realmCollectionURL.append("accounts"));
        collectionGroups = Utils.getOrCreateCollection(broker, transaction, realmCollectionURL.append("groups"));
        collectionRemovedAccounts = Utils.getOrCreateCollection(broker, transaction, realmCollectionURL.append("accounts").append("removed"));
        collectionRemovedGroups = Utils.getOrCreateCollection(broker, transaction, realmCollectionURL.append("groups").append("removed"));
    } catch (final PermissionDeniedException | IOException | TriggerException | LockException e) {
        throw new EXistException(e);
    }
}
Also used : LockException(org.exist.util.LockException) IOException(java.io.IOException) EXistException(org.exist.EXistException) TriggerException(org.exist.collections.triggers.TriggerException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 93 with XmldbURI

use of org.exist.xmldb.XmldbURI in project exist by eXist-db.

the class SecurityManagerImpl method processParameter.

@Override
public void processParameter(final DBBroker broker, final DocumentImpl document) throws ConfigurationException {
    XmldbURI uri = document.getCollection().getURI();
    final boolean isRemoved = uri.endsWith(SecurityManager.REMOVED_COLLECTION_URI);
    if (isRemoved) {
        uri = uri.removeLastSegment();
    }
    final boolean isAccount = uri.endsWith(SecurityManager.ACCOUNTS_COLLECTION_URI);
    final boolean isGroup = uri.endsWith(SecurityManager.GROUPS_COLLECTION_URI);
    if (isAccount || isGroup) {
        uri = uri.removeLastSegment();
        final String realmId = uri.lastSegment().toString();
        final AbstractRealm realm = (AbstractRealm) findRealmForRealmId(realmId);
        final Configuration conf = Configurator.parse(broker.getBrokerPool(), document);
        Integer id = -1;
        if (isRemoved) {
            id = conf.getPropertyInteger("id");
        }
        final String name = conf.getProperty("name");
        if (isAccount) {
            if (isRemoved && id > 2 && !hasUser(id)) {
                final AccountImpl account = new AccountImpl(realm, conf);
                account.removed = true;
                registerAccount(account);
            } else if (name != null) {
                if (realm.hasAccount(name)) {
                    final Integer oldId = saving.get(document.getURI());
                    final Integer newId = conf.getPropertyInteger("id");
                    if (!newId.equals(oldId)) {
                        final Account current = realm.getAccount(name);
                        try (final ManagedLock<ReadWriteLock> lock = ManagedLock.acquire(accountLocks.getLock(current), LockMode.WRITE_LOCK)) {
                            usersById.write(principalDb -> {
                                principalDb.remove(oldId);
                                principalDb.put(newId, current);
                            });
                        }
                    }
                } else {
                    final Account account = new AccountImpl(realm, conf);
                    if (account.getGroups().length == 0) {
                        try {
                            account.setPrimaryGroup(realm.getGroup(SecurityManager.UNKNOWN_GROUP));
                            LOG.warn("Account '{}' has no groups, but every account must have at least 1 group. Assigned group: " + SecurityManager.UNKNOWN_GROUP, account.getName());
                        } catch (final PermissionDeniedException e) {
                            throw new ConfigurationException("Account has no group, unable to default to " + SecurityManager.UNKNOWN_GROUP + ": " + e.getMessage(), e);
                        }
                    }
                    registerAccount(account);
                    realm.registerAccount(account);
                }
            } else {
                // this can't be! log any way
                LOG.error("Account '{}' already exists in realm: '{}', but received notification that a new one was created.", name, realmId);
            }
        } else if (isGroup) {
            if (isRemoved && id > 2 && !hasGroup(id)) {
                final GroupImpl group = new GroupImpl(realm, conf);
                group.removed = true;
                registerGroup(group);
            } else if (name != null && !realm.hasGroup(name)) {
                final GroupImpl group = new GroupImpl(realm, conf);
                registerGroup(group);
                realm.registerGroup(group);
            } else {
                // this can't be! log any way
                LOG.error("Group '{}' already exists in realm: '{}', but received notification that a new one was created.", name, realmId);
            }
        }
        saving.remove(document.getURI());
    }
}
Also used : LockMode(org.exist.storage.lock.Lock.LockMode) Txn(org.exist.storage.txn.Txn) BrokerPool(org.exist.storage.BrokerPool) ConfigurationException(org.exist.config.ConfigurationException) BiFunction(java.util.function.BiFunction) JobDescription(org.exist.scheduler.JobDescription) PermissionDeniedException(org.exist.security.PermissionDeniedException) ConcurrentValueWrapper(org.exist.util.ConcurrentValueWrapper) Configuration(org.exist.config.Configuration) Configurator(org.exist.config.Configurator) Map(java.util.Map) SchemaType(org.exist.security.SchemaType) Collection(org.exist.collections.Collection) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) JobExecutionContext(org.quartz.JobExecutionContext) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) AbstractRealm(org.exist.security.AbstractRealm) AuthenticationException(org.exist.security.AuthenticationException) GroupAider(org.exist.security.internal.aider.GroupAider) Session(org.exist.security.Session) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AtomicLazyVal(com.evolvedbinary.j8fu.lazy.AtomicLazyVal) Collectors(java.util.stream.Collectors) SecurityManager(org.exist.security.SecurityManager) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Principal(org.exist.security.Principal) ManagedLock(org.exist.storage.lock.ManagedLock) JobDataMap(org.quartz.JobDataMap) Realm(org.exist.security.realm.Realm) WeakLazyStripes(org.exist.util.WeakLazyStripes) ThreadSafe(net.jcip.annotations.ThreadSafe) HashMap(java.util.HashMap) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ArrayList(java.util.ArrayList) Account(org.exist.security.Account) Subject(org.exist.security.Subject) BrokerPoolServiceException(org.exist.storage.BrokerPoolServiceException) XmldbURI(org.exist.xmldb.XmldbURI) SimpleTrigger(org.quartz.SimpleTrigger) DocumentImpl(org.exist.dom.persistent.DocumentImpl) EXistException(org.exist.EXistException) Permission(org.exist.security.Permission) Database(org.exist.Database) Properties(java.util.Properties) Group(org.exist.security.Group) BrokerPoolService(org.exist.storage.BrokerPoolService) org.exist.config.annotation(org.exist.config.annotation) DBBroker(org.exist.storage.DBBroker) Int2ObjectMap(it.unimi.dsi.fastutil.ints.Int2ObjectMap) LogManager(org.apache.logging.log4j.LogManager) Account(org.exist.security.Account) Configuration(org.exist.config.Configuration) AbstractRealm(org.exist.security.AbstractRealm) ManagedLock(org.exist.storage.lock.ManagedLock) ConfigurationException(org.exist.config.ConfigurationException) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 94 with XmldbURI

use of org.exist.xmldb.XmldbURI in project exist by eXist-db.

the class RepoBackup method restore.

public static void restore(final Txn transaction, final DBBroker broker) throws IOException, PermissionDeniedException {
    final XmldbURI docPath = XmldbURI.createInternal(XmldbURI.ROOT_COLLECTION + "/" + REPO_ARCHIVE);
    try (final LockedDocument lockedDoc = broker.getXMLResource(docPath, LockMode.READ_LOCK)) {
        if (lockedDoc == null) {
            return;
        }
        final DocumentImpl doc = lockedDoc.getDocument();
        if (doc.getResourceType() != DocumentImpl.BINARY_FILE) {
            throw new IOException(docPath + " is not a binary resource");
        }
        try (final InputStream is = broker.getBrokerPool().getBlobStore().get(transaction, ((BinaryDocument) doc).getBlobId())) {
            final Path directory = ExistRepository.getRepositoryDir(broker.getConfiguration());
            unzip(doc.getURI(), is, directory);
        }
    }
}
Also used : Path(java.nio.file.Path) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) LockedDocument(org.exist.dom.persistent.LockedDocument) IOException(java.io.IOException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) XmldbURI(org.exist.xmldb.XmldbURI)

Example 95 with XmldbURI

use of org.exist.xmldb.XmldbURI in project exist by eXist-db.

the class EnsureLockingAspect method enforceEnsureLockedReturnType.

/**
 * Ensures that the object returned by a method
 * has an lock taken upon it before it is returned.
 *
 * @param joinPoint the join point of the aspect
 *
 * @param result the result of the instrumented method
 *
 * @throws LockException if the appropriate locks are not held and
 *  the System property `exist.ensurelocking.enforce=true` is set.
 */
@AfterReturning(value = "methodWithEnsureLockedReturnType()", returning = "result")
public void enforceEnsureLockedReturnType(final JoinPoint joinPoint, final Object result) throws Throwable {
    if (DISABLED) {
        return;
    }
    final MethodSignature ms = (MethodSignature) joinPoint.getSignature();
    final Method method = ms.getMethod();
    final AnnotatedMethodConstraint<EnsureLocked> ensureLockedConstraint = getMethodAnnotation(method, EnsureLocked.class);
    final EnsureLockDetail ensureLockDetail = resolveLockDetail(ensureLockedConstraint, joinPoint.getArgs());
    traceln(() -> "Checking: " + toAnnotationString(EnsureLocked.class, ensureLockDetail) + " method=" + ms.getDeclaringType().getName() + "#" + ms.getName() + " ...");
    // check the lock constraint holds
    boolean failed = false;
    if (result != null) {
        final LockManager lockManager = getLockManager();
        if (lockManager != null) {
            switch(ensureLockDetail.type) {
                case COLLECTION:
                    final XmldbURI collectionUri;
                    if (XmldbURI.class.isAssignableFrom(result.getClass())) {
                        collectionUri = (XmldbURI) result;
                    } else {
                        collectionUri = ((Collection) result).getURI();
                    }
                    if (!hasCollectionLock(lockManager, collectionUri, ensureLockDetail)) {
                        report("FAILED: Constraint to require lock mode " + ensureLockDetail.mode + " on Collection: " + collectionUri);
                        failed = true;
                    }
                    break;
                case DOCUMENT:
                    final XmldbURI documentUri;
                    if (XmldbURI.class.isAssignableFrom(result.getClass())) {
                        documentUri = (XmldbURI) result;
                    } else {
                        documentUri = ((DocumentImpl) result).getURI();
                    }
                    if (!hasDocumentLock(lockManager, documentUri, ensureLockDetail)) {
                        report("FAILED: Constraint to require lock mode " + ensureLockDetail.mode + " on Document: " + documentUri + " FAILED");
                        failed = true;
                    }
                    break;
                default:
                    throw new UnsupportedOperationException("Currently only Collection or Document locks are supported");
            }
        }
    } else {
        traceln(() -> "Unable to check return type as value is null!");
    }
    if (!failed) {
        traceln(() -> "PASSED.");
    }
}
Also used : MethodSignature(org.aspectj.lang.reflect.MethodSignature) Method(java.lang.reflect.Method) XmldbURI(org.exist.xmldb.XmldbURI)

Aggregations

XmldbURI (org.exist.xmldb.XmldbURI)260 Collection (org.exist.collections.Collection)100 PermissionDeniedException (org.exist.security.PermissionDeniedException)69 Test (org.junit.Test)56 Txn (org.exist.storage.txn.Txn)55 EXistException (org.exist.EXistException)42 URISyntaxException (java.net.URISyntaxException)39 LockedDocument (org.exist.dom.persistent.LockedDocument)39 IOException (java.io.IOException)38 DBBroker (org.exist.storage.DBBroker)38 DocumentImpl (org.exist.dom.persistent.DocumentImpl)34 SAXException (org.xml.sax.SAXException)33 Permission (org.exist.security.Permission)30 LockException (org.exist.util.LockException)27 Path (java.nio.file.Path)22 XPathException (org.exist.xquery.XPathException)22 BrokerPool (org.exist.storage.BrokerPool)21 TransactionManager (org.exist.storage.txn.TransactionManager)20 Subject (org.exist.security.Subject)19 StringInputSource (org.exist.util.StringInputSource)17