]> git.basschouten.com Git - openhab-addons.git/blob
b869f231705db65c4281d61a5f6526050539bf70
[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.pjlinkdevice.internal.device.command;
14
15 import java.io.IOException;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.core.cache.ExpiringCache;
20
21 /**
22  * CachedCommand wraps any command and caches its response for a configurable period of time.
23  *
24  * @author Nils Schnabel - Initial contribution
25  */
26 @NonNullByDefault
27 public class CachedCommand<ResponseType extends Response<?>> implements Command<ResponseType> {
28
29     private Command<ResponseType> cachedCommand;
30     private ExpiringCache<ResponseType> cache;
31
32     public CachedCommand(Command<ResponseType> cachedCommand) {
33         this(cachedCommand, 1000);
34     }
35
36     public CachedCommand(Command<ResponseType> cachedCommand, int expiry) {
37         this.cachedCommand = cachedCommand;
38         this.cache = new ExpiringCache<>(expiry, () -> {
39             try {
40                 return this.cachedCommand.execute();
41             } catch (ResponseException | IOException | AuthenticationException e) {
42                 // wrap exception into RuntimeException to unwrap again later in CachedCommand.execute()
43                 throw new CacheException(e);
44             }
45         });
46     }
47
48     @Override
49     public ResponseType execute() throws ResponseException, IOException, AuthenticationException {
50         ExpiringCache<ResponseType> cache = this.cache;
51         try {
52             @Nullable
53             ResponseType result = cache.getValue();
54             if (result == null) {
55                 // this can not happen in reality, limitation of ExpiringCache
56                 throw new ResponseException("Cached value is null");
57             }
58             return result;
59         } catch (CacheException e) {
60             // try to unwrap RuntimeException thrown in ExpiringCache
61             Throwable cause = e.getCause();
62             if (cause instanceof ResponseException) {
63                 throw (ResponseException) cause;
64             }
65             if (cause instanceof IOException) {
66                 throw (IOException) cause;
67             }
68             if (cause instanceof AuthenticationException) {
69                 throw (AuthenticationException) cause;
70             }
71             throw e;
72         }
73     }
74 }