2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 Nokia. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.pnfsimulator.filesystem;
23 import java.io.IOException;
24 import java.nio.file.FileSystems;
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 import java.nio.file.StandardWatchEventKinds;
28 import java.nio.file.WatchEvent;
29 import java.nio.file.WatchKey;
30 import java.nio.file.WatchService;
31 import lombok.extern.slf4j.Slf4j;
32 import org.onap.pnfsimulator.db.Storage;
33 import org.onap.pnfsimulator.template.Template;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.beans.factory.annotation.Value;
36 import org.springframework.stereotype.Component;
40 public class WatcherThread implements Runnable {
42 private final WatchService watchService;
43 private final Storage<Template> storage;
44 private final Path templatesDir;
46 WatcherThread(String templatesDir, WatchService watchService, Storage<Template> storage) throws IOException {
47 this.watchService = watchService;
48 this.storage = storage;
49 this.templatesDir = Paths.get(templatesDir);
50 registerDirectory(this.templatesDir);
54 public WatcherThread(@Value("${templates.dir}") String templatesDir, Storage<Template> storage) throws IOException {
55 this(templatesDir, FileSystems.getDefault().newWatchService(), storage);
58 private void registerDirectory(Path path) throws IOException {
59 path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
60 StandardWatchEventKinds.ENTRY_MODIFY);
68 key = watchService.take();
69 for (WatchEvent<?> event : key.pollEvents()) {
70 WatcherEventProcessor.process(event, storage, templatesDir);
73 } catch (InterruptedException e) {
74 log.error("Watch service interrupted.", e.getMessage());
75 Thread.currentThread().interrupt();