001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.config;
018
019import java.io.File;
020import java.util.List;
021
022import org.apache.logging.log4j.core.util.FileWatcher;
023import org.apache.logging.log4j.core.util.Log4jThreadFactory;
024
025/**
026 * Watcher for configuration files. Causes a reconfiguration when a file changes.
027 */
028public class ConfiguratonFileWatcher implements FileWatcher {
029
030    private final Reconfigurable reconfigurable;
031    private final List<ConfigurationListener> configurationListeners;
032    private final Log4jThreadFactory threadFactory;
033
034    public ConfiguratonFileWatcher(final Reconfigurable reconfigurable, final List<ConfigurationListener> configurationListeners) {
035        this.reconfigurable = reconfigurable;
036        this.configurationListeners = configurationListeners;
037        this.threadFactory = Log4jThreadFactory.createDaemonThreadFactory("ConfiguratonFileWatcher");
038    }
039
040    public List<ConfigurationListener> getListeners() {
041        return configurationListeners;
042    }
043
044
045    @Override
046    public void fileModified(final File file) {
047        for (final ConfigurationListener configurationListener : configurationListeners) {
048            final Thread thread = threadFactory.newThread(new ReconfigurationRunnable(configurationListener, reconfigurable));
049            thread.start();
050        }
051    }
052
053    /**
054     * Helper class for triggering a reconfiguration in a background thread.
055     */
056    private static class ReconfigurationRunnable implements Runnable {
057
058        private final ConfigurationListener configurationListener;
059        private final Reconfigurable reconfigurable;
060
061        public ReconfigurationRunnable(final ConfigurationListener configurationListener, final Reconfigurable reconfigurable) {
062            this.configurationListener = configurationListener;
063            this.reconfigurable = reconfigurable;
064        }
065
066        @Override
067        public void run() {
068            configurationListener.onChange(reconfigurable);
069        }
070    }
071}