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 org.apache.logging.log4j.core.util.FileWatcher;
020import org.apache.logging.log4j.core.util.Log4jThread;
021
022import java.io.File;
023import java.util.List;
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> listeners;
032
033    public ConfiguratonFileWatcher(Reconfigurable reconfigurable, final List<ConfigurationListener> listeners) {
034        this.reconfigurable = reconfigurable;
035        this.listeners = listeners;
036    }
037
038    public List<ConfigurationListener> getListeners() {
039        return listeners;
040    }
041
042
043    @Override
044    public void fileModified(File file) {
045        for (final ConfigurationListener listener : listeners) {
046            final Thread thread = new Log4jThread(new ReconfigurationWorker(listener, reconfigurable));
047            thread.setDaemon(true);
048            thread.start();
049        }
050    }
051
052    /**
053     * Helper class for triggering a reconfiguration in a background thread.
054     */
055    private static class ReconfigurationWorker implements Runnable {
056
057        private final ConfigurationListener listener;
058        private final Reconfigurable reconfigurable;
059
060        public ReconfigurationWorker(final ConfigurationListener listener, final Reconfigurable reconfigurable) {
061            this.listener = listener;
062            this.reconfigurable = reconfigurable;
063        }
064
065        @Override
066        public void run() {
067            listener.onChange(reconfigurable);
068        }
069    }
070}