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