2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.automation.jsscripting.internal.scope;
15 import java.util.ArrayList;
16 import java.util.Comparator;
17 import java.util.List;
18 import java.util.function.Consumer;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
24 * Allows scripts to register for lifecycle events
26 * @author Jonathan Gilbert - Initial contribution
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<>();
33 public void addDisposeHook(Consumer<Object> listener, int priority) {
34 addListener(listener, priority);
37 public void addDisposeHook(Consumer<Object> listener) {
38 addDisposeHook(listener, DEFAULT_PRIORITY);
41 private void addListener(Consumer<Object> listener, int priority) {
42 listeners.add(new Hook(priority, listener));
46 public void unload(String scriptIdentifier) {
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());
55 private static class Hook {
56 public Hook(int priority, Consumer<Object> fn) {
57 this.priority = priority;