]> git.basschouten.com Git - openhab-addons.git/blob
46a7314bcefe262a5722090ef612f78c092d2234
[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.binding.jellyfin.internal.util;
14
15 import java.util.concurrent.CountDownLatch;
16 import java.util.concurrent.TimeUnit;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.jellyfin.sdk.compatibility.JavaContinuation;
21
22 /**
23  * The {@link SyncCallback} util to consume kotlin suspend functions.
24  *
25  * @author Miguel Álvarez - Initial contribution
26  */
27 @NonNullByDefault
28 public abstract class SyncCallback<T> extends JavaContinuation<@Nullable T> {
29     private final CountDownLatch latch;
30     @Nullable
31     private T result;
32     @Nullable
33     private Throwable error;
34
35     protected SyncCallback() {
36         latch = new CountDownLatch(1);
37     }
38
39     @Override
40     public void onSuccess(@Nullable T result) {
41         this.result = result;
42         latch.countDown();
43     }
44
45     @Override
46     public void onError(@Nullable Throwable error) {
47         this.error = error;
48         latch.countDown();
49     }
50
51     public T awaitResult() throws SyncCallbackError {
52         return awaitResult(10);
53     }
54
55     public T awaitResult(int timeoutSecs) throws SyncCallbackError {
56         try {
57             if (!latch.await(timeoutSecs, TimeUnit.SECONDS)) {
58                 throw new SyncCallbackError("Execution timeout");
59             }
60         } catch (InterruptedException e) {
61             throw new SyncCallbackError(e);
62         }
63         var error = this.error;
64         if (error != null) {
65             throw new SyncCallbackError(error);
66         }
67         var result = this.result;
68         if (result == null) {
69             throw new SyncCallbackError("Missing result");
70         }
71         return result;
72     }
73
74     public static class SyncCallbackError extends Exception {
75         private static final long serialVersionUID = 2157912759968949551L;
76
77         protected SyncCallbackError(String message) {
78             super(message);
79         }
80
81         protected SyncCallbackError(Throwable original) {
82             super(original);
83         }
84     }
85 }