Java 17 features (H-M) (#15520)

- add missing @override
- Java style array syntax
- remove redundant modifiers
- always move String constants to left side in comparisons
- simplify lambda expressions and return statements
- use replace instead of replaceAll w/o regex
- instanceof matching and multiline strings
- remove null check before instanceof

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>
This commit is contained in:
Holger Friedrich
2023-09-08 14:36:59 +02:00
committed by GitHub
parent 3751fd0646
commit edaf17b345
519 changed files with 2703 additions and 2660 deletions

View File

@@ -394,12 +394,12 @@ public class HomematicConfig {
@Override
public String toString() {
return String.format(
"%s[gatewayAddress=%s,callbackHost=%s,xmlCallbackPort=%d,binCallbackPort=%d,"
+ "gatewayType=%s,rfPort=%d,wiredPort=%d,hmIpPort=%d,cuxdPort=%d,groupPort=%d,timeout=%d,"
+ "discoveryTimeToLive=%d,installModeDuration=%d,socketMaxAlive=%d]",
getClass().getSimpleName(), gatewayAddress, callbackHost, xmlCallbackPort, binCallbackPort, gatewayType,
getRfPort(), getWiredPort(), getHmIpPort(), getCuxdPort(), getGroupPort(), timeout, discoveryTimeToLive,
installModeDuration, socketMaxAlive);
return String.format("""
%s[gatewayAddress=%s,callbackHost=%s,xmlCallbackPort=%d,binCallbackPort=%d,\
gatewayType=%s,rfPort=%d,wiredPort=%d,hmIpPort=%d,cuxdPort=%d,groupPort=%d,timeout=%d,\
discoveryTimeToLive=%d,installModeDuration=%d,socketMaxAlive=%d]\
""", getClass().getSimpleName(), gatewayAddress, callbackHost, xmlCallbackPort, binCallbackPort,
gatewayType, getRfPort(), getWiredPort(), getHmIpPort(), getCuxdPort(), getGroupPort(), timeout,
discoveryTimeToLive, installModeDuration, socketMaxAlive);
}
}

View File

@@ -84,8 +84,7 @@ public class XmlRpcClient extends RpcClient<String> {
} catch (IOException ex) {
reason = ex;
// no retries for "init" request or if connection is refused
if ("init".equals(request.getMethodName())
|| ex.getCause() != null && ex.getCause() instanceof ExecutionException) {
if ("init".equals(request.getMethodName()) || ex.getCause() instanceof ExecutionException) {
break;
}
logger.debug("XmlRpcMessage failed({}), sending message again {}/{}", ex.getMessage(), rpcRetryCounter,

View File

@@ -47,7 +47,7 @@ public class BinRpcMessage implements RpcRequest<byte[]>, RpcResponse {
}
private Object[] messageData;
private byte binRpcData[];
private byte[] binRpcData;
private int offset;
private String methodName;
@@ -74,7 +74,7 @@ public class BinRpcMessage implements RpcRequest<byte[]>, RpcResponse {
*/
public BinRpcMessage(InputStream is, boolean methodHeader, Charset encoding) throws IOException {
this.encoding = encoding;
byte sig[] = new byte[8];
byte[] sig = new byte[8];
int length = is.read(sig, 0, 4);
if (length != 4) {
throw new EOFException("Only " + length + " bytes received reading signature");
@@ -85,7 +85,7 @@ public class BinRpcMessage implements RpcRequest<byte[]>, RpcResponse {
throw new EOFException("Only " + length + " bytes received reading message length");
}
int datasize = (new BigInteger(Arrays.copyOfRange(sig, 4, 8))).intValue();
byte payload[] = new byte[datasize];
byte[] payload = new byte[datasize];
int offset = 0;
int currentLength;
@@ -201,14 +201,14 @@ public class BinRpcMessage implements RpcRequest<byte[]>, RpcResponse {
// read rpc values
private int readInt() {
byte bi[] = new byte[4];
byte[] bi = new byte[4];
System.arraycopy(binRpcData, offset, bi, 0, 4);
offset += 4;
return (new BigInteger(bi)).intValue();
}
private long readInt64() {
byte bi[] = new byte[8];
byte[] bi = new byte[8];
System.arraycopy(binRpcData, offset, bi, 0, 8);
offset += 8;
return (new BigInteger(bi)).longValue();
@@ -274,7 +274,7 @@ public class BinRpcMessage implements RpcRequest<byte[]>, RpcResponse {
private void addByte(byte b) {
if (offset == binRpcData.length) {
byte newdata[] = new byte[binRpcData.length * 2];
byte[] newdata = new byte[binRpcData.length * 2];
System.arraycopy(binRpcData, 0, newdata, 0, binRpcData.length);
binRpcData = newdata;
}
@@ -311,7 +311,7 @@ public class BinRpcMessage implements RpcRequest<byte[]>, RpcResponse {
}
private void addString(String string) {
byte sd[] = string.getBytes(encoding);
byte[] sd = string.getBytes(encoding);
for (byte ch : sd) {
addByte(ch);
}
@@ -351,13 +351,11 @@ public class BinRpcMessage implements RpcRequest<byte[]>, RpcResponse {
} else if (object.getClass() == Date.class) {
addInt(5);
addInt((int) ((Date) object).getTime() / 1000);
} else if (object instanceof List<?>) {
Collection<?> list = (Collection<?>) object;
} else if (object instanceof List<?> list) {
addInt(0x100);
addInt(list.size());
addList(list);
} else if (object instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>) object;
} else if (object instanceof Map<?, ?> map) {
addInt(0x101);
addInt(map.size());
for (Map.Entry<?, ?> entry : map.entrySet()) {

View File

@@ -42,10 +42,10 @@ public class RpcUtils {
sb.append("[\n");
}
for (Object o : c) {
if (o instanceof Map) {
dumpMap((Map<?, ?>) o, sb, indent + 1);
} else if (o instanceof Object[]) {
dumpCollection((Object[]) o, sb, indent + 1);
if (o instanceof Map map) {
dumpMap(map, sb, indent + 1);
} else if (o instanceof Object[] objects) {
dumpCollection(objects, sb, indent + 1);
} else {
for (int in = 0; in < indent; in++) {
sb.append('\t');
@@ -76,12 +76,12 @@ public class RpcUtils {
}
sb.append(me.getKey());
sb.append('=');
if (o instanceof Map<?, ?>) {
if (o instanceof Map<?, ?> map) {
sb.append("\n");
dumpMap((Map<?, ?>) o, sb, indent + 1);
} else if (o instanceof Object[]) {
dumpMap(map, sb, indent + 1);
} else if (o instanceof Object[] objects) {
sb.append("\n");
dumpCollection((Object[]) o, sb, indent + 1);
dumpCollection(objects, sb, indent + 1);
} else {
sb.append(o);
sb.append('\n');

View File

@@ -136,16 +136,16 @@ public class XmlRpcRequest implements RpcRequest<String> {
tag("boolean", ((Boolean) value).booleanValue() ? "1" : "0");
} else if (clazz == Date.class) {
tag("dateTime.iso8601", xmlRpcDateFormat.format(((Date) value)));
} else if (value instanceof Calendar) {
generateValue(((Calendar) value).getTime());
} else if (value instanceof byte[]) {
tag("base64", Base64.getEncoder().encodeToString((byte[]) value));
} else if (value instanceof Calendar calendar) {
generateValue(calendar.getTime());
} else if (value instanceof byte[] bytes) {
tag("base64", Base64.getEncoder().encodeToString(bytes));
} else if (clazz.isArray() || value instanceof List) {
sb.append("<array><data>");
Object[] array = null;
if (value instanceof List) {
array = ((List<?>) value).toArray();
if (value instanceof List list) {
array = list.toArray();
} else {
array = (Object[]) value;
}

View File

@@ -97,10 +97,10 @@ public class XmlRpcResponse implements RpcResponse {
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
String tag = qName.toLowerCase();
if (tag.equals("array") || tag.equals("struct")) {
if ("array".equals(tag) || "struct".equals(tag)) {
currentDataObject.addLast(new ArrayList<>());
}
isValueTag = tag.equals("value");
isValueTag = "value".equals(tag);
tagValue = new StringBuilder();
}

View File

@@ -105,8 +105,7 @@ public abstract class CommonRpcParser<M, R> implements RpcParser<M, R> {
* Converts the object to a string array.
*/
protected String[] toOptionList(Object optionList) {
if (optionList != null && optionList instanceof Object[]) {
Object[] vl = (Object[]) optionList;
if (optionList != null && optionList instanceof Object[] vl) {
String[] stringArray = new String[vl.length];
for (int i = 0; i < vl.length; i++) {
stringArray[i] = vl[i].toString();
@@ -232,9 +231,9 @@ public abstract class CommonRpcParser<M, R> implements RpcParser<M, R> {
if (value == null || value.isBlank()) {
return null;
}
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on")) {
if ("true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value)) {
return (Boolean.TRUE);
} else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("off")) {
} else if ("false".equalsIgnoreCase(value) || "off".equalsIgnoreCase(value)) {
return (Boolean.FALSE);
} else if (value.matches("(-|\\+)?[0-9]+")) {
return (Integer.valueOf(value));

View File

@@ -58,7 +58,7 @@ public class GetParamsetParser extends CommonRpcParser<Object[], Void> {
// suppress warning for this datapoint due wrong CCU metadata
String deviceType = channel.getDevice().getType();
boolean isHmSenMdirNextTrans = dpInfo.getName().equals("NEXT_TRANSMISSION")
boolean isHmSenMdirNextTrans = "NEXT_TRANSMISSION".equals(dpInfo.getName())
&& (deviceType.startsWith("HM-Sen-MDIR-O") || deviceType.startsWith("HM-Sen-MDIR-WM55")
|| deviceType.startsWith("HM-Sec-MDIR-2"));
if (!isHmSenMdirNextTrans) {

View File

@@ -28,9 +28,9 @@ import org.openhab.core.common.ThreadPoolManager;
* @author Gerhard Riegler - Initial contribution
*/
public class BinRpcNetworkService implements Runnable {
private static final byte BIN_EMPTY_STRING[] = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 0, 3, 0, 0, 0, 0 };
private static final byte BIN_EMPTY_ARRAY[] = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 1, 0, 0, 0, 0, 0 };
private static final byte BIN_EMPTY_EVENT_LIST[] = { 'B', 'i', 'n', 1, 0, 0, 0, 21, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0,
private static final byte[] BIN_EMPTY_STRING = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 0, 3, 0, 0, 0, 0 };
private static final byte[] BIN_EMPTY_ARRAY = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 1, 0, 0, 0, 0, 0 };
private static final byte[] BIN_EMPTY_EVENT_LIST = { 'B', 'i', 'n', 1, 0, 0, 0, 21, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0,
3, 0, 0, 0, 5, 'e', 'v', 'e', 'n', 't' };
private static final String RPC_POOL_NAME = "homematicRpc";

View File

@@ -43,7 +43,7 @@ public class DeleteDeviceModeVirtualDatapointHandler extends AbstractVirtualData
@Override
public void initialize(HmDevice device) {
if (!device.isGatewayExtras() && !(device.getHmInterface() == HmInterface.CUXD)) {
if (!device.isGatewayExtras() && device.getHmInterface() != HmInterface.CUXD) {
HmDatapoint dp = addDatapoint(device, 0, getName(), HmValueType.ENUM, 0, false);
dp.setOptions(new String[] { MODE_LOCKED, MODE_RESET, MODE_FORCE, MODE_DEFER });
dp.setMinValue(0);

View File

@@ -44,7 +44,7 @@ public class DeleteDeviceVirtualDatapointHandler extends AbstractVirtualDatapoin
@Override
public void initialize(HmDevice device) {
if (!device.isGatewayExtras() && !(device.getHmInterface() == HmInterface.CUXD)) {
if (!device.isGatewayExtras() && device.getHmInterface() != HmInterface.CUXD) {
addDatapoint(device, 0, getName(), HmValueType.BOOL, Boolean.FALSE, false);
}
}

View File

@@ -40,8 +40,7 @@ public class DisplayOptionsVirtualDatapointHandler extends AbstractVirtualDatapo
@Override
public void initialize(HmDevice device) {
if (device.getType().startsWith(DEVICE_TYPE_19_REMOTE_CONTROL)
&& !(device.getHmInterface() == HmInterface.CUXD)) {
if (device.getType().startsWith(DEVICE_TYPE_19_REMOTE_CONTROL) && device.getHmInterface() != HmInterface.CUXD) {
addDatapoint(device, 18, getName(), HmValueType.STRING, null, false);
}
}

View File

@@ -62,8 +62,8 @@ public class OnTimeAutomaticVirtualDatapointHandler extends AbstractVirtualDatap
@Override
public boolean canHandleCommand(HmDatapoint dp, Object value) {
boolean isLevel = DATAPOINT_NAME_LEVEL.equals(dp.getName()) && value != null && value instanceof Number
&& ((Number) value).doubleValue() > 0.0;
boolean isLevel = DATAPOINT_NAME_LEVEL.equals(dp.getName()) && value != null
&& value instanceof Number numberCommand && numberCommand.doubleValue() > 0.0;
boolean isState = DATAPOINT_NAME_STATE.equals(dp.getName()) && MiscUtils.isTrueValue(value);
return ((isLevel || isState) && getVirtualDatapointValue(dp.getChannel()) > 0.0)

View File

@@ -19,7 +19,7 @@ import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketTimeoutException;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.Future;
import org.openhab.binding.homematic.internal.discovery.eq3udp.Eq3UdpRequest;
@@ -50,7 +50,7 @@ public class CcuDiscoveryService extends AbstractDiscoveryService {
private NetworkAddressService networkAddressService;
public CcuDiscoveryService() {
super(Collections.singleton(THING_TYPE_BRIDGE), 5, true);
super(Set.of(THING_TYPE_BRIDGE), 5, true);
}
@Override

View File

@@ -14,7 +14,6 @@ package org.openhab.binding.homematic.internal.discovery;
import static org.openhab.binding.homematic.internal.HomematicBindingConstants.THING_TYPE_BRIDGE;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@@ -41,7 +40,7 @@ public class HomegearDiscoveryParticipant implements UpnpDiscoveryParticipant {
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
return Collections.singleton(THING_TYPE_BRIDGE);
return Set.of(THING_TYPE_BRIDGE);
}
@Override

View File

@@ -14,7 +14,7 @@ package org.openhab.binding.homematic.internal.discovery;
import static org.openhab.binding.homematic.internal.HomematicBindingConstants.BINDING_ID;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@@ -54,13 +54,13 @@ public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService
private volatile Object installModeSync = new Object();
public HomematicDeviceDiscoveryService() {
super(Collections.singleton(new ThingTypeUID(BINDING_ID, "-")), DISCOVER_TIMEOUT_SECONDS, false);
super(Set.of(new ThingTypeUID(BINDING_ID, "-")), DISCOVER_TIMEOUT_SECONDS, false);
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof HomematicBridgeHandler) {
this.bridgeHandler = (HomematicBridgeHandler) handler;
if (handler instanceof HomematicBridgeHandler homematicBridgeHandler) {
this.bridgeHandler = homematicBridgeHandler;
this.bridgeHandler.setDiscoveryService(this);
}
}

View File

@@ -17,8 +17,8 @@ import static org.openhab.core.thing.Thing.*;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
@@ -229,7 +229,7 @@ public class HomematicBridgeHandler extends BaseBridgeHandler implements Homemat
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(HomematicDeviceDiscoveryService.class);
return Set.of(HomematicDeviceDiscoveryService.class);
}
@Override

View File

@@ -594,15 +594,14 @@ public class HomematicThingHandler extends BaseThingHandler {
if (dp != null) {
try {
if (newValue != null) {
if (newValue instanceof BigDecimal) {
final BigDecimal decimal = (BigDecimal) newValue;
if (newValue instanceof BigDecimal decimal) {
if (dp.isIntegerType()) {
newValue = decimal.intValue();
} else if (dp.isFloatType()) {
newValue = decimal.doubleValue();
}
} else if (newValue instanceof String && dp.isEnumType()) {
newValue = dp.getOptionIndex((String) newValue);
} else if (newValue instanceof String string && dp.isEnumType()) {
newValue = dp.getOptionIndex(string);
}
if (!Objects.equals(dp.getValue(), newValue)) {
sendDatapoint(dp, new HmDatapointConfig(), newValue);

View File

@@ -426,9 +426,10 @@ public class HmDatapoint implements Cloneable {
@Override
public String toString() {
return String.format("%s[name=%s,value=%s,defaultValue=%s,type=%s,minValue=%s,maxValue=%s,options=%s,"
+ "readOnly=%b,readable=%b,unit=%s,description=%s,info=%s,paramsetType=%s,virtual=%b,trigger=%b]",
getClass().getSimpleName(), name, value, defaultValue, type, minValue, maxValue,
return String.format("""
%s[name=%s,value=%s,defaultValue=%s,type=%s,minValue=%s,maxValue=%s,options=%s,\
readOnly=%b,readable=%b,unit=%s,description=%s,info=%s,paramsetType=%s,virtual=%b,trigger=%b]\
""", getClass().getSimpleName(), name, value, defaultValue, type, minValue, maxValue,
(options == null ? null : String.join(";", options)), readOnly, readable, unit, description, info,
paramsetType, virtual, trigger);
}

View File

@@ -96,7 +96,7 @@ public class HmDatapointInfo {
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof HmDatapointInfo)) {
if (!(obj instanceof HmDatapointInfo)) {
return false;
}
HmDatapointInfo comp = (HmDatapointInfo) obj;

View File

@@ -213,7 +213,7 @@ public class HmDevice {
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof HmDevice)) {
if (!(obj instanceof HmDevice)) {
return false;
}
HmDevice comp = (HmDevice) obj;

View File

@@ -189,11 +189,11 @@ public class HomematicTypeGeneratorImpl implements HomematicTypeGenerator {
for (String deviceType : firmwaresByType.keySet()) {
Set<String> firmwares = firmwaresByType.get(deviceType);
if (firmwares.size() > 1) {
logger.info(
"Multiple firmware versions for device type '{}' found ({}). "
+ "Make sure, all devices of the same type have the same firmware version, "
+ "otherwise you MAY have channel and/or datapoint errors in the logfile",
deviceType, String.join(", ", firmwares));
logger.info("""
Multiple firmware versions for device type '{}' found ({}). \
Make sure, all devices of the same type have the same firmware version, \
otherwise you MAY have channel and/or datapoint errors in the logfile\
""", deviceType, String.join(", ", firmwares));
}
}
}
@@ -387,7 +387,7 @@ public class HomematicTypeGeneratorImpl implements HomematicTypeGenerator {
*/
public static boolean isIgnoredDatapoint(HmDatapoint dp) {
for (String testValue : IGNORE_DATAPOINT_NAMES) {
if (dp.getName().indexOf(testValue) > -1) {
if (dp.getName().contains(testValue)) {
return true;
}
}