001/*
002 * (C) Copyright 2013 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-2.1.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 *     Antoine Taillefer <ataillefer@nuxeo.com>
016 */
017package org.nuxeo.drive.adapter.impl;
018
019import java.io.IOException;
020
021import org.apache.commons.codec.digest.DigestUtils;
022import org.nuxeo.drive.adapter.FileSystemItem;
023import org.nuxeo.drive.service.VersioningFileSystemItemFactory;
024import org.nuxeo.ecm.core.api.Blob;
025import org.nuxeo.ecm.core.api.CoreSession;
026import org.nuxeo.ecm.core.api.DocumentModel;
027import org.nuxeo.ecm.core.api.NuxeoException;
028import org.nuxeo.ecm.core.versioning.VersioningService;
029
030/**
031 * Helper for {@link FileSystemItem} manipulation.
032 *
033 * @author Antoine Taillefer
034 */
035public final class FileSystemItemHelper {
036
037    public static final String MD5_DIGEST_ALGORITHM = "MD5";
038
039    private FileSystemItemHelper() {
040        // Helper class
041    }
042
043    /**
044     * @since 7.4
045     */
046    public static void versionIfNeeded(VersioningFileSystemItemFactory factory, DocumentModel doc, CoreSession session) {
047        if (factory.needsVersioning(doc)) {
048            doc.putContextData(VersioningService.VERSIONING_OPTION, factory.getVersioningOption());
049            session.saveDocument(doc);
050        }
051    }
052
053    /**
054     * Gets the md5 digest of the given blob.
055     */
056    public static String getMD5Digest(Blob blob) {
057        try {
058            return DigestUtils.md5Hex(blob.getStream());
059        } catch (IOException e) {
060            throw new NuxeoException(String.format("Error while computing digest for blob %s.", blob.getFilename()), e);
061        }
062    }
063
064}