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.binding.pjlinkdevice.internal.device.command;
15 import java.io.IOException;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.core.cache.ExpiringCache;
22 * CachedCommand wraps any command and caches its response for a configurable period of time.
24 * @author Nils Schnabel - Initial contribution
27 public class CachedCommand<ResponseType extends Response<?>> implements Command<ResponseType> {
29 private Command<ResponseType> cachedCommand;
30 private ExpiringCache<ResponseType> cache;
32 public CachedCommand(Command<ResponseType> cachedCommand) {
33 this(cachedCommand, 1000);
36 public CachedCommand(Command<ResponseType> cachedCommand, int expiry) {
37 this.cachedCommand = cachedCommand;
38 this.cache = new ExpiringCache<>(expiry, () -> {
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);
49 public ResponseType execute() throws ResponseException, IOException, AuthenticationException {
50 ExpiringCache<ResponseType> cache = this.cache;
53 ResponseType result = cache.getValue();
55 // this can not happen in reality, limitation of ExpiringCache
56 throw new ResponseException("Cached value is null");
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;
65 if (cause instanceof IOException) {
66 throw (IOException) cause;
68 if (cause instanceof AuthenticationException) {
69 throw (AuthenticationException) cause;