001/*
002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Thomas Roger
016 */
017
018package org.nuxeo.ecm.csv;
019
020import java.io.File;
021import java.io.FileInputStream;
022import java.io.IOException;
023import java.io.InputStream;
024
025import org.apache.commons.codec.digest.DigestUtils;
026import org.apache.commons.io.IOUtils;
027import org.apache.commons.logging.Log;
028import org.apache.commons.logging.LogFactory;
029
030/**
031 * Helper class to compute a unique id for an import task.
032 *
033 * @since 5.7.3
034 */
035public class CSVImportId {
036
037    private static final Log log = LogFactory.getLog(CSVImportId.class);
038
039    private CSVImportId() {
040        // utility class
041    }
042
043    public static String create(String repositoryName, String path, File csvFile) {
044        return create(repositoryName, path, computeDigest(csvFile));
045    }
046
047    public static String create(String repositoryName, String path, String csvBlobDigest) {
048        return repositoryName + ':' + path + ":csvImport:" + csvBlobDigest;
049    }
050
051    protected static String computeDigest(File file) {
052        InputStream in = null;
053        try {
054            in = new FileInputStream(file);
055            return DigestUtils.md5Hex(in);
056        } catch (IOException e) {
057            log.error(e, e);
058            return "";
059        } finally {
060            IOUtils.closeQuietly(in);
061        }
062    }
063
064}