810cd714c9482adef89ed2ac2e9d911dca0be2bf
[bgpcep.git] / config-loader / 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 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 BGPFileWatcher() throws IOException {
33         final File file = new File(DEFAULT_APP_CONFIG_FILE_PATH);
34         if (!file.exists()) {
35             file.mkdirs();
36         }
37
38         this.watchService = FileSystems.getDefault().newWatchService();
39         Runtime.getRuntime().addShutdownHook(new Thread(() -> {
40             try {
41                 BGPFileWatcher.this.watchService.close();
42             } catch (final IOException e) {
43                 LOG.warn(INTERRUPTED, e);
44             }
45         }));
46         PATH.register(this.watchService, OVERFLOW, ENTRY_CREATE);
47     }
48
49     @Override
50     public String getPathFile() {
51         return DEFAULT_APP_CONFIG_FILE_PATH;
52     }
53
54     @Override
55     public WatchService getWatchService() {
56         return this.watchService;
57     }
58
59     @Override
60     public synchronized void close() throws Exception {
61         if (this.watchService != null) {
62             this.watchService.close();
63         }
64     }
65 }