]> git.basschouten.com Git - openhab-addons.git/blob
35cfcea12457abfb016aca2440703f4c3441f01e
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.OpenHAB;
23 import org.openhab.core.service.AbstractWatchService;
24 import org.openhab.core.transform.TransformationService;
25 import org.osgi.service.component.annotations.Activate;
26 import org.osgi.service.component.annotations.Component;
27 import org.osgi.service.component.annotations.Reference;
28
29 /**
30  * The {@link TransformationScriptWatcher} watches the transformation directory for files. If a deleted/modified file is
31  * detected, the script is passed to the {@link JavaScriptEngineManager}.
32  *
33  * @author Thomas Kordelle - Initial contribution
34  * @author Thomas Kordelle - pre compiled scripts
35  */
36 @Component
37 public class TransformationScriptWatcher extends AbstractWatchService {
38
39     public static final String TRANSFORM_FOLDER = OpenHAB.getConfigFolder() + File.separator
40             + TransformationService.TRANSFORM_FOLDER_NAME;
41
42     private final JavaScriptEngineManager manager;
43
44     @Activate
45     public TransformationScriptWatcher(final @Reference JavaScriptEngineManager manager) {
46         super(TRANSFORM_FOLDER);
47         this.manager = manager;
48     }
49
50     @Override
51     public void activate() {
52         super.activate();
53     }
54
55     @Override
56     protected boolean watchSubDirectories() {
57         return true;
58     }
59
60     @Override
61     protected Kind<?>[] getWatchEventKinds(Path directory) {
62         return new Kind<?>[] { ENTRY_DELETE, ENTRY_MODIFY };
63     }
64
65     @SuppressWarnings("unchecked")
66     @Override
67     protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
68         logger.debug("New watch event {} for path {}.", kind, path);
69
70         if (kind == OVERFLOW) {
71             return;
72         }
73
74         final WatchEvent<Path> ev = (WatchEvent<Path>) event;
75         final Path filename = ev.context();
76
77         logger.debug("Reloading javascript file {}.", filename);
78
79         manager.removeFromCache(filename.toString());
80     }
81 }