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 *     Arnaud Kervern <akervern@nuxeo.com>
018 */
019
020package org.nuxeo.ecm.user.registration;
021
022import static org.nuxeo.ecm.core.api.event.DocumentEventTypes.DOCUMENT_REMOVED;
023import static org.nuxeo.ecm.user.registration.DocumentRegistrationInfo.DOCUMENT_ID_FIELD;
024
025import org.nuxeo.ecm.core.api.DocumentModel;
026import org.nuxeo.ecm.core.api.DocumentModelList;
027import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
028import org.nuxeo.ecm.core.event.Event;
029import org.nuxeo.ecm.core.event.EventListener;
030import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
031
032public class RegistrationCleanerListener implements EventListener {
033
034    @Override
035    public void handleEvent(Event event) {
036        if (!event.getName().equals(DOCUMENT_REMOVED) || !(event.getContext() instanceof DocumentEventContext)) {
037            return;
038        }
039
040        DocumentEventContext context = (DocumentEventContext) event.getContext();
041        final DocumentModel sourceDocument = context.getSourceDocument();
042
043        if (sourceDocument.getType().equals("UserRegistration") || sourceDocument.isVersion()) {
044            return;
045        }
046
047        new UnrestrictedSessionRunner(context.getCoreSession()) {
048            @Override
049            public void run() {
050                DocumentModelList docs = session.query(String.format(
051                        "Select * from Document where ecm:mixinType = 'UserRegistration' and %s = '%s'",
052                        DOCUMENT_ID_FIELD, sourceDocument.getId()));
053                for (DocumentModel doc : docs) {
054                    session.removeDocument(doc.getRef());
055                }
056            }
057        }.runUnrestricted();
058    }
059}