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