001package org.nuxeo.snapshot.pub;
002
003import java.util.Map;
004
005import org.nuxeo.ecm.core.api.CoreSession;
006import org.nuxeo.ecm.core.api.DocumentModel;
007import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
008import org.nuxeo.ecm.core.api.VersioningOption;
009import org.nuxeo.ecm.platform.publisher.api.PublicationNode;
010import org.nuxeo.ecm.platform.publisher.api.PublishedDocument;
011import org.nuxeo.ecm.platform.publisher.impl.core.SimpleCorePublishedDocument;
012import org.nuxeo.ecm.platform.publisher.task.CoreProxyWithWorkflowFactory;
013import org.nuxeo.snapshot.Snapshot;
014import org.nuxeo.snapshot.Snapshotable;
015
016public class FolderishProxyFactory extends CoreProxyWithWorkflowFactory {
017
018    protected DocumentModel subPublish(CoreSession session, DocumentModel parentProxy, Snapshot tree, boolean skipParent)
019            {
020
021        DocumentModel newFolderishProxy = null;
022        if (skipParent) {
023            newFolderishProxy = parentProxy;
024        } else {
025            DocumentModel version = tree.getDocument();
026            newFolderishProxy = session.createProxy(version.getRef(), parentProxy.getRef());
027        }
028
029        for (Snapshot snap : tree.getChildrenSnapshots()) {
030            subPublish(session, newFolderishProxy, snap, false);
031        }
032
033        return newFolderishProxy;
034    }
035
036    @Override
037    public PublishedDocument publishDocument(DocumentModel doc, PublicationNode targetNode, Map<String, String> params)
038            {
039
040        Snapshot snapshot = null;
041
042        if (doc.isFolder()) {
043            Snapshotable snapshotable = doc.getAdapter(Snapshotable.class);
044            if (snapshotable != null) {
045                snapshot = snapshotable.createSnapshot(VersioningOption.MINOR);
046            }
047        }
048
049        PublishedDocument result = super.publishDocument(doc, targetNode, params);
050
051        if (snapshot != null) {
052
053            final Snapshot tree = snapshot;
054            final DocumentModel parent = ((SimpleCorePublishedDocument) result).getProxy();
055
056            UnrestrictedSessionRunner runner = new UnrestrictedSessionRunner(doc.getCoreSession()) {
057                @Override
058                public void run() {
059                    // force cleanup of the tree !!!
060                    session.removeChildren(parent.getRef());
061                    subPublish(session, parent, tree, true);
062                }
063            };
064            runner.runUnrestricted();
065        }
066
067        return result;
068
069    }
070}