]> git.basschouten.com Git - openhab-addons.git/blob
3a09fb1c22dc5344b7aa36efe4510c52ba5dc7ce
[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.text.MessageFormat;
16 import java.util.Arrays;
17 import java.util.Set;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21
22 /**
23  * Base class for most responses that can be retrieved from the device.
24  *
25  * A prefix has to be passed in the constructor for which is checked.
26  *
27  * Subclasses have to implement parseResponseWithoutPrefix, which allows parsing without having to remove the prefix
28  * first.
29  *
30  * @author Nils Schnabel - Initial contribution
31  */
32 @NonNullByDefault
33 public abstract class PrefixedResponse<ResponseType> implements Response<ResponseType> {
34     private String prefix;
35     private @Nullable Set<ErrorCode> specifiedErrors;
36     private ResponseType result;
37
38     public PrefixedResponse(String prefix, String response) throws ResponseException {
39         this(prefix, null, response);
40     }
41
42     public PrefixedResponse(String prefix, @Nullable Set<ErrorCode> specifiedErrors, String response)
43             throws ResponseException {
44         this.prefix = prefix;
45         this.specifiedErrors = specifiedErrors;
46         this.result = parse(response);
47     }
48
49     public ResponseType getResult() {
50         return this.result;
51     }
52
53     @Override
54     public ResponseType parse(String response) throws ResponseException {
55         String fullPrefix = "%1" + this.prefix;
56         if (!response.toUpperCase().startsWith(fullPrefix)) {
57             throw new ResponseException(
58                     MessageFormat.format("Expected prefix ''{0}'' ({1}), instead got ''{2}'' ({3})", fullPrefix,
59                             Arrays.toString(fullPrefix.getBytes()), response, Arrays.toString(response.getBytes())));
60         }
61         String result = response.substring(fullPrefix.length());
62         ErrorCode.checkForErrorStatus(result, this.specifiedErrors);
63         return parseResponseWithoutPrefix(result);
64     }
65
66     protected abstract ResponseType parseResponseWithoutPrefix(String responseWithoutPrefix) throws ResponseException;
67 }