Search in sources :

Example 1 with DateTimeValue

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

the class SystemExport method exportDocument.

private void exportDocument(final BackupHandler bh, final BackupWriter output, final Date date, final BackupDescriptor prevBackup, final SAXSerializer serializer, final int docsCount, final int count, final DocumentImpl doc) throws IOException, SAXException, TerminatedException {
    if (callback != null) {
        callback.startDocument(doc.getFileURI().toString(), count, docsCount);
    }
    if ((monitor != null) && !monitor.proceed()) {
        throw (new TerminatedException("system export terminated by db"));
    }
    final boolean needsBackup = (prevBackup == null) || (date.getTime() < doc.getLastModified());
    if (needsBackup) {
        // Note: do not auto-close the output stream or the zip will be closed!
        try {
            final OutputStream os = output.newEntry(Backup.encode(URIUtils.urlDecodeUtf8(doc.getFileURI())));
            if (doc.getResourceType() == DocumentImpl.BINARY_FILE) {
                broker.readBinaryResource((BinaryDocument) doc, os);
            } else {
                final SAXSerializer contentSerializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
                final Writer writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8));
                try {
                    // write resource to contentSerializer
                    contentSerializer.setOutput(writer, defaultOutputProperties);
                    final Receiver receiver;
                    if (chainFactory != null) {
                        chainFactory.getLast().setNextInChain(contentSerializer);
                        receiver = chainFactory.getFirst();
                    } else {
                        receiver = contentSerializer;
                    }
                    writeXML(doc, receiver);
                } finally {
                    SerializerPool.getInstance().returnObject(contentSerializer);
                    writer.flush();
                }
            }
        } catch (final Exception e) {
            reportError("A write error occurred while exporting document: '" + doc.getFileURI() + "'. Continuing with next document.", e);
            return;
        } finally {
            output.closeEntry();
        }
    }
    final Permission perms = doc.getPermissions();
    // store permissions
    final AttributesImpl attr = new AttributesImpl();
    attr.addAttribute(Namespaces.EXIST_NS, "type", "type", "CDATA", (doc.getResourceType() == DocumentImpl.BINARY_FILE) ? "BinaryResource" : "XMLResource");
    attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", doc.getFileURI().toString());
    attr.addAttribute(Namespaces.EXIST_NS, "skip", "skip", "CDATA", (needsBackup ? "no" : "yes"));
    Backup.writeUnixStylePermissionAttributes(attr, perms);
    try {
        final String created = new DateTimeValue(new Date(doc.getCreated())).getStringValue();
        final String modified = new DateTimeValue(new Date(doc.getLastModified())).getStringValue();
        attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", created);
        attr.addAttribute(Namespaces.EXIST_NS, "modified", "modified", "CDATA", modified);
    } catch (final XPathException e) {
        LOG.warn(e.getMessage(), e);
    }
    attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", Backup.encode(URIUtils.urlDecodeUtf8(doc.getFileURI())));
    String mimeType = "application/xml";
    if (doc.getMimeType() != null) {
        mimeType = Backup.encode(doc.getMimeType());
    }
    attr.addAttribute(Namespaces.EXIST_NS, "mimetype", "mimetype", "CDATA", mimeType);
    // output by serializer
    // if( ( doc.getResourceType() == DocumentImpl.XML_FILE ) && ( metadata != null ) && ( doc.getDoctype() != null ) ) {
    // 
    // if( doc.getDoctype().getName() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "namedoctype", "namedoctype", "CDATA", doc.getDoctype().getName() );
    // }
    // 
    // if( doc.getDoctype().getPublicId() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "publicid", "publicid", "CDATA", doc.getDoctype().getPublicId() );
    // }
    // 
    // if( doc.getDoctype().getSystemId() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "systemid", "systemid", "CDATA", doc.getDoctype().getSystemId() );
    // }
    // }
    bh.backup(doc, attr);
    serializer.startElement(Namespaces.EXIST_NS, "resource", "resource", attr);
    if (perms instanceof ACLPermission) {
        Backup.writeACLPermission(serializer, (ACLPermission) perms);
    }
    bh.backup(doc, serializer);
    serializer.endElement(Namespaces.EXIST_NS, "resource", "resource");
}
Also used : DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) ACLPermission(org.exist.security.ACLPermission) Receiver(org.exist.util.serializer.Receiver) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockException(org.exist.util.LockException) TerminatedException(org.exist.xquery.TerminatedException) XMLStreamException(javax.xml.stream.XMLStreamException) SAXException(org.xml.sax.SAXException) XPathException(org.exist.xquery.XPathException) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) SAXSerializer(org.exist.util.serializer.SAXSerializer) TerminatedException(org.exist.xquery.TerminatedException)

Example 2 with DateTimeValue

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

the class SystemExport method export.

/**
 * Export a collection. Write out the collection metadata and save the resources stored in the collection.
 *
 * @param current    the collection
 * @param output     the output writer
 * @param date
 * @param prevBackup DOCUMENT ME!
 * @param errorList  a list of {@link org.exist.backup.ErrorReport} objects as returned by methods in {@link org.exist.backup.ConsistencyCheck}
 * @param docs       a document set to keep track of all written documents.
 * @throws IOException
 * @throws SAXException
 * @throws TerminatedException DOCUMENT ME!
 */
private void export(final BackupHandler bh, final Collection current, final BackupWriter output, final Date date, final BackupDescriptor prevBackup, final List<ErrorReport> errorList, final MutableDocumentSet docs) throws IOException, SAXException, TerminatedException, PermissionDeniedException {
    if ((monitor != null) && !monitor.proceed()) {
        throw (new TerminatedException("system export terminated by db"));
    }
    // if( !current.getURI().equalsInternal( XmldbURI.ROOT_COLLECTION_URI ) ) {
    output.newCollection(Backup.encode(URIUtils.urlDecodeUtf8(current.getURI())));
    // }
    final SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
    try {
        final Writer contents = output.newContents();
        // serializer writes to __contents__.xml
        serializer.setOutput(contents, contentsOutputProps);
        final Permission perm = current.getPermissionsNoLock();
        serializer.startDocument();
        serializer.startPrefixMapping("", Namespaces.EXIST_NS);
        final XmldbURI uri = current.getURI();
        final AttributesImpl attr = new AttributesImpl();
        attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", uri.toString());
        attr.addAttribute(Namespaces.EXIST_NS, "version", "version", "CDATA", String.valueOf(currVersion));
        Backup.writeUnixStylePermissionAttributes(attr, perm);
        try {
            attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", new DateTimeValue(new Date(current.getCreated())).getStringValue());
        } catch (final XPathException e) {
            e.printStackTrace();
        }
        bh.backup(current, attr);
        serializer.startElement(Namespaces.EXIST_NS, "collection", "collection", attr);
        if (perm instanceof ACLPermission) {
            Backup.writeACLPermission(serializer, (ACLPermission) perm);
        }
        bh.backup(current, serializer);
        final int docsCount = current.getDocumentCountNoLock(broker);
        int count = 0;
        for (final Iterator<DocumentImpl> i = current.iteratorNoLock(broker); i.hasNext(); count++) {
            final DocumentImpl doc = i.next();
            if (isDamaged(doc, errorList)) {
                reportError("Skipping damaged document " + doc.getFileURI(), null);
                continue;
            }
            if (doc.getFileURI().equalsInternal(CONTENTS_URI) || doc.getFileURI().equalsInternal(LOST_URI)) {
                // skip __contents__.xml documents
                continue;
            }
            exportDocument(bh, output, date, prevBackup, serializer, docsCount, count, doc);
            docs.add(doc, false);
        }
        for (final Iterator<XmldbURI> i = current.collectionIteratorNoLock(broker); i.hasNext(); ) {
            final XmldbURI childUri = i.next();
            if (childUri.equalsInternal(TEMP_COLLECTION)) {
                continue;
            }
            if (isDamagedChild(childUri, errorList)) {
                reportError("Skipping damaged child collection " + childUri, null);
                continue;
            }
            attr.clear();
            attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", childUri.toString());
            attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", Backup.encode(URIUtils.urlDecodeUtf8(childUri.toString())));
            serializer.startElement(Namespaces.EXIST_NS, "subcollection", "subcollection", attr);
            serializer.endElement(Namespaces.EXIST_NS, "subcollection", "subcollection");
        }
        if (prevBackup != null) {
            // Check which collections and resources have been deleted since
            // the
            // last backup
            final CheckDeletedHandler check = new CheckDeletedHandler(current, serializer);
            try {
                prevBackup.parse(broker.getBrokerPool().getParserPool(), check);
            } catch (final Exception e) {
                LOG.error("Caught exception while trying to parse previous backup descriptor: {}", prevBackup.getSymbolicPath(), e);
            }
        }
        // close <collection>
        serializer.endElement(Namespaces.EXIST_NS, "collection", "collection");
        serializer.endPrefixMapping("");
        serializer.endDocument();
        output.closeContents();
    } finally {
        SerializerPool.getInstance().returnObject(serializer);
        // if( !current.getURI().equalsInternal( XmldbURI.ROOT_COLLECTION_URI ) ) {
        output.closeCollection();
    // }
    }
}
Also used : DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) ACLPermission(org.exist.security.ACLPermission) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockException(org.exist.util.LockException) TerminatedException(org.exist.xquery.TerminatedException) XMLStreamException(javax.xml.stream.XMLStreamException) SAXException(org.xml.sax.SAXException) XPathException(org.exist.xquery.XPathException) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) SAXSerializer(org.exist.util.serializer.SAXSerializer) TerminatedException(org.exist.xquery.TerminatedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 3 with DateTimeValue

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

the class SystemImportHandler 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");
    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;
    if (version >= STRICT_URI_VERSION) {
        docUri = XmldbURI.create(name);
    } else {
        try {
            docUri = 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();
        }
    }
    try (final EXistInputSource 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);
            throw new RuntimeException(msg);
        }
        try (final Txn transaction = beginTransaction()) {
            broker.storeDocument(transaction, docUri, is, mimeType, dateCreated, dateModified, null, docType, null, currentCollection);
            try (final LockedDocument doc = currentCollection.getDocumentWithLock(broker, docUri, Lock.LockMode.READ_LOCK)) {
                rh.startDocumentRestore(doc.getDocument(), atts);
            }
            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, currentCollection.getURI().append(name), SecurityManager.SYSTEM, SecurityManager.DBA_GROUP, Integer.parseInt(perms, 8));
            } else {
                deferredPermission = new ResourceDeferredPermission(listener, currentCollection.getURI().append(name), owner, group, Integer.parseInt(perms, 8));
            }
            try (final LockedDocument doc = currentCollection.getDocumentWithLock(broker, docUri, Lock.LockMode.READ_LOCK)) {
                rh.endDocumentRestore(doc.getDocument());
            }
            listener.restoredResource(name);
            return deferredPermission;
        } catch (final Exception e) {
            throw new IOException(e);
        }
    } catch (final Exception e) {
        listener.warn("Failed to restore resource '" + name + "'\nfrom file '" + descriptor.getSymbolicPath(name, false) + "'.\nReason: " + e.getMessage());
        LOG.error(e.getMessage(), e);
        return new SkippedEntryDeferredPermission();
    }
}
Also used : URIUtils(org.exist.xquery.util.URIUtils) Tuple2(com.evolvedbinary.j8fu.tuple.Tuple2) Txn(org.exist.storage.txn.Txn) java.util(java.util) ACE_TARGET(org.exist.security.ACLPermission.ACE_TARGET) URISyntaxException(java.net.URISyntaxException) SAXParserFactory(javax.xml.parsers.SAXParserFactory) Tuple(com.evolvedbinary.j8fu.tuple.Tuple.Tuple) XMLReader(org.xml.sax.XMLReader) Namespaces(org.exist.Namespaces) Collection(org.exist.collections.Collection) XmldbURI(org.exist.xmldb.XmldbURI) Attributes(org.xml.sax.Attributes) DocumentImpl(org.exist.dom.persistent.DocumentImpl) DateTimeValue(org.exist.xquery.value.DateTimeValue) Lock(org.exist.storage.lock.Lock) Permission(org.exist.security.Permission) Nullable(javax.annotation.Nullable) 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) ACE_ACCESS_TYPE(org.exist.security.ACLPermission.ACE_ACCESS_TYPE) DBBroker(org.exist.storage.DBBroker) SAXException(org.xml.sax.SAXException) org.exist.util(org.exist.util) DocumentTypeImpl(org.exist.dom.persistent.DocumentTypeImpl) LogManager(org.apache.logging.log4j.LogManager) 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) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) TransactionException(org.exist.storage.txn.TransactionException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) XPathException(org.exist.xquery.XPathException) SAXException(org.xml.sax.SAXException) LockedDocument(org.exist.dom.persistent.LockedDocument) Nullable(javax.annotation.Nullable) XmldbURI(org.exist.xmldb.XmldbURI)

Example 4 with DateTimeValue

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

the class Backup method backup.

private void backup(final Set<String> seenBlobIds, final Collection current, final BackupWriter output, final BackupDialog dialog) throws XMLDBException, IOException, SAXException {
    if (current == null) {
        return;
    }
    current.setProperty(OutputKeys.ENCODING, defaultOutputProperties.getProperty(OutputKeys.ENCODING));
    current.setProperty(OutputKeys.INDENT, defaultOutputProperties.getProperty(OutputKeys.INDENT));
    current.setProperty(EXistOutputKeys.EXPAND_XINCLUDES, defaultOutputProperties.getProperty(EXistOutputKeys.EXPAND_XINCLUDES));
    current.setProperty(EXistOutputKeys.PROCESS_XSL_PI, defaultOutputProperties.getProperty(EXistOutputKeys.PROCESS_XSL_PI));
    // get collections and documents
    final String[] collections = current.listChildCollections();
    final String[] resources = current.listResources();
    // do not sort: order is important because permissions need to be read in the same order below
    // Arrays.sort( resources );
    final UserManagementService mgtService = (UserManagementService) current.getService("UserManagementService", "1.0");
    final Permission[] perms = mgtService.listResourcePermissions();
    final Permission currentPerms = mgtService.getPermissions(current);
    if (dialog != null) {
        dialog.setCollection(current.getName());
        dialog.setResourceCount(resources.length);
    }
    final Writer contents = output.newContents();
    // serializer writes to __contents__.xml
    final SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
    try {
        serializer.setOutput(contents, contentsOutputProps);
        serializer.startDocument();
        serializer.startPrefixMapping("", Namespaces.EXIST_NS);
        // write <collection> element
        final EXistCollection cur = (EXistCollection) current;
        final AttributesImpl attr = new AttributesImpl();
        // The name should have come from an XmldbURI.toString() call
        attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", current.getName());
        writeUnixStylePermissionAttributes(attr, currentPerms);
        attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", "" + new DateTimeValue(cur.getCreationTime()));
        attr.addAttribute(Namespaces.EXIST_NS, "deduplicate-blobs", "deduplicate-blobs", "CDATA", Boolean.toString(deduplicateBlobs));
        attr.addAttribute(Namespaces.EXIST_NS, "version", "version", "CDATA", String.valueOf(BACKUP_FORMAT_VERSION));
        serializer.startElement(Namespaces.EXIST_NS, "collection", "collection", attr);
        if (currentPerms instanceof ACLPermission) {
            writeACLPermission(serializer, (ACLPermission) currentPerms);
        }
        // scan through resources
        for (int i = 0; i < resources.length; i++) {
            try {
                if ("__contents__.xml".equals(resources[i])) {
                    // Skipping resources[i]
                    continue;
                }
                final Resource resource = current.getResource(resources[i]);
                if (dialog != null) {
                    dialog.setResource(resources[i]);
                    dialog.setProgress(i);
                }
                // Avoid NPE
                if (resource == null) {
                    final String msg = "Resource " + resources[i] + " could not be found.";
                    if (dialog != null) {
                        Object[] options = { "Ignore", "Abort" };
                        int n = JOptionPane.showOptionDialog(null, msg, "Backup Error", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
                        if (n == JOptionPane.YES_OPTION) {
                            // ignore one
                            continue;
                        }
                        // Abort
                        dialog.dispose();
                        JOptionPane.showMessageDialog(null, "Backup aborted.", "Abort", JOptionPane.WARNING_MESSAGE);
                    }
                    throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, msg);
                }
                final String name = resources[i];
                String filename = encode(URIUtils.urlDecodeUtf8(resources[i]));
                if (".".equals(name.trim())) {
                    filename = EXIST_GENERATED_FILENAME_DOT_FILENAME + i;
                } else if ("..".equals(name.trim())) {
                    filename = EXIST_GENERATED_FILENAME_DOTDOT_FILENAME + i;
                }
                final OutputStream os;
                if (resource instanceof ExtendedResource) {
                    if (deduplicateBlobs && resource instanceof EXistBinaryResource) {
                        // only add distinct blobs to the Blob Store once!
                        final String blobId = ((EXistBinaryResource) resource).getBlobId().toString();
                        if (!seenBlobIds.contains(blobId)) {
                            os = output.newBlobEntry(blobId);
                            ((ExtendedResource) resource).getContentIntoAStream(os);
                            output.closeEntry();
                            seenBlobIds.add(blobId);
                        }
                    } else {
                        os = output.newEntry(filename);
                        ((ExtendedResource) resource).getContentIntoAStream(os);
                        output.closeEntry();
                    }
                } else {
                    os = output.newEntry(filename);
                    final Writer writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8));
                    // write resource to contentSerializer
                    final SAXSerializer contentSerializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
                    try {
                        contentSerializer.setOutput(writer, defaultOutputProperties);
                        ((EXistResource) resource).setLexicalHandler(contentSerializer);
                        ((XMLResource) resource).getContentAsSAX(contentSerializer);
                    } finally {
                        SerializerPool.getInstance().returnObject(contentSerializer);
                    }
                    writer.flush();
                    output.closeEntry();
                }
                final EXistResource ris = (EXistResource) resource;
                // store permissions
                attr.clear();
                attr.addAttribute(Namespaces.EXIST_NS, "type", "type", "CDATA", resource.getResourceType());
                attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", name);
                writeUnixStylePermissionAttributes(attr, perms[i]);
                Date date = ris.getCreationTime();
                if (date != null) {
                    attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", "" + new DateTimeValue(date));
                }
                date = ris.getLastModificationTime();
                if (date != null) {
                    attr.addAttribute(Namespaces.EXIST_NS, "modified", "modified", "CDATA", "" + new DateTimeValue(date));
                }
                attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", filename);
                attr.addAttribute(Namespaces.EXIST_NS, "mimetype", "mimetype", "CDATA", encode(((EXistResource) resource).getMimeType()));
                if (!"BinaryResource".equals(resource.getResourceType())) {
                    if (ris.getDocType() != null) {
                        if (ris.getDocType().getName() != null) {
                            attr.addAttribute(Namespaces.EXIST_NS, "namedoctype", "namedoctype", "CDATA", ris.getDocType().getName());
                        }
                        if (ris.getDocType().getPublicId() != null) {
                            attr.addAttribute(Namespaces.EXIST_NS, "publicid", "publicid", "CDATA", ris.getDocType().getPublicId());
                        }
                        if (ris.getDocType().getSystemId() != null) {
                            attr.addAttribute(Namespaces.EXIST_NS, "systemid", "systemid", "CDATA", ris.getDocType().getSystemId());
                        }
                    }
                } else {
                    attr.addAttribute(Namespaces.EXIST_NS, "blob-id", "blob-id", "CDATA", ((EXistBinaryResource) ris).getBlobId().toString());
                }
                serializer.startElement(Namespaces.EXIST_NS, "resource", "resource", attr);
                if (perms[i] instanceof ACLPermission) {
                    writeACLPermission(serializer, (ACLPermission) perms[i]);
                }
                serializer.endElement(Namespaces.EXIST_NS, "resource", "resource");
            } catch (final XMLDBException e) {
                System.err.println("Failed to backup resource " + resources[i] + " from collection " + current.getName());
                throw e;
            }
        }
        // write sub-collections
        for (final String collection : collections) {
            if (current.getName().equals(XmldbURI.SYSTEM_COLLECTION) && "temp".equals(collection)) {
                continue;
            }
            attr.clear();
            attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", collection);
            attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", encode(URIUtils.urlDecodeUtf8(collection)));
            serializer.startElement(Namespaces.EXIST_NS, "subcollection", "subcollection", attr);
            serializer.endElement(Namespaces.EXIST_NS, "subcollection", "subcollection");
        }
        // close <collection>
        serializer.endElement(Namespaces.EXIST_NS, "collection", "collection");
        serializer.endPrefixMapping("");
        serializer.endDocument();
        output.closeContents();
    } finally {
        SerializerPool.getInstance().returnObject(serializer);
    }
    // descend into sub-collections
    for (final String collection : collections) {
        final Collection child = current.getChildCollection(collection);
        if (child.getName().equals(XmldbURI.TEMP_COLLECTION)) {
            continue;
        }
        output.newCollection(encode(URIUtils.urlDecodeUtf8(collection)));
        backup(seenBlobIds, child, output, dialog);
        output.closeCollection();
    }
}
Also used : ACLPermission(org.exist.security.ACLPermission) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) SAXSerializer(org.exist.util.serializer.SAXSerializer) DateTimeValue(org.exist.xquery.value.DateTimeValue) XMLResource(org.xmldb.api.modules.XMLResource) XMLResource(org.xmldb.api.modules.XMLResource) Date(java.util.Date)

Example 5 with DateTimeValue

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

the class GetScheduledJobs method eval.

/**
 * evaluate the call to the xquery function, it is really the main entry point of this class.
 *
 * @param   args             arguments from the function call
 * @param   contextSequence  the Context Sequence to operate on (not used here internally!)
 *
 * @return  A sequence representing the result of the function call
 *
 * @throws  XPathException  DOCUMENT ME!
 *
 * @see     org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
 */
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Subject user = context.getSubject();
    boolean userhasDBARole = user.hasDbaRole();
    StringBuilder xmlBuf = new StringBuilder();
    int iJobs = 0;
    List<String> groups = scheduler.getJobGroupNames();
    List<ScheduledJobInfo> scheduledJobs = scheduler.getScheduledJobs();
    for (String group : groups) {
        if (userhasDBARole || group.equals(UserJob.JOB_GROUP)) {
            xmlBuf.append("<" + SchedulerModule.PREFIX + ":group name=\"").append(group).append("\">");
            for (ScheduledJobInfo scheduledJob : scheduledJobs) {
                if (scheduledJob.getGroup().equals(group)) {
                    xmlBuf.append("<" + SchedulerModule.PREFIX + ":job name=\"").append(scheduledJob.getName()).append("\">");
                    xmlBuf.append("<" + SchedulerModule.PREFIX + ":trigger name=\"").append(scheduledJob.getTriggerName()).append("\">");
                    xmlBuf.append("<expression>");
                    xmlBuf.append(scheduledJob.getTriggerExpression());
                    xmlBuf.append("</expression>");
                    xmlBuf.append("<state>");
                    xmlBuf.append(scheduledJob.getTriggerState());
                    xmlBuf.append("</state>");
                    xmlBuf.append("<start>");
                    xmlBuf.append(new DateTimeValue(scheduledJob.getStartTime()));
                    xmlBuf.append("</start>");
                    xmlBuf.append("<end>");
                    Date endTime = scheduledJob.getEndTime();
                    if (endTime != null) {
                        xmlBuf.append(new DateTimeValue(endTime));
                    }
                    xmlBuf.append("</end>");
                    xmlBuf.append("<previous>");
                    Date previousTime = scheduledJob.getPreviousFireTime();
                    if (previousTime != null) {
                        xmlBuf.append(new DateTimeValue(scheduledJob.getPreviousFireTime()));
                    }
                    xmlBuf.append("</previous>");
                    xmlBuf.append("<next>");
                    Date nextTime = scheduledJob.getNextFireTime();
                    if (nextTime != null) {
                        xmlBuf.append(new DateTimeValue());
                    }
                    xmlBuf.append("</next>");
                    xmlBuf.append("<final>");
                    Date finalTime = scheduledJob.getFinalFireTime();
                    if ((endTime != null) && (finalTime != null)) {
                        xmlBuf.append(new DateTimeValue());
                    }
                    xmlBuf.append("</final>");
                    xmlBuf.append("</" + SchedulerModule.PREFIX + ":trigger>");
                    xmlBuf.append("</" + SchedulerModule.PREFIX + ":job>");
                    iJobs++;
                }
            }
            xmlBuf.append("</" + SchedulerModule.PREFIX + ":group>");
        }
    }
    xmlBuf.insert(0, "<" + SchedulerModule.PREFIX + ":jobs xmlns:scheduler=\"" + SchedulerModule.NAMESPACE_URI + "\" count=\"" + iJobs + "\">");
    xmlBuf.append("</" + SchedulerModule.PREFIX + ":jobs>");
    try {
        return ModuleUtils.stringToXML(context, xmlBuf.toString());
    } catch (SAXException | IOException se) {
        throw new XPathException(this, se.getMessage(), se);
    }
}
Also used : DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) IOException(java.io.IOException) Subject(org.exist.security.Subject) Date(java.util.Date) SAXException(org.xml.sax.SAXException) ScheduledJobInfo(org.exist.scheduler.ScheduledJobInfo)

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