001/*
002 * (C) Copyright 2012-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 *     Anahide Tchertchian
018 */
019package org.nuxeo.ecm.directory;
020
021import java.util.List;
022
023import org.apache.commons.logging.Log;
024import org.apache.commons.logging.LogFactory;
025import org.nuxeo.ecm.directory.api.DirectoryService;
026import org.nuxeo.runtime.api.Framework;
027import org.nuxeo.runtime.reload.ReloadEventNames;
028import org.nuxeo.runtime.services.event.Event;
029import org.nuxeo.runtime.services.event.EventListener;
030
031/**
032 * Event listener that flushes the {@link DirectoryService} caches.
033 *
034 * @since 5.6
035 */
036public class DirectoryCacheFlusher implements EventListener {
037
038    private static final Log log = LogFactory.getLog(DirectoryCacheFlusher.class);
039
040    @Override
041    public void handleEvent(Event event) {
042        if (!Framework.isDevModeSet()) {
043            log.info("Do not flush the directory caches: dev mode is not set");
044            return;
045        }
046        if (!ReloadEventNames.FLUSH_EVENT_ID.equals(event.getId())) {
047            return;
048        }
049        try {
050            DirectoryService service = Framework.getService(DirectoryService.class);
051            List<Directory> directories = service.getDirectories();
052            if (directories != null) {
053                for (Directory directory : directories) {
054                    directory.getCache().invalidateAll();
055                }
056            }
057        } catch (DirectoryException e) {
058            log.error("Error while flushing the directory caches", e);
059        }
060    }
061
062}