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