Search in sources :

Example 6 with DateTimeValue

use of org.exist.xquery.value.DateTimeValue in project exist by eXist-db.

the class GetRunningJobs method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (!context.getSubject().hasDbaRole()) {
        throw (new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to get the list of running jobs"));
    }
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("jobs", NAMESPACE_URI, PREFIX), null);
        final BrokerPool brokerPool = context.getBroker().getBrokerPool();
        final ProcessMonitor monitor = brokerPool.getProcessMonitor();
        final ProcessMonitor.JobInfo[] jobs = monitor.runningJobs();
        for (ProcessMonitor.JobInfo job : jobs) {
            final Thread process = job.getThread();
            final Date startDate = new Date(job.getStartTime());
            builder.startElement(new QName("job", NAMESPACE_URI, PREFIX), null);
            builder.addAttribute(new QName("id", null, null), process.getName());
            builder.addAttribute(new QName("action", null, null), job.getAction());
            builder.addAttribute(new QName("start", null, null), new DateTimeValue(startDate).getStringValue());
            builder.addAttribute(new QName("info", null, null), job.getAddInfo().toString());
            builder.endElement();
        }
        builder.endElement();
        builder.endDocument();
        return (NodeValue) builder.getDocument().getDocumentElement();
    } finally {
        context.popDocumentContext();
    }
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) QName(org.exist.dom.QName) ProcessMonitor(org.exist.storage.ProcessMonitor) BrokerPool(org.exist.storage.BrokerPool) Date(java.util.Date)

Example 7 with DateTimeValue

use of org.exist.xquery.value.DateTimeValue in project exist by eXist-db.

the class Directory method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    if (!context.getSubject().hasDbaRole()) {
        XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to call this function.");
        logger.error("Invalid user", xPathException);
        throw xPathException;
    }
    final String inputPath = args[0].getStringValue();
    final Path directoryPath = FileModuleHelper.getFile(inputPath);
    if (logger.isDebugEnabled()) {
        logger.debug("Listing matching files in directory: {}", directoryPath.toAbsolutePath().toString());
    }
    if (!Files.isDirectory(directoryPath)) {
        throw new XPathException(this, "'" + inputPath + "' does not point to a valid directory.");
    }
    // Get list of files, null if baseDir does not point to a directory
    context.pushDocumentContext();
    try (final Stream<Path> scannedFiles = Files.list(directoryPath)) {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("list", null, null), null);
        scannedFiles.forEach(entry -> {
            if (logger.isDebugEnabled()) {
                logger.debug("Found: {}", entry.toAbsolutePath().toString());
            }
            String entryType = "unknown";
            if (Files.isRegularFile(entry)) {
                entryType = "file";
            } else if (Files.isDirectory(entry)) {
                entryType = "directory";
            }
            builder.startElement(new QName(entryType, NAMESPACE_URI, PREFIX), null);
            builder.addAttribute(new QName("name", null, null), FileUtils.fileName(entry));
            try {
                if (Files.isRegularFile(entry)) {
                    final Long sizeLong = Files.size(entry);
                    String sizeString = Long.toString(sizeLong);
                    String humanSize = getHumanSize(sizeLong, sizeString);
                    builder.addAttribute(new QName("size", null, null), sizeString);
                    builder.addAttribute(new QName("human-size", null, null), humanSize);
                }
                builder.addAttribute(new QName("modified", null, null), new DateTimeValue(new Date(Files.getLastModifiedTime(entry).toMillis())).getStringValue());
                builder.addAttribute(new QName("hidden", null, null), new BooleanValue(Files.isHidden(entry)).getStringValue());
                builder.addAttribute(new QName("canRead", null, null), new BooleanValue(Files.isReadable(entry)).getStringValue());
                builder.addAttribute(new QName("canWrite", null, null), new BooleanValue(Files.isWritable(entry)).getStringValue());
            } catch (final IOException | XPathException ioe) {
                LOG.warn(ioe);
            }
            builder.endElement();
        });
        builder.endElement();
        return (NodeValue) builder.getDocument().getDocumentElement();
    } catch (final IOException ioe) {
        throw new XPathException(this, ioe);
    } finally {
        context.popDocumentContext();
    }
}
Also used : Path(java.nio.file.Path) NodeValue(org.exist.xquery.value.NodeValue) DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) QName(org.exist.dom.QName) IOException(java.io.IOException) Date(java.util.Date) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) BooleanValue(org.exist.xquery.value.BooleanValue)

Example 8 with DateTimeValue

use of org.exist.xquery.value.DateTimeValue in project exist by eXist-db.

the class Deployment method storeRepoXML.

/**
 * Store repo.xml into the db. Adds the time of deployment to the descriptor.
 *
 * @param repoXML
 * @param targetCollection
 * @throws XPathException
 */
private void storeRepoXML(final DBBroker broker, final Txn transaction, final DocumentImpl repoXML, final XmldbURI targetCollection, final Optional<RequestedPerms> requestedPerms) throws PackageException, XPathException {
    // Store repo.xml
    final DateTimeValue time = new DateTimeValue(new Date());
    final MemTreeBuilder builder = new MemTreeBuilder();
    builder.startDocument();
    final UpdatingDocumentReceiver receiver = new UpdatingDocumentReceiver(builder, time.getStringValue());
    try {
        repoXML.copyTo(broker, receiver);
    } catch (final SAXException e) {
        throw new PackageException("Error while updating repo.xml in-memory: " + e.getMessage(), e);
    }
    builder.endDocument();
    final DocumentImpl updatedXML = builder.getDocument();
    try {
        final Collection collection = broker.getOrCreateCollection(transaction, targetCollection);
        final XmldbURI name = XmldbURI.createInternal("repo.xml");
        final Permission permission = PermissionFactory.getDefaultResourcePermission(broker.getBrokerPool().getSecurityManager());
        setPermissions(broker, requestedPerms, false, MimeType.XML_TYPE, permission);
        collection.storeDocument(transaction, broker, name, updatedXML, MimeType.XML_TYPE, null, null, permission, null, null);
    } catch (final PermissionDeniedException | IOException | SAXException | LockException | EXistException e) {
        throw new PackageException("Error while storing updated repo.xml: " + e.getMessage(), e);
    }
}
Also used : DateTimeValue(org.exist.xquery.value.DateTimeValue) IOException(java.io.IOException) EXistException(org.exist.EXistException) SAXException(org.xml.sax.SAXException) UnixStylePermission(org.exist.security.UnixStylePermission) Permission(org.exist.security.Permission) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 9 with DateTimeValue

use of org.exist.xquery.value.DateTimeValue in project exist by eXist-db.

the class FunDateTime method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().start(this);
        context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
        if (contextSequence != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
        }
    }
    Sequence result;
    if (args[0].isEmpty() || args[1].isEmpty()) {
        result = Sequence.EMPTY_SEQUENCE;
    } else if (args[0].hasMany()) {
        throw new XPathException(this, ErrorCodes.XPTY0004, "Expected at most one xs:date", args[0]);
    } else if (args[1].hasMany()) {
        throw new XPathException(this, ErrorCodes.XPTY0004, "Expected at most one xs:time", args[1]);
    } else {
        final DateValue dv = (DateValue) args[0].itemAt(0);
        final TimeValue tv = (TimeValue) args[1].itemAt(0);
        if (!dv.getTimezone().isEmpty()) {
            if (!tv.getTimezone().isEmpty()) {
                if (!((DayTimeDurationValue) dv.getTimezone().itemAt(0)).compareTo(null, Comparison.EQ, ((DayTimeDurationValue) tv.getTimezone().itemAt(0)))) {
                    final ValueSequence argsSeq = new ValueSequence();
                    argsSeq.add(dv);
                    argsSeq.add(tv);
                    throw new XPathException(this, ErrorCodes.FORG0008, "Operands have different timezones", argsSeq);
                }
            }
        }
        String dtv = ((DateTimeValue) dv.convertTo(Type.DATE_TIME)).getTrimmedCalendar().toXMLFormat();
        if (dv.getTimezone().isEmpty()) {
            dtv = dtv.substring(0, dtv.length() - 8);
            result = new DateTimeValue(dtv + tv.getStringValue());
        } else if ("PT0S".equals(((DayTimeDurationValue) dv.getTimezone().itemAt(0)).getStringValue())) {
            dtv = dtv.substring(0, dtv.length() - 9);
            if (tv.getTimezone().isEmpty()) {
                result = new DateTimeValue(dtv + tv.getStringValue() + "Z");
            } else {
                result = new DateTimeValue(dtv + tv.getStringValue());
            }
        } else {
            if (tv.getTimezone().isEmpty()) {
                final String tz = dtv.substring(19);
                dtv = dtv.substring(0, dtv.length() - 14);
                result = new DateTimeValue(dtv + tv.getStringValue() + tz);
            } else {
                dtv = dtv.substring(0, dtv.length() - 14);
                result = new DateTimeValue(dtv + tv.getStringValue());
            }
        }
    }
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().end(this, "", result);
    }
    return result;
}
Also used : DayTimeDurationValue(org.exist.xquery.value.DayTimeDurationValue) DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) DateValue(org.exist.xquery.value.DateValue) ValueSequence(org.exist.xquery.value.ValueSequence) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) TimeValue(org.exist.xquery.value.TimeValue) DateTimeValue(org.exist.xquery.value.DateTimeValue)

Example 10 with DateTimeValue

use of org.exist.xquery.value.DateTimeValue in project exist by eXist-db.

the class RestoreHandler method restoreResourceEntry.

private DeferredPermission restoreResourceEntry(final Attributes atts) throws SAXException {
    @Nullable final String skip = atts.getValue("skip");
    // Don't process entries which should be skipped
    if (skip != null && !"no".equals(skip)) {
        return new SkippedEntryDeferredPermission();
    }
    @Nullable final String name = atts.getValue("name");
    if (name == null) {
        throw new SAXException("Resource requires a name attribute");
    }
    final boolean xmlType = Optional.ofNullable(atts.getValue("type")).filter(s -> s.equals("XMLResource")).isPresent();
    final String owner = getAttr(atts, "owner", SecurityManager.SYSTEM);
    final String group = getAttr(atts, "group", SecurityManager.DBA_GROUP);
    final String perms = getAttr(atts, "mode", "644");
    final String filename = getAttr(atts, "filename", name);
    @Nullable final String mimeTypeStr = atts.getValue("mimetype");
    @Nullable final String dateCreatedStr = atts.getValue("created");
    @Nullable final String dateModifiedStr = atts.getValue("modified");
    @Nullable final String publicId = atts.getValue("publicid");
    @Nullable final String systemId = atts.getValue("systemid");
    @Nullable final String nameDocType = atts.getValue("namedoctype");
    final XmldbURI docName;
    if (version >= STRICT_URI_VERSION) {
        docName = XmldbURI.create(name);
    } else {
        try {
            docName = URIUtils.encodeXmldbUriFor(name);
        } catch (final URISyntaxException e) {
            final String msg = "Could not parse document name into a URI: " + e.getMessage();
            listener.error(msg);
            LOG.error(msg, e);
            return new SkippedEntryDeferredPermission();
        }
    }
    final EXistInputSource is;
    if (deduplicateBlobs && !xmlType) {
        final String blobId = atts.getValue("blob-id");
        is = descriptor.getBlobInputSource(blobId);
        if (is == null) {
            final String msg = "Failed to restore resource '" + name + "'\nfrom BLOB '" + blobId + "'.\nReason: Unable to obtain its EXistInputSource";
            listener.warn(msg);
            return new SkippedEntryDeferredPermission();
        }
    } else {
        is = descriptor.getInputSource(filename);
        if (is == null) {
            final String msg = "Failed to restore resource '" + name + "'\nfrom file '" + descriptor.getSymbolicPath(name, false) + "'.\nReason: Unable to obtain its EXistInputSource";
            listener.warn(msg);
            return new SkippedEntryDeferredPermission();
        }
    }
    MimeType mimeType = null;
    if (mimeTypeStr != null) {
        mimeType = MimeTable.getInstance().getContentType(mimeTypeStr);
    }
    if (mimeType == null) {
        mimeType = xmlType ? MimeType.XML_TYPE : MimeType.BINARY_TYPE;
    }
    Date dateCreated = null;
    if (dateCreatedStr != null) {
        try {
            dateCreated = new DateTimeValue(dateCreatedStr).getDate();
        } catch (final XPathException xpe) {
            listener.warn("Illegal creation date. Ignoring date...");
        }
    }
    Date dateModified = null;
    if (dateModifiedStr != null) {
        try {
            dateModified = new DateTimeValue(dateModifiedStr).getDate();
        } catch (final XPathException xpe) {
            listener.warn("Illegal modification date. Ignoring date...");
        }
    }
    final DocumentType docType;
    if (publicId != null || systemId != null) {
        docType = new DocumentTypeImpl(nameDocType, publicId, systemId);
    } else {
        docType = null;
    }
    final XmldbURI docUri = currentCollectionUri.append(docName);
    try {
        try (final Txn transaction = beginTransaction()) {
            boolean validated = false;
            try {
                try (final Collection collection = broker.openCollection(currentCollectionUri, Lock.LockMode.WRITE_LOCK);
                    final ManagedDocumentLock docLock = broker.getBrokerPool().getLockManager().acquireDocumentWriteLock(docUri)) {
                    broker.storeDocument(transaction, docName, is, mimeType, dateCreated, dateModified, null, docType, null, collection);
                    validated = true;
                    transaction.commit();
                    // NOTE: early release of Collection lock inline with Asymmetrical Locking scheme
                    collection.close();
                }
            } finally {
                /*
                        This allows us to commit the transaction (so the restore doesn't stop)
                        and still throw an exception to skip over resources that didn't
                        validate. This preserves eXist-db's previous behaviour
                        of "best effort attempt" when restoring a backup,
                        rather than an ACID "all or nothing" approach.
                     */
                if (!validated) {
                    // because `validated == false` we know that there have only been reads on the transaction/sub-transaction!
                    transaction.commit();
                }
            }
        }
        final DeferredPermission deferredPermission;
        if (name.startsWith(XmldbURI.SYSTEM_COLLECTION)) {
            // prevents restore of a backup from changing system collection resource ownership
            deferredPermission = new ResourceDeferredPermission(listener, docUri, SecurityManager.SYSTEM, SecurityManager.DBA_GROUP, Integer.parseInt(perms, 8));
        } else {
            deferredPermission = new ResourceDeferredPermission(listener, docUri, owner, group, Integer.parseInt(perms, 8));
        }
        listener.restoredResource(name);
        return deferredPermission;
    } catch (final Exception e) {
        final String message = String.format("Failed to restore resource '%s'\nfrom file '%s'.\nReason: %s", name, descriptor.getSymbolicPath(name, false), e.getMessage());
        listener.warn(message);
        LOG.error(message, e);
        return new SkippedEntryDeferredPermission();
    } finally {
        is.close();
    }
}
Also used : URIUtils(org.exist.xquery.util.URIUtils) Tuple2(com.evolvedbinary.j8fu.tuple.Tuple2) Txn(org.exist.storage.txn.Txn) java.util(java.util) URISyntaxException(java.net.URISyntaxException) ManagedCollectionLock(org.exist.storage.lock.ManagedCollectionLock) PermissionDeniedException(org.exist.security.PermissionDeniedException) Tuple(com.evolvedbinary.j8fu.tuple.Tuple.Tuple) XMLReader(org.xml.sax.XMLReader) ACLPermission(org.exist.security.ACLPermission) Namespaces(org.exist.Namespaces) RealmImpl(org.exist.security.internal.RealmImpl) Collection(org.exist.collections.Collection) XmldbURI(org.exist.xmldb.XmldbURI) Attributes(org.xml.sax.Attributes) DateTimeValue(org.exist.xquery.value.DateTimeValue) Lock(org.exist.storage.lock.Lock) Permission(org.exist.security.Permission) Nullable(javax.annotation.Nullable) ManagedDocumentLock(org.exist.storage.lock.ManagedDocumentLock) RestoreListener(org.exist.backup.restore.listener.RestoreListener) LockedDocument(org.exist.dom.persistent.LockedDocument) UTF_8(java.nio.charset.StandardCharsets.UTF_8) IOException(java.io.IOException) TransactionException(org.exist.storage.txn.TransactionException) DocumentType(org.w3c.dom.DocumentType) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SecurityManager(org.exist.security.SecurityManager) SAXParseException(org.xml.sax.SAXParseException) Logger(org.apache.logging.log4j.Logger) BackupDescriptor(org.exist.backup.BackupDescriptor) DBBroker(org.exist.storage.DBBroker) LockManager(org.exist.storage.lock.LockManager) SAXException(org.xml.sax.SAXException) org.exist.util(org.exist.util) DocumentTypeImpl(org.exist.dom.persistent.DocumentTypeImpl) TriggerException(org.exist.collections.triggers.TriggerException) LogManager(org.apache.logging.log4j.LogManager) BinaryDocument(org.exist.dom.persistent.BinaryDocument) XPathException(org.exist.xquery.XPathException) DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) DocumentTypeImpl(org.exist.dom.persistent.DocumentTypeImpl) DocumentType(org.w3c.dom.DocumentType) URISyntaxException(java.net.URISyntaxException) Txn(org.exist.storage.txn.Txn) URISyntaxException(java.net.URISyntaxException) PermissionDeniedException(org.exist.security.PermissionDeniedException) IOException(java.io.IOException) TransactionException(org.exist.storage.txn.TransactionException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) TriggerException(org.exist.collections.triggers.TriggerException) XPathException(org.exist.xquery.XPathException) SAXException(org.xml.sax.SAXException) ManagedDocumentLock(org.exist.storage.lock.ManagedDocumentLock) Collection(org.exist.collections.Collection) Nullable(javax.annotation.Nullable) XmldbURI(org.exist.xmldb.XmldbURI)

Aggregations

DateTimeValue (org.exist.xquery.value.DateTimeValue)19 XPathException (org.exist.xquery.XPathException)12 Date (java.util.Date)9 IOException (java.io.IOException)8 Permission (org.exist.security.Permission)6 PermissionDeniedException (org.exist.security.PermissionDeniedException)5 XmldbURI (org.exist.xmldb.XmldbURI)5 SAXException (org.xml.sax.SAXException)5 Collection (org.exist.collections.Collection)4 QName (org.exist.dom.QName)4 ACLPermission (org.exist.security.ACLPermission)4 Path (java.nio.file.Path)3 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)3 SAXSerializer (org.exist.util.serializer.SAXSerializer)3 Sequence (org.exist.xquery.value.Sequence)3 AttributesImpl (org.xml.sax.helpers.AttributesImpl)3 Tuple (com.evolvedbinary.j8fu.tuple.Tuple.Tuple)2 Tuple2 (com.evolvedbinary.j8fu.tuple.Tuple2)2 URISyntaxException (java.net.URISyntaxException)2 UTF_8 (java.nio.charset.StandardCharsets.UTF_8)2