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

@@ -78,8 +78,8 @@ public class ThingsTemplateGenerator {
private String getLocale(Bridge bridge) {
var locale = bridge.getConfiguration().get(MieleCloudBindingConstants.CONFIG_PARAM_LOCALE);
if (locale instanceof String) {
return (String) locale;
if (locale instanceof String str) {
return str;
} else {
return "en";
}

View File

@@ -171,10 +171,13 @@ public final class AccountOverviewServlet extends AbstractShowPageServlet {
private String renderSslWarning(HttpServletRequest request, String skeleton) {
if (!request.isSecure()) {
return skeleton.replace(NO_SSL_WARNING_PLACEHOLDER, "<div class=\"alert alert-danger\" role=\"alert\">\n"
+ " Warning: We strongly advice to proceed only with SSL enabled for a secure data exchange.\n"
+ " See <a href=\"https://www.openhab.org/docs/installation/security.html\">Securing access to openHAB</a> for details.\n"
+ " </div>");
return skeleton.replace(NO_SSL_WARNING_PLACEHOLDER,
"""
<div class="alert alert-danger" role="alert">
Warning: We strongly advice to proceed only with SSL enabled for a secure data exchange.
See <a href="https://www.openhab.org/docs/installation/security.html">Securing access to openHAB</a> for details.
</div>\
""");
} else {
return skeleton.replace(NO_SSL_WARNING_PLACEHOLDER, "");
}

View File

@@ -200,8 +200,7 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements D
@Override
public void setThingHandler(ThingHandler handler) {
if (handler instanceof MieleBridgeHandler) {
var bridgeHandler = (MieleBridgeHandler) handler;
if (handler instanceof MieleBridgeHandler bridgeHandler) {
bridgeHandler.setDiscoveryService(this);
this.bridgeHandler = bridgeHandler;
}

View File

@@ -82,10 +82,10 @@ public final class ThingInformationExtractor {
if (deviceType.isPresent() && techType.isPresent()) {
return Optional.of(deviceType.get() + " " + techType.get());
}
if (!deviceType.isPresent() && techType.isPresent()) {
if (deviceType.isEmpty() && techType.isPresent()) {
return techType;
}
if (deviceType.isPresent() && !techType.isPresent()) {
if (deviceType.isPresent() && techType.isEmpty()) {
return deviceType;
}
return Optional.empty();

View File

@@ -80,7 +80,7 @@ public abstract class AbstractMieleThingHandler extends BaseThingHandler {
}
BridgeHandler handler = bridge.getHandler();
if (handler == null || !(handler instanceof MieleBridgeHandler)) {
if (!(handler instanceof MieleBridgeHandler)) {
return Optional.empty();
}

View File

@@ -13,8 +13,8 @@
package org.openhab.binding.mielecloud.internal.handler;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
@@ -230,7 +230,7 @@ public class MieleBridgeHandler extends BaseBridgeHandler
private void tryInitializeWebservice() {
Optional<String> accessToken = tokenRefresher.getAccessTokenFromStorage(getOAuthServiceHandle());
if (!accessToken.isPresent()) {
if (accessToken.isEmpty()) {
logger.debug("No OAuth2 access token available. Retrying later.");
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
I18NKeys.BRIDGE_STATUS_DESCRIPTION_ACCESS_TOKEN_NOT_CONFIGURED);
@@ -301,8 +301,7 @@ public class MieleBridgeHandler extends BaseBridgeHandler
@Override
public Optional<String> getLanguage() {
Object languageObject = thing.getConfiguration().get(MieleCloudBindingConstants.CONFIG_PARAM_LOCALE);
if (languageObject instanceof String) {
String language = (String) languageObject;
if (languageObject instanceof String language) {
if (language.isEmpty() || !LocaleValidator.isValidLanguage(language)) {
return Optional.empty();
} else {
@@ -348,6 +347,6 @@ public class MieleBridgeHandler extends BaseBridgeHandler
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(ThingDiscoveryService.class);
return Set.of(ThingDiscoveryService.class);
}
}

View File

@@ -46,7 +46,7 @@ public final class ChannelTypeUtil {
* Converts an {@link Optional} of {@link String} to {@link State}.
*/
public static State stringToState(Optional<String> value) {
return value.filter(v -> !v.isEmpty()).filter(v -> !v.equals("null")).map(v -> (State) new StringType(v))
return value.filter(v -> !v.isEmpty()).filter(v -> !"null".equals(v)).map(v -> (State) new StringType(v))
.orElse(UnDefType.UNDEF);
}

View File

@@ -132,7 +132,7 @@ public final class DefaultMieleWebservice implements MieleWebservice, SseListene
@Nullable
private Request createSseRequest(String endpoint) {
Optional<String> accessToken = this.accessToken;
if (!accessToken.isPresent()) {
if (accessToken.isEmpty()) {
logger.warn("No access token present.");
return null;
}
@@ -243,7 +243,7 @@ public final class DefaultMieleWebservice implements MieleWebservice, SseListene
@Override
public void logout() {
Optional<String> accessToken = this.accessToken;
if (!accessToken.isPresent()) {
if (accessToken.isEmpty()) {
logger.debug("No access token present.");
return;
}
@@ -301,7 +301,7 @@ public final class DefaultMieleWebservice implements MieleWebservice, SseListene
*/
private Actions getActions(String deviceId) {
Optional<String> accessToken = this.accessToken;
if (!accessToken.isPresent()) {
if (accessToken.isEmpty()) {
throw new MieleWebserviceException("Missing access token.", ConnectionError.AUTHORIZATION_FAILED);
}
@@ -337,7 +337,7 @@ public final class DefaultMieleWebservice implements MieleWebservice, SseListene
private void putActions(String deviceId, String json) {
retryStrategy.performRetryableOperation(() -> {
Optional<String> accessToken = this.accessToken;
if (!accessToken.isPresent()) {
if (accessToken.isEmpty()) {
throw new MieleWebserviceException("Missing access token.", ConnectionError.AUTHORIZATION_FAILED);
}

View File

@@ -81,9 +81,9 @@ public final class HttpUtil {
private static String getHttpErrorMessageFromCloudResponse(Response response) {
String exceptionMessage = "HTTP error " + response.getStatus() + ": " + response.getReason();
if (response instanceof ContentResponse) {
if (response instanceof ContentResponse contentResponse) {
try {
ErrorMessage errorMessage = ErrorMessage.fromJson(((ContentResponse) response).getContentAsString());
ErrorMessage errorMessage = ErrorMessage.fromJson(contentResponse.getContentAsString());
exceptionMessage += "\nCloud returned message: " + errorMessage.getMessage();
} catch (MieleSyntaxException e) {
exceptionMessage += "\nCloud returned invalid message.";

View File

@@ -181,7 +181,7 @@ public class DeviceState {
Optional<Integer> targetTemperature = getTargetTemperature(0);
Optional<Integer> currentTemperature = getTemperature(0);
if (!targetTemperature.isPresent() || !currentTemperature.isPresent()) {
if (targetTemperature.isEmpty() || currentTemperature.isEmpty()) {
return Optional.empty();
}
@@ -452,7 +452,7 @@ public class DeviceState {
Optional<Boolean> doorState = getDoorState();
Optional<Boolean> failure = device.flatMap(Device::getState).flatMap(State::getSignalFailure);
if (!doorState.isPresent() || !failure.isPresent()) {
if (doorState.isEmpty() || failure.isEmpty()) {
return Optional.empty();
}

View File

@@ -86,7 +86,7 @@ public class TransitionState {
}
private Optional<Boolean> hasFinishedFromPreviousState(DeviceState prevState) {
if (!prevState.getStateType().isPresent()) {
if (prevState.getStateType().isEmpty()) {
return Optional.empty();
}

View File

@@ -71,7 +71,7 @@ public class AuthorizationFailedRetryStrategy implements RetryStrategy {
} catch (MieleWebserviceException e) {
// Workaround for HTML response from cloud in case of a 401 HTTP error.
var cause = e.getCause();
if (cause == null || !(cause instanceof ExecutionException)) {
if (!(cause instanceof ExecutionException)) {
throw e;
}

View File

@@ -18,6 +18,7 @@ import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@@ -138,7 +139,7 @@ public class ThingsTemplateGeneratorTest {
when(discoveryResult.getThingTypeUID()).thenReturn(thingTypeUid);
when(discoveryResult.getThingUID()).thenReturn(new ThingUID(thingTypeUid, id, bridgeId));
when(discoveryResult.getProperties())
.thenReturn(Collections.singletonMap(MieleCloudBindingConstants.CONFIG_PARAM_DEVICE_IDENTIFIER, id));
.thenReturn(Map.of(MieleCloudBindingConstants.CONFIG_PARAM_DEVICE_IDENTIFIER, id));
return discoveryResult;
}
@@ -177,9 +178,12 @@ public class ThingsTemplateGeneratorTest {
Collections.emptyList());
// then:
assertEquals("Bridge mielecloud:account:mielebridge [ email=\"everyone@openhab.org\", locale=\"de\" ] {\n"
+ " Thing oven 000137439123 \"Oven H7860XY\" [ deviceIdentifier=\"000137439123\" ]\n"
+ " Thing hob 000160106123 [ deviceIdentifier=\"000160106123\" ]\n}", template);
assertEquals("""
Bridge mielecloud:account:mielebridge [ email="everyone@openhab.org", locale="de" ] {
Thing oven 000137439123 "Oven H7860XY" [ deviceIdentifier="000137439123" ]
Thing hob 000160106123 [ deviceIdentifier="000160106123" ]
}\
""", template);
}
@Test
@@ -203,10 +207,12 @@ public class ThingsTemplateGeneratorTest {
discoveredThings);
// then:
assertEquals("Bridge mielecloud:account:mielebridge [ email=\"everyone@openhab.org\", locale=\"de\" ] {\n"
+ " Thing fridge_freezer 000154106123 \"Fridge-Freezer Kitchen\" [ deviceIdentifier=\"000154106123\" ]\n"
+ " Thing washing_machine 000189106123 \"Washing Machine\" [ deviceIdentifier=\"000189106123\" ]\n}",
template);
assertEquals("""
Bridge mielecloud:account:mielebridge [ email="everyone@openhab.org", locale="de" ] {
Thing fridge_freezer 000154106123 "Fridge-Freezer Kitchen" [ deviceIdentifier="000154106123" ]
Thing washing_machine 000189106123 "Washing Machine" [ deviceIdentifier="000189106123" ]
}\
""", template);
}
@Test
@@ -237,12 +243,14 @@ public class ThingsTemplateGeneratorTest {
discoveredThings);
// then:
assertEquals("Bridge mielecloud:account:mielebridge [ email=\"openhab@openhab.org\", locale=\"de\" ] {\n"
+ " Thing oven 000137439123 \"Oven H7860XY\" [ deviceIdentifier=\"000137439123\" ]\n"
+ " Thing hob 000160106123 [ deviceIdentifier=\"000160106123\" ]\n"
+ " Thing fridge_freezer 000154106123 \"Fridge-Freezer Kitchen\" [ deviceIdentifier=\"000154106123\" ]\n"
+ " Thing washing_machine 000189106123 \"Washing Machine\" [ deviceIdentifier=\"000189106123\" ]\n}",
template);
assertEquals("""
Bridge mielecloud:account:mielebridge [ email="openhab@openhab.org", locale="de" ] {
Thing oven 000137439123 "Oven H7860XY" [ deviceIdentifier="000137439123" ]
Thing hob 000160106123 [ deviceIdentifier="000160106123" ]
Thing fridge_freezer 000154106123 "Fridge-Freezer Kitchen" [ deviceIdentifier="000154106123" ]
Thing washing_machine 000189106123 "Washing Machine" [ deviceIdentifier="000189106123" ]
}\
""", template);
}
@Test

View File

@@ -398,7 +398,6 @@ public class DefaultMieleWebserviceTest {
try (DefaultMieleWebservice webservice = new DefaultMieleWebservice(requestFactory, retryStrategy,
new DeviceStateDispatcher(), scheduler)) {
// when:
assertThrows(IllegalArgumentException.class, () -> {
webservice.putProcessAction(DEVICE_IDENTIFIER, ProcessAction.UNKNOWN);

View File

@@ -125,7 +125,7 @@ public class ActionsStateTest {
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.START));
when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.START));
// when:
boolean canBeStarted = actionState.canBeStarted();
@@ -141,7 +141,7 @@ public class ActionsStateTest {
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.STOP));
when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.STOP));
// when:
boolean canBeStarted = actionState.canBeStarted();
@@ -173,7 +173,7 @@ public class ActionsStateTest {
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.START_SUPERCOOLING));
when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.START_SUPERCOOLING));
// when:
boolean canStartSupercooling = actionState.canStartSupercooling();
@@ -189,7 +189,7 @@ public class ActionsStateTest {
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.START_SUPERFREEZING));
when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.START_SUPERFREEZING));
// when:
boolean canStartSuperfreezing = actionState.canStartSuperfreezing();
@@ -205,7 +205,7 @@ public class ActionsStateTest {
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
when(actions.getLight()).thenReturn(Collections.singletonList(Light.ENABLE));
when(actions.getLight()).thenReturn(List.of(Light.ENABLE));
// when:
boolean canEnableLight = actionState.canEnableLight();
@@ -219,7 +219,7 @@ public class ActionsStateTest {
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
when(actions.getLight()).thenReturn(Collections.singletonList(Light.DISABLE));
when(actions.getLight()).thenReturn(List.of(Light.DISABLE));
// when:
boolean canDisableLight = actionState.canDisableLight();
@@ -232,7 +232,7 @@ public class ActionsStateTest {
public void testCanControlLightReturnsTrueWhenLightCanBeEnabled() {
// given:
Actions actions = mock(Actions.class);
when(actions.getLight()).thenReturn(Collections.singletonList(Light.ENABLE));
when(actions.getLight()).thenReturn(List.of(Light.ENABLE));
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
@@ -247,7 +247,7 @@ public class ActionsStateTest {
public void testCanControlLightReturnsTrueWhenLightCanBeDisabled() {
// given:
Actions actions = mock(Actions.class);
when(actions.getLight()).thenReturn(Collections.singletonList(Light.DISABLE));
when(actions.getLight()).thenReturn(List.of(Light.DISABLE));
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
@@ -307,7 +307,7 @@ public class ActionsStateTest {
public void testProgramIdCanBeSetWhenProgramIdIsPresent() {
// given:
Actions actions = mock(Actions.class);
when(actions.getProgramId()).thenReturn(Collections.singletonList(1));
when(actions.getProgramId()).thenReturn(List.of(1));
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);

View File

@@ -18,6 +18,7 @@ import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault;
@@ -851,7 +852,7 @@ public class DeviceStateTest {
when(plateStepMock.getValueLocalized()).thenReturn(Optional.empty());
State state = mock(State.class);
when(state.getPlateStep()).thenReturn(Collections.singletonList(plateStepMock));
when(state.getPlateStep()).thenReturn(List.of(plateStepMock));
when(state.getStatus()).thenReturn(Optional.of(status));
Device device = mock(Device.class);
@@ -1111,7 +1112,7 @@ public class DeviceStateTest {
State state = mock(State.class);
when(state.getStatus()).thenReturn(Optional.of(status));
when(state.getElapsedTime()).thenReturn(Optional.of(Collections.singletonList(2)));
when(state.getElapsedTime()).thenReturn(Optional.of(List.of(2)));
Device device = mock(Device.class);
when(device.getState()).thenReturn(Optional.of(state));
@@ -1866,7 +1867,7 @@ public class DeviceStateTest {
// Test TargetTemperature:
Temperature targetTemperatureMock = mock(Temperature.class);
when(state.getTargetTemperature()).thenReturn(Collections.singletonList(targetTemperatureMock));
when(state.getTargetTemperature()).thenReturn(List.of(targetTemperatureMock));
when(targetTemperatureMock.getValueLocalized()).thenReturn(Optional.of(200));
// when:
Optional<Integer> targetTemperature = deviceState.getTargetTemperature(0);
@@ -1875,7 +1876,7 @@ public class DeviceStateTest {
// Test Temperature:
Temperature temperature = mock(Temperature.class);
when(state.getTemperature()).thenReturn(Collections.singletonList(temperature));
when(state.getTemperature()).thenReturn(List.of(temperature));
when(temperature.getValueLocalized()).thenReturn(Optional.of(200));
// when:
Optional<Integer> t = deviceState.getTemperature(0);

View File

@@ -16,9 +16,9 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.openhab.binding.mielecloud.internal.util.ResourceUtil.getResourceAsString;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
@@ -38,13 +38,13 @@ public class ActionsCollectionTest {
ActionsCollection collection = ActionsCollection.fromJson(json);
// then:
assertEquals(Collections.singleton("000123456789"), collection.getDeviceIdentifiers());
assertEquals(Set.of("000123456789"), collection.getDeviceIdentifiers());
Actions actions = collection.getActions("000123456789");
assertEquals(List.of(ProcessAction.START, ProcessAction.STOP), actions.getProcessAction());
assertEquals(Collections.singletonList(Light.DISABLE), actions.getLight());
assertEquals(List.of(Light.DISABLE), actions.getLight());
assertEquals(Optional.empty(), actions.getStartTime());
assertEquals(Collections.singletonList(123), actions.getProgramId());
assertEquals(List.of(123), actions.getProgramId());
assertEquals(Optional.of(true), actions.getPowerOn());
assertEquals(Optional.of(false), actions.getPowerOff());
}
@@ -69,6 +69,6 @@ public class ActionsCollectionTest {
DeviceCollection collection = DeviceCollection.fromJson(json);
// then:
assertEquals(Collections.singleton("mac-00124B000AE539D6"), collection.getDeviceIdentifiers());
assertEquals(Set.of("mac-00124B000AE539D6"), collection.getDeviceIdentifiers());
}
}

View File

@@ -16,7 +16,6 @@ import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
@@ -112,7 +111,7 @@ public class ActionsTest {
Actions actions = new Gson().fromJson(json, Actions.class);
// then:
assertEquals(Collections.singletonList(ProcessAction.START), actions.getProcessAction());
assertEquals(List.of(ProcessAction.START), actions.getProcessAction());
}
@Test