Replace Preconditions.CheckNotNull per RequireNonNull
[bgpcep.git] / bgp / config-loader-impl / src / main / java / org / opendaylight / protocol / bgp / config / loader / impl / ConfigLoaderImpl.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.util.Objects.requireNonNull;
12
13 import java.io.File;
14 import java.io.FileInputStream;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.net.URISyntaxException;
18 import java.nio.file.WatchEvent;
19 import java.nio.file.WatchKey;
20 import java.nio.file.WatchService;
21 import java.util.HashMap;
22 import java.util.Map;
23 import java.util.regex.Pattern;
24 import javax.annotation.concurrent.GuardedBy;
25 import javax.xml.parsers.ParserConfigurationException;
26 import javax.xml.stream.XMLInputFactory;
27 import javax.xml.stream.XMLStreamException;
28 import javax.xml.stream.XMLStreamReader;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
30 import org.opendaylight.protocol.bgp.config.loader.spi.ConfigFileProcessor;
31 import org.opendaylight.protocol.bgp.config.loader.spi.ConfigLoader;
32 import org.opendaylight.yangtools.concepts.AbstractRegistration;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
35 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
36 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
37 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
40 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.xml.sax.SAXException;
44
45 public final class ConfigLoaderImpl implements ConfigLoader, AutoCloseable {
46     private static final Logger LOG = LoggerFactory.getLogger(ConfigLoaderImpl.class);
47     private static final String INTERRUPTED = "InterruptedException";
48     private static final String EXTENSION = "-.*\\.xml";
49     private static final String INITIAL = "^";
50     @GuardedBy("this")
51     private final Map<String, ConfigFileProcessor> configServices = new HashMap<>();
52     private final SchemaContext schemaContext;
53     private final BindingNormalizedNodeSerializer bindingSerializer;
54     private final String path;
55     private final Thread watcherThread;
56
57     public ConfigLoaderImpl(final SchemaContext schemaContext, final BindingNormalizedNodeSerializer bindingSerializer,
58         final String path, final WatchService watchService) {
59         this.schemaContext = requireNonNull(schemaContext);
60         this.bindingSerializer = requireNonNull(bindingSerializer);
61         this.path = requireNonNull(path);
62         requireNonNull(watchService);
63         this.watcherThread = new Thread(new ConfigLoaderImplRunnable(watchService));
64         this.watcherThread.start();
65         LOG.info("Config Loader service initiated");
66     }
67
68     private void handleConfigFile(final ConfigFileProcessor config, final String filename) {
69         final NormalizedNode<?, ?> dto;
70         try {
71             dto = parseDefaultConfigFile(config, filename);
72         } catch (final Exception e) {
73             LOG.warn("Failed to parse config file {}", filename, e);
74             return;
75         }
76         LOG.info("Loading initial config {}", filename);
77         config.loadConfiguration(dto);
78     }
79
80     private NormalizedNode<?, ?> parseDefaultConfigFile(final ConfigFileProcessor config, final String filename)
81         throws IOException, XMLStreamException, ParserConfigurationException, SAXException, URISyntaxException {
82         final NormalizedNodeResult result = new NormalizedNodeResult();
83         final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
84
85         final InputStream resourceAsStream = new FileInputStream(new File(this.path, filename));
86         final XMLInputFactory factory = XMLInputFactory.newInstance();
87         final XMLStreamReader reader = factory.createXMLStreamReader(resourceAsStream);
88
89         final SchemaNode schemaNode = SchemaContextUtil.findDataSchemaNode(this.schemaContext, config.getSchemaPath());
90         final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, this.schemaContext, schemaNode);
91         xmlParser.parse(reader);
92
93         return result.getResult();
94     }
95
96     @Override
97     public synchronized AbstractRegistration registerConfigFile(final ConfigFileProcessor config) {
98         final String pattern = INITIAL + config.getSchemaPath().getLastComponent().getLocalName() + EXTENSION;
99         this.configServices.put(pattern, config);
100
101         final File[] fList = new File(this.path).listFiles();
102         if (fList != null) {
103             for (final File file : fList) {
104                 if (file.isFile()) {
105                     final String filename = file.getName();
106                     if (Pattern.matches(pattern, filename)) {
107                         handleConfigFile(config, filename);
108                     }
109                 }
110             }
111         }
112
113         return new AbstractRegistration() {
114             @Override
115             protected void removeRegistration() {
116                 synchronized (ConfigLoaderImpl.this) {
117                     ConfigLoaderImpl.this.configServices.remove(pattern);
118                 }
119             }
120         };
121     }
122
123     @Override
124     public BindingNormalizedNodeSerializer getBindingNormalizedNodeSerializer() {
125         return this.bindingSerializer;
126     }
127
128
129     @Override
130     public void close() throws Exception {
131         this.watcherThread.interrupt();
132     }
133
134     private class ConfigLoaderImplRunnable implements Runnable {
135         private final WatchService watchService;
136
137         ConfigLoaderImplRunnable(final WatchService watchService) {
138             this.watchService = watchService;
139         }
140
141         @Override
142         public void run() {
143             try {
144                 while (!Thread.currentThread().isInterrupted()) {
145                     handleChanges(this.watchService);
146                 }
147             } catch (final Exception e) {
148                 LOG.warn(INTERRUPTED, e);
149             }
150         }
151
152         private synchronized void handleChanges(final WatchService watchService) {
153             try {
154                 final WatchKey key = watchService.take();
155                 if (key != null) {
156                     for (final WatchEvent<?> event : key.pollEvents()) {
157                         handleEvent(event.context().toString());
158                     }
159                     final boolean reset = key.reset();
160                     if (!reset) {
161                         LOG.warn("Could not reset the watch key.");
162                     }
163                 }
164             } catch (final InterruptedException e) {
165                 LOG.warn(INTERRUPTED, e);
166             }
167         }
168
169         private synchronized void handleEvent(final String filename) {
170             ConfigLoaderImpl.this.configServices.entrySet().stream()
171                 .filter(entry -> Pattern.matches(entry.getKey(), filename)).
172                 forEach(entry -> handleConfigFile(entry.getValue(), filename));
173         }
174     }
175 }