001/*
002 * (C) Copyright 2012 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.csv;
021
022import java.io.File;
023import java.io.FileInputStream;
024import java.io.IOException;
025import java.io.InputStream;
026
027import org.apache.commons.codec.digest.DigestUtils;
028import org.apache.commons.io.IOUtils;
029import org.apache.commons.logging.Log;
030import org.apache.commons.logging.LogFactory;
031
032/**
033 * Helper class to compute a unique id for an import task.
034 *
035 * @since 5.7.3
036 */
037public class CSVImportId {
038
039    private static final Log log = LogFactory.getLog(CSVImportId.class);
040
041    private CSVImportId() {
042        // utility class
043    }
044
045    public static String create(String repositoryName, String path, File csvFile) {
046        return create(repositoryName, path, computeDigest(csvFile));
047    }
048
049    public static String create(String repositoryName, String path, String csvBlobDigest) {
050        return repositoryName + ':' + path + ":csvImport:" + csvBlobDigest;
051    }
052
053    protected static String computeDigest(File file) {
054        InputStream in = null;
055        try {
056            in = new FileInputStream(file);
057            return DigestUtils.md5Hex(in);
058        } catch (IOException e) {
059            log.error(e, e);
060            return "";
061        } finally {
062            IOUtils.closeQuietly(in);
063        }
064    }
065
066}