| 1 | package org.jtoolkit.essence.data.impl; |
| 2 | |
| 3 | import org.jetbrains.annotations.NotNull; |
| 4 | import static org.jtoolkit.essence.concurrency.Threads.getCurrentSES; |
| 5 | import org.jtoolkit.essence.data.Event; |
| 6 | |
| 7 | import java.lang.ref.WeakReference; |
| 8 | import java.util.concurrent.Executor; |
| 9 | |
| 10 | /* |
| 11 | Copyright 2006 Peter Lawrey |
| 12 | |
| 13 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 14 | you may not use this file except in compliance with the License. |
| 15 | You may obtain a copy of the License at |
| 16 | |
| 17 | http://www.apache.org/licenses/LICENSE-2.0 |
| 18 | |
| 19 | Unless required by applicable law or agreed to in writing, software |
| 20 | distributed under the License is distributed on an "AS IS" BASIS, |
| 21 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 22 | See the License for the specific language governing permissions and |
| 23 | limitations under the License. |
| 24 | */ |
| 25 | |
| 26 | /** |
| 27 | * @author Peter Lawrey |
| 28 | */ |
| 29 | public class ThreadedListener implements Event.Listener { |
| 30 | private final WeakReference<Executor> executor; |
| 31 | private final Event.Listener listener; |
| 32 | |
| 33 | public ThreadedListener(Event.Listener listener) { |
| 34 | this.listener = listener; |
| 35 | executor = new WeakReference<Executor>(getCurrentSES()); |
| 36 | } |
| 37 | |
| 38 | public Event.Listener getUnderlying() { |
| 39 | return listener; |
| 40 | } |
| 41 | |
| 42 | private void onCallback(@NotNull final Event e) { |
| 43 | Executor executor = this.executor.get(); |
| 44 | if (executor == null) throw new IllegalStateException("Executor no longer running."); |
| 45 | executor.execute(new Runnable() { |
| 46 | public void run() { |
| 47 | e.notifyListener(listener); |
| 48 | } |
| 49 | }); |
| 50 | } |
| 51 | |
| 52 | public void onStatusEvent(boolean online) throws IllegalStateException { |
| 53 | onCallback(new Event.StatusEvent(online)); |
| 54 | } |
| 55 | } |