001/*
002 * (C) Copyright 2009 Nuxeo SA (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 *     Thomas Roger
018 */
019
020package org.nuxeo.ecm.platform.importer.factories;
021
022import java.io.Serializable;
023import java.util.Map;
024
025import org.apache.commons.logging.Log;
026import org.apache.commons.logging.LogFactory;
027import org.nuxeo.common.utils.IdUtils;
028import org.nuxeo.ecm.core.api.CoreSession;
029import org.nuxeo.ecm.core.api.DocumentModel;
030import org.nuxeo.ecm.core.api.PropertyException;
031import org.nuxeo.ecm.core.api.impl.DocumentModelImpl;
032import org.nuxeo.ecm.core.api.model.PropertyNotFoundException;
033import org.nuxeo.ecm.core.api.pathsegment.PathSegmentService;
034import org.nuxeo.ecm.platform.importer.source.SourceNode;
035import org.nuxeo.runtime.api.Framework;
036
037/**
038 * Base class for classes implementing {@code ImporterDocumentModelFactory}. Contains common methods.
039 *
040 * @author <a href="mailto:troger@nuxeo.com">Thomas Roger</a>
041 */
042public abstract class AbstractDocumentModelFactory implements ImporterDocumentModelFactory {
043
044    private static final Log log = LogFactory.getLog(AbstractDocumentModelFactory.class);
045
046    /**
047     * By default there is no process bound to a folderish node creation error, and the global import task will
048     * continue.
049     * <p>
050     * You should override this method if you want a specific process to be executed after such an error and/or if you
051     * want the global import task to stop immediately after the error occurs, in which case the method should return
052     * false.
053     * </p>
054     */
055    @Override
056    public boolean processFolderishNodeCreationError(CoreSession session, DocumentModel parent, SourceNode node) {
057        log.info(String.format("Nothing to process after error while trying to create the folderish node %s.",
058                node.getSourcePath()));
059        log.info("Global import task will continue.");
060        return true;
061    }
062
063    /**
064     * By default there is no process bound to a leaf node creation error, and the global import task will continue.
065     * <p>
066     * You should override this method if you want a specific process to be executed after such an error and/or if you
067     * want the global import task to stop immediately after the error occurs, in which case the method should return
068     * false.
069     * </p>
070     */
071    @Override
072    public boolean processLeafNodeCreationError(CoreSession session, DocumentModel parent, SourceNode node) {
073        log.info(String.format("Nothing to process after error while trying to create the leaf node %s.",
074                node.getSourcePath()));
075        log.info("Global import task will continue.");
076        return true;
077    }
078
079    /*
080     * (non-Javadoc)
081     * @see org.nuxeo.ecm.platform.importer.base.ImporterDocumentModelFactory# isTargetDocumentModelFolderish
082     * (org.nuxeo.ecm.platform.importer.base.SourceNode)
083     */
084    public boolean isTargetDocumentModelFolderish(SourceNode node) {
085        return node.isFolderish();
086    }
087
088    protected final FilenameNormalizer filenameNormalizer = "true".equals(Framework.getProperty("nuxeo.importer.compatFilenames")) ? new CompatFilenameNormalizer()
089            : new DefaultFilenameNormalizer();
090
091    protected interface FilenameNormalizer {
092        String normalize(String name);
093    }
094
095    protected static class CompatFilenameNormalizer implements FilenameNormalizer {
096
097        @Override
098        public String normalize(String name) {
099            name = IdUtils.generateId(name, "-", true, 100);
100            name = name.replace("'", "");
101            name = name.replace("(", "");
102            name = name.replace(")", "");
103            name = name.replace("+", "");
104            return name;
105        }
106
107    }
108
109    protected static class DefaultFilenameNormalizer implements FilenameNormalizer {
110
111        @Override
112        public String normalize(String name) {
113            DocumentModel fake = new DocumentModelImpl("/", name, "File");
114            return Framework.getLocalService(PathSegmentService.class).generatePathSegment(fake);
115        }
116    }
117
118    /**
119     * Returns a valid Nuxeo name from the given {@code fileName}.
120     *
121     * @throws PropertyException
122     */
123    protected String getValidNameFromFileName(String fileName) {
124        return filenameNormalizer.normalize(fileName);
125    }
126
127    /**
128     * Set all the properties to the given {@code doc}. The key is field xpath, the value is the value to set on the
129     * document.
130     */
131    protected DocumentModel setDocumentProperties(CoreSession session, Map<String, Serializable> properties,
132            DocumentModel doc) {
133        if (properties != null) {
134
135            for (Map.Entry<String, Serializable> entry : properties.entrySet()) {
136                try {
137                    doc.setPropertyValue(entry.getKey(), entry.getValue());
138                } catch (PropertyNotFoundException e) {
139                    String message = String.format("Property '%s' not found on document type: %s. Skipping it.",
140                            entry.getKey(), doc.getType());
141                    log.debug(message);
142                }
143            }
144            doc = session.saveDocument(doc);
145        }
146        return doc;
147    }
148
149}