BGPCEP-710: Create Network Topology Loader
[bgpcep.git] / config-loader / config-loader-impl / src / main / java / org / opendaylight / bgpcep / config / loader / impl / FileWatcherImpl.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.bgpcep.config.loader.impl;
10
11 import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
12 import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
13
14 import java.io.File;
15 import java.io.IOException;
16 import java.nio.file.FileSystems;
17 import java.nio.file.Path;
18 import java.nio.file.Paths;
19 import java.nio.file.WatchService;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 public final class FileWatcherImpl implements FileWatcher, AutoCloseable {
24     private static final Logger LOG = LoggerFactory.getLogger(FileWatcherImpl.class);
25     private static final String INTERRUPTED = "InterruptedException";
26     private static final String BGPCEP_CONFIG_FOLDER = "bgpcep";
27     private static final String DEFAULT_APP_CONFIG_FILE_PATH = "etc" + File.separator + "opendaylight"
28             + File.separator + BGPCEP_CONFIG_FOLDER + File.separator;
29     private static final Path PATH = Paths.get(DEFAULT_APP_CONFIG_FILE_PATH);
30     private final WatchService watchService;
31
32     public FileWatcherImpl() throws IOException {
33         this.watchService = FileSystems.getDefault().newWatchService();
34         final File file = new File(DEFAULT_APP_CONFIG_FILE_PATH);
35         if (!file.exists()) {
36             if (file.mkdirs()) {
37                 return;
38             }
39         }
40
41         Runtime.getRuntime().addShutdownHook(new Thread(() -> {
42             try {
43                 FileWatcherImpl.this.watchService.close();
44             } catch (final IOException e) {
45                 LOG.warn(INTERRUPTED, e);
46             }
47         }));
48         PATH.register(this.watchService, OVERFLOW, ENTRY_CREATE);
49         LOG.info("File Watcher service initiated");
50     }
51
52     @Override
53     public String getPathFile() {
54         return DEFAULT_APP_CONFIG_FILE_PATH;
55     }
56
57     @Override
58     public synchronized WatchService getWatchService() {
59         return this.watchService;
60     }
61
62     @Override
63     public synchronized void close() throws Exception {
64         if (this.watchService != null) {
65             this.watchService.close();
66         }
67     }
68 }