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.text.MessageFormat;
16 import java.util.Arrays;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
23 * Base class for most responses that can be retrieved from the device.
25 * A prefix has to be passed in the constructor for which is checked.
27 * Subclasses have to implement parseResponseWithoutPrefix, which allows parsing without having to remove the prefix
30 * @author Nils Schnabel - Initial contribution
33 public abstract class PrefixedResponse<ResponseType> implements Response<ResponseType> {
34 private String prefix;
35 private @Nullable Set<ErrorCode> specifiedErrors;
36 private ResponseType result;
38 public PrefixedResponse(String prefix, String response) throws ResponseException {
39 this(prefix, null, response);
42 public PrefixedResponse(String prefix, @Nullable Set<ErrorCode> specifiedErrors, String response)
43 throws ResponseException {
45 this.specifiedErrors = specifiedErrors;
46 this.result = parse(response);
49 public ResponseType getResult() {
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())));
61 String result = response.substring(fullPrefix.length());
62 ErrorCode.checkForErrorStatus(result, this.specifiedErrors);
63 return parseResponseWithoutPrefix(result);
66 protected abstract ResponseType parseResponseWithoutPrefix(String responseWithoutPrefix) throws ResponseException;