001/*
002 * (C) Copyright 2014 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 *     Vladimir Pasquier <vpasquier@nuxeo.com>
018 */
019
020package org.nuxeo.binary.metadata.internals.listeners;
021
022import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.ABOUT_TO_CREATE;
023import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.BEFORE_DOC_UPDATE;
024
025import org.nuxeo.binary.metadata.api.BinaryMetadataConstants;
026import org.nuxeo.binary.metadata.api.BinaryMetadataService;
027import org.nuxeo.ecm.core.api.DocumentModel;
028import org.nuxeo.ecm.core.event.Event;
029import org.nuxeo.ecm.core.event.EventContext;
030import org.nuxeo.ecm.core.event.EventListener;
031import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
032import org.nuxeo.runtime.api.Framework;
033
034/**
035 * Handle document and blob updates according to following rules in an event context: - Define if rule should be
036 * executed in async or sync mode. - If Blob dirty and document metadata dirty, write metadata from doc to Blob. - If
037 * Blob dirty and document metadata not dirty, write metadata from Blob to doc. - If Blob not dirty and document
038 * metadata dirty, write metadata from doc to Blob.
039 *
040 * @since 7.1
041 */
042public class BinaryMetadataSyncListener implements EventListener {
043
044    @Override
045    public void handleEvent(Event event) {
046        EventContext ctx = event.getContext();
047        if (!(ctx instanceof DocumentEventContext)) {
048            return;
049        }
050        BinaryMetadataService binaryMetadataService = Framework.getService(BinaryMetadataService.class);
051        DocumentEventContext docCtx = (DocumentEventContext) ctx;
052        DocumentModel doc = docCtx.getSourceDocument();
053        Boolean disable = (Boolean) event.getContext().getProperty(
054                BinaryMetadataConstants.DISABLE_BINARY_METADATA_LISTENER);
055        if (ABOUT_TO_CREATE.equals(event.getName()) && !doc.isProxy() && disable == null) {
056            binaryMetadataService.writeMetadata(doc);
057        } else if (BEFORE_DOC_UPDATE.equals(event.getName()) && !doc.isProxy() && disable == null) {
058            doc.putContextData(BinaryMetadataConstants.DISABLE_BINARY_METADATA_LISTENER, Boolean.TRUE);
059            binaryMetadataService.handleSyncUpdate(doc);
060        }
061    }
062
063}