001/*
002 * (C) Copyright 2006-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 *     Nuxeo - initial API and implementation
018 */
019package org.nuxeo.ecm.platform.filemanager.core.listener;
020
021import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.ABOUT_TO_CREATE;
022import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.BEFORE_DOC_UPDATE;
023
024import java.io.IOException;
025import java.security.MessageDigest;
026import java.security.NoSuchAlgorithmException;
027import java.util.List;
028
029import org.apache.commons.codec.binary.Base64;
030import org.apache.commons.codec.digest.DigestUtils;
031import org.apache.commons.logging.Log;
032import org.apache.commons.logging.LogFactory;
033import org.nuxeo.ecm.core.api.Blob;
034import org.nuxeo.ecm.core.api.DocumentModel;
035import org.nuxeo.ecm.core.api.PropertyException;
036import org.nuxeo.ecm.core.api.model.Property;
037import org.nuxeo.ecm.core.event.Event;
038import org.nuxeo.ecm.core.event.EventContext;
039import org.nuxeo.ecm.core.event.EventListener;
040import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
041import org.nuxeo.ecm.platform.filemanager.api.FileManager;
042import org.nuxeo.runtime.api.Framework;
043
044public class DigestComputer implements EventListener {
045
046    private boolean initDone = false;
047
048    private List<String> xpathFields;
049
050    private String digestAlgo = "sha-256";
051
052    private Boolean activateDigestComputation = false;
053
054    private static final Log log = LogFactory.getLog(DigestComputer.class);
055
056    private boolean initIfNeeded() {
057        if (!initDone) {
058            FileManager fm = Framework.getService(FileManager.class);
059            xpathFields = fm.getFields();
060            digestAlgo = fm.getDigestAlgorithm();
061            activateDigestComputation = fm.isDigestComputingEnabled();
062            initDone = true;
063        }
064        return initDone;
065    }
066
067    private void addDigestToDocument(DocumentModel doc) {
068        for (String xpathField : xpathFields) {
069            Property blobProp = null;
070            try {
071                blobProp = doc.getProperty(xpathField);
072            } catch (PropertyException e) {
073                log.debug("Property " + xpathField + " not found on doc, skipping");
074            }
075            if (blobProp != null && !blobProp.isPhantom() && blobProp.isDirty()) {
076                try {
077                    Blob blob = (Blob) blobProp.getValue();
078                    if (blob != null) {
079                        String digest = computeDigest(blob);
080                        if (!digest.equals(blob.getDigest())) {
081                            blob.setDigest(digest);
082                        }
083                    }
084                } catch (PropertyException | IOException e) {
085                    log.error("Error while trying to save blob digest", e);
086                }
087            }
088        }
089    }
090
091    private String computeDigest(Blob blob) throws IOException {
092
093        MessageDigest md;
094        try {
095            md = MessageDigest.getInstance(digestAlgo);
096        } catch (NoSuchAlgorithmException e) {
097            throw new RuntimeException(e);
098        }
099        byte[] b = DigestUtils.updateDigest(md, blob.getStream()).digest();
100        return Base64.encodeBase64String(b);
101    }
102
103    public void handleEvent(Event event) {
104        if (!initIfNeeded()) {
105            return;
106        }
107
108        if (!activateDigestComputation) {
109            return;
110        }
111
112        EventContext ctx = event.getContext();
113        String evt = event.getName();
114        if (ABOUT_TO_CREATE.equals(evt) || BEFORE_DOC_UPDATE.equals(evt)) {
115
116            if (ctx instanceof DocumentEventContext) {
117                DocumentEventContext docCtx = (DocumentEventContext) ctx;
118                DocumentModel doc = docCtx.getSourceDocument();
119                if (doc == null || doc.isProxy()) {
120                    return;
121                }
122                addDigestToDocument(doc);
123            }
124        }
125    }
126
127}