]> git.basschouten.com Git - openhab-addons.git/blob
1661eb1ad2f13d4a5c6c6b92a2b46b6f2c911117
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.automation.jsscripting.internal.scope;
14
15 import java.util.ArrayList;
16 import java.util.Comparator;
17 import java.util.List;
18 import java.util.function.Consumer;
19
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 /**
24  * Allows scripts to register for lifecycle events
25  *
26  * @author Jonathan Gilbert - Initial contribution
27  */
28 public class Lifecycle implements ScriptDisposalAware {
29     private static final Logger logger = LoggerFactory.getLogger(Lifecycle.class);
30     public static final int DEFAULT_PRIORITY = 50;
31     private List<Hook> listeners = new ArrayList<>();
32
33     public void addDisposeHook(Consumer<Object> listener, int priority) {
34         addListener(listener, priority);
35     }
36
37     public void addDisposeHook(Consumer<Object> listener) {
38         addDisposeHook(listener, DEFAULT_PRIORITY);
39     }
40
41     private void addListener(Consumer<Object> listener, int priority) {
42         listeners.add(new Hook(priority, listener));
43     }
44
45     @Override
46     public void unload(String scriptIdentifier) {
47         try {
48             listeners.stream().sorted(Comparator.comparingInt(h -> h.priority))
49                     .forEach(h -> h.fn.accept(scriptIdentifier));
50         } catch (RuntimeException ex) {
51             logger.warn("Script unloading halted due to exception in disposal: {}: {}", ex.getClass(), ex.getMessage());
52         }
53     }
54
55     private static class Hook {
56         public Hook(int priority, Consumer<Object> fn) {
57             this.priority = priority;
58             this.fn = fn;
59         }
60
61         int priority;
62         Consumer<Object> fn;
63     }
64 }