2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.mso.bpmn.core;
23 import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
26 import java.io.FileReader;
27 import java.io.IOException;
28 import java.nio.file.ClosedWatchServiceException;
29 import java.nio.file.FileSystems;
30 import java.nio.file.Path;
31 import java.nio.file.WatchEvent;
32 import java.nio.file.WatchKey;
33 import java.nio.file.WatchService;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.List;
40 import java.util.Map.Entry;
41 import java.util.Properties;
42 import java.util.Timer;
43 import java.util.TimerTask;
44 import java.util.concurrent.ConcurrentHashMap;
48 import org.openecomp.mso.logger.MessageEnum;
49 import org.openecomp.mso.logger.MsoLogger;
52 * Loads the property configuration from file system and refreshes the
53 * properties when the property gets changed.
55 * WARNING: automatic refreshes might not work on network filesystems.
57 public class PropertyConfiguration {
60 * The base name of the MSO BPMN properties file (mso.bpmn.properties).
62 public static final String MSO_BPMN_PROPERTIES = "mso.bpmn.properties";
65 * The base name of the MSO BPMN URN-Mappings properties file (mso.bpmn.urn.properties).
67 public static final String MSO_BPMN_URN_PROPERTIES = "mso.bpmn.urn.properties";
70 * The name of the meta-property holding the time the properties were loaded
73 public static final String TIMESTAMP_PROPERTY = "mso.properties.timestamp";
75 private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
77 private static final List<String> SUPPORTED_FILES =
78 Arrays.asList(MSO_BPMN_PROPERTIES, MSO_BPMN_URN_PROPERTIES);
80 private volatile String msoConfigPath = null;
82 private final ConcurrentHashMap<String, Map<String, String>> propFileCache =
83 new ConcurrentHashMap<String, Map<String, String>>();
85 private final Object CACHELOCK = new Object();
86 private FileWatcherThread fileWatcherThread = null;
88 // The key is the file name
89 private Map<String, TimerTask> timerTaskMap = new HashMap<String, TimerTask>();
92 * Singleton holder pattern eliminates locking when accessing the instance
93 * and still provides for lazy initialization.
95 private static class PropertyConfigurationInstanceHolder {
96 private static PropertyConfiguration instance = new PropertyConfiguration();
100 * Gets the one and only instance of this class.
102 public static PropertyConfiguration getInstance() {
103 return PropertyConfigurationInstanceHolder.instance;
107 * Returns the list of supported files.
109 public static List<String> supportedFiles() {
110 return new ArrayList<String>(SUPPORTED_FILES);
114 * Private Constructor.
116 private PropertyConfiguration() {
121 * May be called to restart the PropertyConfiguration if it was previously shut down.
123 public synchronized void startUp() {
124 msoConfigPath = System.getProperty("mso.config.path");
126 if (msoConfigPath == null) {
127 LOGGER.debug("mso.config.path JVM system property is not set");
132 Path directory = FileSystems.getDefault().getPath(msoConfigPath);
133 WatchService watchService = FileSystems.getDefault().newWatchService();
134 directory.register(watchService, ENTRY_MODIFY);
136 LOGGER.info(MessageEnum.BPMN_GENERAL_INFO, "BPMN", "Starting FileWatcherThread");
137 LOGGER.debug("Starting FileWatcherThread");
138 fileWatcherThread = new FileWatcherThread(watchService);
139 fileWatcherThread.start();
140 } catch (Exception e) {
141 LOGGER.debug("Error occurred while starting FileWatcherThread:", e);
143 MessageEnum.BPMN_GENERAL_EXCEPTION,
145 "Property Configuration",
146 MsoLogger.ErrorCode.UnknownError,
147 "Error occurred while starting FileWatcherThread:" + e);
152 * May be called to shut down the PropertyConfiguration. A shutDown followed
153 * by a startUp will reset the PropertyConfiguration to its initial state.
155 public synchronized void shutDown() {
156 if (fileWatcherThread != null) {
157 LOGGER.debug("Shutting down FileWatcherThread " + System.identityHashCode(fileWatcherThread));
158 fileWatcherThread.shutdown();
160 long waitInSeconds = 10;
163 fileWatcherThread.join(waitInSeconds * 1000);
164 } catch (InterruptedException e) {
165 LOGGER.debug("FileWatcherThread " + System.identityHashCode(fileWatcherThread)
166 + " shutdown did not occur within " + waitInSeconds + " seconds");
169 LOGGER.debug("Finished shutting down FileWatcherThread " + System.identityHashCode(fileWatcherThread));
170 fileWatcherThread = null;
174 msoConfigPath = null;
177 public synchronized boolean isFileWatcherRunning() {
178 return fileWatcherThread != null;
181 public void clearCache() {
182 synchronized(CACHELOCK) {
183 propFileCache.clear();
187 public int cacheSize() {
188 return propFileCache.size();
191 // TODO: throw IOException?
192 public Map<String, String> getProperties(String fileName) {
193 Map<String, String> properties = propFileCache.get(fileName);
195 if (properties == null) {
196 if (!SUPPORTED_FILES.contains(fileName)) {
197 throw new IllegalArgumentException("Not a supported property file: " + fileName);
200 if (msoConfigPath == null) {
201 LOGGER.debug("mso.config.path JVM system property must be set to load " + fileName);
204 MessageEnum.BPMN_GENERAL_EXCEPTION,
207 MsoLogger.ErrorCode.UnknownError,
208 "mso.config.path JVM system property must be set to load " + fileName);
214 properties = readProperties(new File(msoConfigPath, fileName));
215 } catch (Exception e) {
216 LOGGER.debug("Error loading " + fileName);
219 MessageEnum.BPMN_GENERAL_EXCEPTION,
222 MsoLogger.ErrorCode.UnknownError,
223 "Error loading " + fileName, e);
229 return Collections.unmodifiableMap(properties);
233 * Reads properties from the specified file, updates the property file cache, and
234 * returns the properties in a map.
235 * @param file the file to read
236 * @param reload true if this is a reload event
237 * @return a map of properties
239 private Map<String, String> readProperties(File file) throws IOException {
240 String fileName = file.getName();
241 LOGGER.debug("Reading " + fileName);
243 Map<String, String> properties = new HashMap<String, String>();
244 Properties newProperties = new Properties();
246 FileReader reader = null;
248 reader = new FileReader(file);
249 newProperties.load(reader);
251 if (reader != null) {
254 LOGGER.debug("Closed " + fileName);
255 } catch (Exception e) {
261 for (Entry<Object, Object> entry : newProperties.entrySet()) {
262 properties.put(entry.getKey().toString(), entry.getValue().toString());
265 properties.put(TIMESTAMP_PROPERTY, String.valueOf(System.currentTimeMillis()));
267 synchronized(CACHELOCK) {
268 propFileCache.put(fileName, properties);
275 * File watcher thread which monitors a directory for file modification.
277 private class FileWatcherThread extends Thread {
278 private final WatchService watchService;
279 private final Timer timer = new Timer("FileWatcherTimer");
281 public FileWatcherThread(WatchService service) {
282 this.watchService = service;
285 public void shutdown() {
290 LOGGER.info(MessageEnum.BPMN_GENERAL_INFO, "BPMN",
291 "FileWatcherThread started");
293 LOGGER.debug("Started FileWatcherThread " + System.identityHashCode(fileWatcherThread));
296 WatchKey watchKey = null;
298 while (!isInterrupted()) {
300 if (watchKey != null) {
304 watchKey = watchService.take();
306 for (WatchEvent<?> event : watchKey.pollEvents()) {
307 @SuppressWarnings("unchecked")
308 WatchEvent<Path> pathEvent = (WatchEvent<Path>) event;
310 if ("EVENT_OVERFLOW".equals(pathEvent.kind())) {
311 LOGGER.debug("Ignored overflow event for " + msoConfigPath);
315 String fileName = pathEvent.context().getFileName().toString();
317 if (!SUPPORTED_FILES.contains(fileName)) {
318 LOGGER.debug("Ignored modify event for " + fileName);
322 LOGGER.debug("Configuration file has changed: " + fileName);
324 LOGGER.info(MessageEnum.BPMN_GENERAL_INFO, "BPMN",
325 "Configuation file has changed: " + fileName);
327 // There's a potential problem here. The MODIFY event is
328 // triggered as soon as somebody starts writing the file but
329 // there's no obvious way to know when the write is done. If we
330 // read the file while the write is still in progress, then the
331 // cache can really be messed up. As a workaround, we use a timer
332 // to sleep for at least one second, and then we sleep for as long
333 // as it takes for the file's lastModified time to stop changing.
334 // The timer has another benefit: it consolidates multiple events
335 // that we seem to receive when a file is modified.
337 synchronized(timerTaskMap) {
338 TimerTask task = timerTaskMap.get(fileName);
344 File file = new File(msoConfigPath, fileName);
345 task = new DelayTimerTask(timer, file, 1000);
346 timerTaskMap.put(fileName, task);
349 } catch (InterruptedException e) {
351 } catch (ClosedWatchServiceException e) {
353 MessageEnum.BPMN_GENERAL_INFO,
355 "FileWatcherThread shut down because the watch service was closed");
357 } catch (Exception e) {
359 MessageEnum.BPMN_GENERAL_EXCEPTION,
361 "Property Configuration",
362 MsoLogger.ErrorCode.UnknownError,
363 "FileWatcherThread caught unexpected " + e.getClass().getSimpleName(), e);
370 synchronized(timerTaskMap) {
371 timerTaskMap.clear();
375 watchService.close();
376 } catch (IOException e) {
377 LOGGER.debug("FileWatcherThread caught " + e.getClass().getSimpleName()
378 + " while closing the watch service");
381 LOGGER.info(MessageEnum.BPMN_GENERAL_INFO, "BPMN",
382 "FileWatcherThread stopped");
387 private class DelayTimerTask extends TimerTask {
388 private final File file;
389 private final long lastModifiedTime;
390 private final Timer timer;
392 public DelayTimerTask(Timer timer, File file, long delay) {
395 this.lastModifiedTime = file.lastModified();
396 timer.schedule(this, delay);
402 long newLastModifiedTime = file.lastModified();
404 if (newLastModifiedTime == lastModifiedTime) {
406 readProperties(file);
407 } catch (Exception e) {
409 MessageEnum.BPMN_GENERAL_EXCEPTION,
411 "Property Configuration",
412 MsoLogger.ErrorCode.UnknownError,
413 "Unable to reload " + file, e);
416 LOGGER.debug("Delaying reload of " + file + " by 1 second");
418 synchronized(timerTaskMap) {
419 TimerTask task = timerTaskMap.get(file.getName());
421 if (task != null && task != this) {
425 task = new DelayTimerTask(timer, file, 1000);
426 timerTaskMap.put(file.getName(), task);
430 synchronized(timerTaskMap) {
431 TimerTask task = timerTaskMap.get(file.getName());
434 timerTaskMap.remove(file.getName());