RunFileEventCallbacks.java

/*
 * Copyright (c) 2017, Stein Eldar Johnsen
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.file.internal;

import net.morimekta.file.DirWatcher;
import net.morimekta.file.FileEvent;
import net.morimekta.file.FileEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;

public class RunFileEventCallbacks implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(DirWatcher.class);

    private final Set<Map.Entry<Path, FileEvent>>              updates;
    private final Map<Path, List<Supplier<FileEventListener>>> watcherMap;

    public RunFileEventCallbacks(Set<Map.Entry<Path, FileEvent>> updates,
                                 Map<Path, List<Supplier<FileEventListener>>> watcherMap) {
        this.updates = updates;
        this.watcherMap = watcherMap;
    }

    @Override
    public void run() {
        for (Map.Entry<Path, FileEvent> request : updates) {
            List<Supplier<FileEventListener>> suppliers = watcherMap.get(request.getKey()
                                                                                .getParent());
            if (suppliers != null) {
                for (final Supplier<FileEventListener> supplier : suppliers) {
                    FileEventListener watcher = supplier.get();
                    if (watcher != null) {
                        try {
                            // System.err.println(request.getKey() + ": " + request.getValue());
                            watcher.onFileEvent(request.getKey(), request.getValue());
                        } catch (Exception e) {
                            LOGGER.error("Exception when notifying update on {}", request, e);
                        }
                    }
                }
            }
        }
    }
}