001/*
002 * (C) Copyright 2014-2018 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     annejubert
018 */
019package org.nuxeo.io.fsexporter;
020
021import java.io.File;
022import java.io.IOException;
023import java.io.Serializable;
024import java.util.Date;
025import java.util.HashMap;
026import java.util.List;
027import java.util.Map;
028
029import org.apache.commons.lang3.StringUtils;
030import org.nuxeo.ecm.collections.api.CollectionConstants;
031import org.nuxeo.ecm.core.api.Blob;
032import org.nuxeo.ecm.core.api.CoreSession;
033import org.nuxeo.ecm.core.api.DocumentModel;
034import org.nuxeo.ecm.core.api.DocumentModelList;
035import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
036import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
037import org.nuxeo.ecm.platform.query.api.PageProvider;
038import org.nuxeo.ecm.platform.query.api.PageProviderService;
039import org.nuxeo.ecm.platform.query.core.CoreQueryPageProviderDescriptor;
040import org.nuxeo.ecm.platform.query.nxql.CoreQueryDocumentPageProvider;
041import org.nuxeo.runtime.api.Framework;
042
043public class DefaultExporterPlugin implements FSExporterPlugin {
044
045    @Override
046    public DocumentModelList getChildren(CoreSession session, DocumentModel doc, String customQuery) {
047        Map<String, Serializable> props = new HashMap<>();
048        props.put(CoreQueryDocumentPageProvider.CORE_SESSION_PROPERTY, (Serializable) session);
049
050        String query;
051        // if the user gives a query, we build a new Page Provider with the query provided
052        if (StringUtils.isNotBlank(customQuery)) {
053            if (customQuery.toLowerCase().contains(" where")) {
054                query = customQuery + " AND ecm:parentId = ?";
055            } else {
056                query = customQuery + " where ecm:parentId = ?";
057            }
058        } else {
059            query = "SELECT * FROM Document WHERE ecm:parentId = ? AND ecm:mixinType !='HiddenInNavigation' AND ecm:isVersion = 0 AND ecm:isTrashed = 0";
060        }
061        CoreQueryPageProviderDescriptor desc = new CoreQueryPageProviderDescriptor();
062        desc.setPattern(query);
063
064        PageProviderService ppService = Framework.getService(PageProviderService.class);
065        @SuppressWarnings("unchecked")
066        PageProvider<DocumentModel> pp = (PageProvider<DocumentModel>) ppService.getPageProvider("customPP", desc, null,
067                null, null, null, props, new Object[] { doc.getId() });
068
069        int countPages = 1;
070        // get all the documents of the first page
071        DocumentModelList children = new DocumentModelListImpl(pp.getCurrentPage());
072        // if there is more than one page, get the children of all the other pages and put into one list
073        if (pp.getNumberOfPages() > 1) {
074            while (countPages < pp.getNumberOfPages()) {
075                pp.nextPage();
076                List<DocumentModel> childrenTemp = pp.getCurrentPage();
077                children.addAll(childrenTemp);
078                countPages++;
079            }
080        }
081        // return the complete list of documents
082        return children;
083    }
084
085    @Override
086    public File serialize(CoreSession session, DocumentModel docfrom, String fsPath) throws IOException {
087        File folder;
088        File newFolder = null;
089        folder = new File(fsPath);
090
091        // if target directory doesn't exist, create it
092        if (!folder.exists()) {
093            folder.mkdir();
094        }
095
096        if ("/".equals(docfrom.getPathAsString())) {
097            // we do not serialize the root document
098            return folder;
099        }
100
101        if (docfrom.hasFacet("Folderish") || docfrom.hasFacet(CollectionConstants.COLLECTION_FACET)) {
102            newFolder = new File(fsPath + "/" + docfrom.getName());
103            newFolder.mkdir();
104        }
105
106        // get all the blobs of the blob holder
107        BlobHolder myblobholder = docfrom.getAdapter(BlobHolder.class);
108        if (myblobholder != null) {
109            java.util.List<Blob> listblobs = myblobholder.getBlobs();
110            int i = 1;
111            for (Blob blob : listblobs) {
112                // call the method to determine the name of the exported file
113                String FileNameToExport = getFileName(blob, docfrom, folder, i);
114                // export the file to the target file system
115                File target = new File(folder, FileNameToExport);
116                blob.transferTo(target);
117                i++;
118            }
119        }
120        if (newFolder != null) {
121            folder = newFolder;
122        }
123        return folder;
124    }
125
126    protected String getFileName(Blob blob, DocumentModel docfrom, File folder, int i) {
127        String prefix = "";
128        // if not principal file, prefix = name of the file which contains the blobs
129        if (i != 1) {
130            prefix = docfrom.getName() + "-";
131        }
132
133        // if already existing file, prefix with "timestamp"
134        File alreadyExistingBlob = new File(folder, prefix + blob.getFilename());
135
136        if (alreadyExistingBlob.exists()) {
137            prefix = String.valueOf(new Date().getTime()) + "-" + prefix;
138        }
139
140        return prefix + blob.getFilename();
141    }
142}