001/*
002 * (C) Copyright 2006-2009 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 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.platform.filemanager.core.listener;
023
024import java.security.Principal;
025import java.util.ArrayList;
026import java.util.List;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.nuxeo.ecm.core.api.CoreSession;
031import org.nuxeo.ecm.core.api.DocumentLocation;
032import org.nuxeo.ecm.core.api.DocumentModel;
033import org.nuxeo.ecm.core.api.event.DocumentEventTypes;
034import org.nuxeo.ecm.core.event.Event;
035import org.nuxeo.ecm.core.event.EventContext;
036import org.nuxeo.ecm.core.event.EventListener;
037import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
038
039public class SynchronousUnicityCheckListener extends AbstractUnicityChecker implements EventListener {
040
041    private static final Log log = LogFactory.getLog(SynchronousUnicityCheckListener.class);
042
043    public void handleEvent(Event event) {
044        if (!isUnicityCheckEnabled()) {
045            return;
046        }
047
048        List<String> uuids = new ArrayList<String>();
049        if (DocumentEventTypes.DOCUMENT_CREATED.equals(event.getName())
050                || DocumentEventTypes.DOCUMENT_UPDATED.equals(event.getName())) {
051            EventContext ctx = event.getContext();
052            if (ctx instanceof DocumentEventContext) {
053                DocumentEventContext docCtx = (DocumentEventContext) ctx;
054
055                DocumentModel doc2Check = docCtx.getSourceDocument();
056                if (doc2Check.isProxy()) {
057                    // NOP
058                }
059                if (!uuids.contains(doc2Check.getId())) {
060                    uuids.add(doc2Check.getId());
061                    doUnicityCheck(doc2Check, docCtx.getCoreSession(), event);
062                }
063            }
064        }
065    }
066
067    @Override
068    protected void onDuplicatedDoc(CoreSession session, Principal principal, DocumentModel newDoc,
069            List<DocumentLocation> existingDocs, Event event) {
070        // simply send a message
071        log.info("Duplicated file detected");
072        raiseDuplicatedFileEvent(session, principal, newDoc, existingDocs);
073    }
074
075}