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    @Override
085    public boolean isTargetDocumentModelFolderish(SourceNode node) {
086        return node.isFolderish();
087    }
088
089    protected final FilenameNormalizer filenameNormalizer = "true".equals(Framework.getProperty("nuxeo.importer.compatFilenames")) ? new CompatFilenameNormalizer()
090            : new DefaultFilenameNormalizer();
091
092    protected interface FilenameNormalizer {
093        String normalize(String name);
094    }
095
096    protected static class CompatFilenameNormalizer implements FilenameNormalizer {
097
098        @Override
099        public String normalize(String name) {
100            name = IdUtils.generateId(name, "-", true, 100);
101            name = name.replace("'", "");
102            name = name.replace("(", "");
103            name = name.replace(")", "");
104            name = name.replace("+", "");
105            return name;
106        }
107
108    }
109
110    protected static class DefaultFilenameNormalizer implements FilenameNormalizer {
111
112        @Override
113        public String normalize(String name) {
114            DocumentModel fake = new DocumentModelImpl("/", name, "File");
115            return Framework.getService(PathSegmentService.class).generatePathSegment(fake);
116        }
117    }
118
119    /**
120     * Returns a valid Nuxeo name from the given {@code fileName}.
121     */
122    protected String getValidNameFromFileName(String fileName) {
123        return filenameNormalizer.normalize(fileName);
124    }
125
126    /**
127     * Set all the properties to the given {@code doc}. The key is field xpath, the value is the value to set on the
128     * document.
129     */
130    protected DocumentModel setDocumentProperties(CoreSession session, Map<String, Serializable> properties,
131            DocumentModel doc) {
132        if (properties != null) {
133
134            for (Map.Entry<String, Serializable> entry : properties.entrySet()) {
135                try {
136                    doc.setPropertyValue(entry.getKey(), entry.getValue());
137                } catch (PropertyNotFoundException e) {
138                    String message = String.format("Property '%s' not found on document type: %s. Skipping it.",
139                            entry.getKey(), doc.getType());
140                    log.debug(message);
141                }
142            }
143            doc = session.saveDocument(doc);
144        }
145        return doc;
146    }
147
148}