]> git.basschouten.com Git - openhab-addons.git/blob
5ad9e61777cb7ebd7c691fc6dcef908aa6c15aea
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.transform.javascript.internal;
14
15 import static java.nio.file.StandardWatchEventKinds.*;
16
17 import java.io.File;
18 import java.nio.file.Path;
19 import java.nio.file.WatchEvent;
20 import java.nio.file.WatchEvent.Kind;
21
22 import org.openhab.core.config.core.ConfigConstants;
23 import org.openhab.core.service.AbstractWatchService;
24 import org.openhab.core.transform.TransformationService;
25 import org.osgi.service.component.annotations.Component;
26 import org.osgi.service.component.annotations.Reference;
27
28 /**
29  * The {@link TransformationScriptWatcher} watches the transformation directory for files. If a deleted/modified file is
30  * detected, the script is passed to the {@link JavaScriptEngineManager}.
31  *
32  * @author Thomas Kordelle - pre compiled scripts
33  *
34  */
35 @Component()
36 public class TransformationScriptWatcher extends AbstractWatchService {
37
38     public static final String TRANSFORM_FOLDER = ConfigConstants.getConfigFolder() + File.separator
39             + TransformationService.TRANSFORM_FOLDER_NAME;
40
41     private JavaScriptEngineManager manager;
42
43     public TransformationScriptWatcher() {
44         super(TRANSFORM_FOLDER);
45     }
46
47     @Reference
48     public void setJavaScriptEngineManager(JavaScriptEngineManager manager) {
49         this.manager = manager;
50     }
51
52     public void unsetJavaScriptEngineManager(JavaScriptEngineManager manager) {
53         this.manager = null;
54     }
55
56     @Override
57     public void activate() {
58         super.activate();
59     }
60
61     @Override
62     protected boolean watchSubDirectories() {
63         return true;
64     }
65
66     @Override
67     protected Kind<?>[] getWatchEventKinds(Path directory) {
68         return new Kind<?>[] { ENTRY_DELETE, ENTRY_MODIFY };
69     }
70
71     @SuppressWarnings("unchecked")
72     @Override
73     protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
74         logger.debug("New watch event {} for path {}.", kind, path);
75
76         if (kind == OVERFLOW) {
77             return;
78         }
79
80         final WatchEvent<Path> ev = (WatchEvent<Path>) event;
81         final Path filename = ev.context();
82
83         logger.debug("Reloading javascript file {}.", filename);
84
85         manager.removeFromCache(filename.toString());
86     }
87 }