BUG-6857: ConfigLoader rework
[bgpcep.git] / bgp / config-loader-impl / src / main / java / org / opendaylight / protocol / bgp / config / loader / impl / BGPFileWatcher.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.protocol.bgp.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 BGPFileWatcher implements FileWatcher, AutoCloseable {
24     private static final Logger LOG = LoggerFactory.getLogger(BGPFileWatcher.class);
25     private static final String INTERRUPTED = "InterruptedException";
26     private static final String DEFAULT_APP_CONFIG_FILE_PATH = "etc" + File.separator + "opendaylight" + File.separator + "bgp";
27     private static final Path PATH = Paths.get(DEFAULT_APP_CONFIG_FILE_PATH);
28     private final WatchService watchService;
29
30     public BGPFileWatcher() throws IOException {
31         this.watchService = FileSystems.getDefault().newWatchService();
32         Runtime.getRuntime().addShutdownHook(new Thread() {
33             @Override
34             public void run() {
35                 try {
36                     BGPFileWatcher.this.watchService.close();
37                 } catch (final IOException e) {
38                     LOG.warn(INTERRUPTED, e);
39                 }
40             }
41         });
42         PATH.register(this.watchService, OVERFLOW, ENTRY_CREATE);
43     }
44
45     @Override
46     public String getPathFile() {
47         return DEFAULT_APP_CONFIG_FILE_PATH;
48     }
49
50     @Override
51     public WatchService getWatchService() {
52         return this.watchService;
53     }
54
55     @Override
56     public synchronized void close() throws Exception {
57         if (this.watchService != null) {
58             this.watchService.close();
59         }
60     }
61 }