import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
-import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.mqtt.generic.values.OnOffValue;
}
@Override
- public void removeAvailabilityTopic(@NonNull String availability_topic) {
- availabilityStates.computeIfPresent(availability_topic, (topic, state) -> {
+ public void removeAvailabilityTopic(String availabilityTopic) {
+ availabilityStates.computeIfPresent(availabilityTopic, (topic, state) -> {
if (connection != null && state != null) {
state.stop();
}
*/
package org.openhab.binding.mqtt.generic.mapping;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+
/**
* Color modes supported by the binding.
*
* @author Aitor Iturrioz - Initial contribution
*/
+@NonNullByDefault
public enum ColorMode {
HSB,
RGB,
String typeName = type.getSimpleName();
if (value instanceof BigDecimal && !type.equals(BigDecimal.class)) {
BigDecimal bdValue = (BigDecimal) value;
- if (type.equals(Float.class) || typeName.equals("float")) {
+ if (type.equals(Float.class) || "float".equals(typeName)) {
result = bdValue.floatValue();
- } else if (type.equals(Double.class) || typeName.equals("double")) {
+ } else if (type.equals(Double.class) || "double".equals(typeName)) {
result = bdValue.doubleValue();
- } else if (type.equals(Long.class) || typeName.equals("long")) {
+ } else if (type.equals(Long.class) || "long".equals(typeName)) {
result = bdValue.longValue();
- } else if (type.equals(Integer.class) || typeName.equals("int")) {
+ } else if (type.equals(Integer.class) || "int".equals(typeName)) {
result = bdValue.intValue();
}
} else
// primitive types
if (value instanceof String && !type.equals(String.class)) {
String bdValue = (String) value;
- if (type.equals(Float.class) || typeName.equals("float")) {
+ if (type.equals(Float.class) || "float".equals(typeName)) {
result = Float.valueOf(bdValue);
- } else if (type.equals(Double.class) || typeName.equals("double")) {
+ } else if (type.equals(Double.class) || "double".equals(typeName)) {
result = Double.valueOf(bdValue);
- } else if (type.equals(Long.class) || typeName.equals("long")) {
+ } else if (type.equals(Long.class) || "long".equals(typeName)) {
result = Long.valueOf(bdValue);
} else if (type.equals(BigDecimal.class)) {
result = new BigDecimal(bdValue);
- } else if (type.equals(Integer.class) || typeName.equals("int")) {
+ } else if (type.equals(Integer.class) || "int".equals(typeName)) {
result = Integer.valueOf(bdValue);
- } else if (type.equals(Boolean.class) || typeName.equals("boolean")) {
+ } else if (type.equals(Boolean.class) || "boolean".equals(typeName)) {
result = Boolean.valueOf(bdValue);
} else if (type.isEnum()) {
@SuppressWarnings({ "rawtypes", "unchecked" })
import java.util.function.Supplier;
import java.util.stream.Collector;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+
/**
* Collector to combine a stream of CompletableFutures.
*
* @author Jochen Klein - Initial contribution
*
*/
+@NonNullByDefault
public class FutureCollector {
- public static <X> Collector<CompletableFuture<X>, Set<CompletableFuture<X>>, CompletableFuture<Void>> allOf() {
- return Collector.<CompletableFuture<X>, Set<CompletableFuture<X>>, CompletableFuture<Void>> of(
+ public static <X> Collector<CompletableFuture<X>, Set<CompletableFuture<X>>, CompletableFuture<@Nullable Void>> allOf() {
+ return Collector.<CompletableFuture<X>, Set<CompletableFuture<X>>, CompletableFuture<@Nullable Void>> of(
(Supplier<Set<CompletableFuture<X>>>) HashSet::new, Set::add, (left, right) -> {
left.addAll(right);
return left;
- }, a -> {
- return CompletableFuture.allOf(a.toArray(new CompletableFuture[a.size()]));
- }, Collector.Characteristics.UNORDERED);
+ }, a -> CompletableFuture.allOf(a.toArray(new CompletableFuture[a.size()])),
+ Collector.Characteristics.UNORDERED);
}
}
package org.openhab.binding.mqtt.generic.values;
import java.math.BigDecimal;
+import java.util.List;
import java.util.Locale;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
import javax.ws.rs.NotSupportedException;
* @param onBrightness When receiving a ON command, the brightness percentage is set to this value
*/
public ColorValue(ColorMode colorMode, @Nullable String onValue, @Nullable String offValue, int onBrightness) {
- super(CoreItemFactory.COLOR,
- Stream.of(OnOffType.class, PercentType.class, StringType.class).collect(Collectors.toList()));
+ super(CoreItemFactory.COLOR, List.of(OnOffType.class, PercentType.class, StringType.class));
if (onBrightness > 100) {
throw new IllegalArgumentException("Brightness parameter must be <= 100");
Integer.parseInt(split[2]));
break;
case XYY:
- HSBType temp_state = HSBType.fromXY(Float.parseFloat(split[0]), Float.parseFloat(split[1]));
- state = new HSBType(temp_state.getHue(), temp_state.getSaturation(), new PercentType(split[2]));
+ HSBType tempState = HSBType.fromXY(Float.parseFloat(split[0]), Float.parseFloat(split[1]));
+ state = new HSBType(tempState.getHue(), tempState.getSaturation(), new PercentType(split[2]));
break;
default:
logger.warn("Non supported color mode");
}
}
- HSBType hsb_state = (HSBType) state;
+ HSBType hsbState = (HSBType) state;
switch (this.colorMode) {
case HSB:
- return String.format(formatPattern, hsb_state.getHue().intValue(), hsb_state.getSaturation().intValue(),
- hsb_state.getBrightness().intValue());
+ return String.format(formatPattern, hsbState.getHue().intValue(), hsbState.getSaturation().intValue(),
+ hsbState.getBrightness().intValue());
case RGB:
- PercentType[] rgb = hsb_state.toRGB();
+ PercentType[] rgb = hsbState.toRGB();
return String.format(formatPattern, rgb[0].toBigDecimal().multiply(factor).intValue(),
rgb[1].toBigDecimal().multiply(factor).intValue(),
rgb[2].toBigDecimal().multiply(factor).intValue());
case XYY:
- PercentType[] xyY = hsb_state.toXY();
+ PercentType[] xyY = hsbState.toXY();
return String.format(Locale.ROOT, formatPattern, xyY[0].floatValue() / 100.0f,
- xyY[1].floatValue() / 100.0f, hsb_state.getBrightness().floatValue());
+ xyY[1].floatValue() / 100.0f, hsbState.getBrightness().floatValue());
default:
throw new NotSupportedException(String.format("Non supported color mode: {}", this.colorMode));
}
package org.openhab.binding.mqtt.generic.values;
import java.time.format.DateTimeFormatter;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
+import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@NonNullByDefault
public class DateTimeValue extends Value {
public DateTimeValue() {
- super(CoreItemFactory.DATETIME, Stream.of(DateTimeType.class, StringType.class).collect(Collectors.toList()));
+ super(CoreItemFactory.DATETIME, List.of(DateTimeType.class, StringType.class));
}
@Override
*/
package org.openhab.binding.mqtt.generic.values;
-import java.util.Collections;
+import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.library.CoreItemFactory;
@NonNullByDefault
public class ImageValue extends Value {
public ImageValue() {
- super(CoreItemFactory.IMAGE, Collections.emptyList());
+ super(CoreItemFactory.IMAGE, List.of());
}
@Override
package org.openhab.binding.mqtt.generic.values;
import java.math.BigDecimal;
+import java.util.List;
import java.util.Locale;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.library.CoreItemFactory;
@NonNullByDefault
public class LocationValue extends Value {
public LocationValue() {
- super(CoreItemFactory.LOCATION, Stream.of(PointType.class, StringType.class).collect(Collectors.toList()));
+ super(CoreItemFactory.LOCATION, List.of(PointType.class, StringType.class));
}
@Override
- public @NonNull String getMQTTpublishValue(@Nullable String pattern) {
+ public String getMQTTpublishValue(@Nullable String pattern) {
String formatPattern = pattern;
PointType point = ((PointType) state);
package org.openhab.binding.mqtt.generic.values;
import java.math.BigDecimal;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
+import java.util.List;
import javax.measure.Unit;
public NumberValue(@Nullable BigDecimal min, @Nullable BigDecimal max, @Nullable BigDecimal step,
@Nullable Unit<?> unit) {
- super(CoreItemFactory.NUMBER, Stream.of(QuantityType.class, IncreaseDecreaseType.class, UpDownType.class)
- .collect(Collectors.toList()));
+ super(CoreItemFactory.NUMBER, List.of(QuantityType.class, IncreaseDecreaseType.class, UpDownType.class));
this.min = min;
this.max = max;
this.step = step == null ? BigDecimal.ONE : step;
*/
package org.openhab.binding.mqtt.generic.values;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
+import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
*/
public OnOffValue(@Nullable String onState, @Nullable String offState, @Nullable String onCommand,
@Nullable String offCommand) {
- super(CoreItemFactory.SWITCH, Stream.of(OnOffType.class, StringType.class).collect(Collectors.toList()));
+ super(CoreItemFactory.SWITCH, List.of(OnOffType.class, StringType.class));
this.onState = onState == null ? OnOffType.ON.name() : onState;
this.offState = offState == null ? OnOffType.OFF.name() : offState;
this.onCommand = onCommand == null ? OnOffType.ON.name() : onCommand;
*/
package org.openhab.binding.mqtt.generic.values;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
+import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
* Creates a contact Open/Close type.
*/
public OpenCloseValue() {
- super(CoreItemFactory.CONTACT, Stream.of(OpenClosedType.class, StringType.class).collect(Collectors.toList()));
+ super(CoreItemFactory.CONTACT, List.of(OpenClosedType.class, StringType.class));
this.openString = OpenClosedType.OPEN.name();
this.closeString = OpenClosedType.CLOSED.name();
}
* @param closeValue The OFF value string. This will be compared to MQTT messages.
*/
public OpenCloseValue(@Nullable String openValue, @Nullable String closeValue) {
- super(CoreItemFactory.CONTACT, Stream.of(OpenClosedType.class, StringType.class).collect(Collectors.toList()));
+ super(CoreItemFactory.CONTACT, List.of(OpenClosedType.class, StringType.class));
this.openString = openValue == null ? OpenClosedType.OPEN.name() : openValue;
this.closeString = closeValue == null ? OpenClosedType.CLOSED.name() : closeValue;
}
import java.math.BigDecimal;
import java.math.MathContext;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
+import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
public PercentageValue(@Nullable BigDecimal min, @Nullable BigDecimal max, @Nullable BigDecimal step,
@Nullable String onValue, @Nullable String offValue) {
- super(CoreItemFactory.DIMMER, Stream.of(DecimalType.class, QuantityType.class, IncreaseDecreaseType.class,
- OnOffType.class, UpDownType.class, StringType.class).collect(Collectors.toList()));
+ super(CoreItemFactory.DIMMER, List.of(DecimalType.class, QuantityType.class, IncreaseDecreaseType.class,
+ OnOffType.class, UpDownType.class, StringType.class));
this.onValue = onValue;
this.offValue = offValue;
this.min = min == null ? BigDecimal.ZERO : min;
*/
package org.openhab.binding.mqtt.generic.values;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
+import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
*/
public RollershutterValue(@Nullable String upString, @Nullable String downString, @Nullable String stopString) {
super(CoreItemFactory.ROLLERSHUTTER,
- Stream.of(UpDownType.class, StopMoveType.class, PercentType.class, StringType.class)
- .collect(Collectors.toList()));
+ List.of(UpDownType.class, StopMoveType.class, PercentType.class, StringType.class));
this.upString = upString;
this.downString = downString;
this.stopString = stopString == null ? StopMoveType.STOP.name() : stopString;
import static java.util.function.Predicate.not;
-import java.util.Collections;
+import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
* will be allowed.
*/
public TextValue(String[] states) {
- super(CoreItemFactory.STRING, Collections.singletonList(StringType.class));
+ super(CoreItemFactory.STRING, List.of(StringType.class));
Set<String> s = Stream.of(states).filter(not(String::isBlank)).collect(Collectors.toSet());
if (!s.isEmpty()) {
this.states = s;
}
public TextValue() {
- super(CoreItemFactory.STRING, Collections.singletonList(StringType.class));
+ super(CoreItemFactory.STRING, List.of(StringType.class));
this.states = null;
}
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
+@NonNullByDefault
public class ChannelStateTests {
- private @Mock MqttBrokerConnection connection;
- private @Mock ChannelStateUpdateListener channelStateUpdateListener;
- private @Mock ChannelUID channelUID;
- private @Spy TextValue textValue;
+ private @Mock @NonNullByDefault({}) MqttBrokerConnection connectionMock;
+ private @Mock @NonNullByDefault({}) ChannelStateUpdateListener channelStateUpdateListenerMock;
+ private @Mock @NonNullByDefault({}) ChannelUID channelUIDMock;
+ private @Spy @NonNullByDefault({}) TextValue textValue;
- private ScheduledExecutorService scheduler;
+ private @NonNullByDefault({}) ScheduledExecutorService scheduler;
private ChannelConfig config = ChannelConfigBuilder.create("state", "command").build();
@BeforeEach
public void setUp() {
- CompletableFuture<Void> voidFutureComplete = new CompletableFuture<>();
+ CompletableFuture<@Nullable Void> voidFutureComplete = new CompletableFuture<>();
voidFutureComplete.complete(null);
- doReturn(voidFutureComplete).when(connection).unsubscribeAll();
- doReturn(CompletableFuture.completedFuture(true)).when(connection).subscribe(any(), any());
- doReturn(CompletableFuture.completedFuture(true)).when(connection).unsubscribe(any(), any());
- doReturn(CompletableFuture.completedFuture(true)).when(connection).publish(any(), any(), anyInt(),
+ doReturn(voidFutureComplete).when(connectionMock).unsubscribeAll();
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).subscribe(any(), any());
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).unsubscribe(any(), any());
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).publish(any(), any(), anyInt(),
anyBoolean());
scheduler = new ScheduledThreadPoolExecutor(1);
}
@Test
- public void noInteractionTimeoutTest() throws InterruptedException, ExecutionException, TimeoutException {
- ChannelState c = spy(new ChannelState(config, channelUID, textValue, channelStateUpdateListener));
- c.start(connection, scheduler, 50).get(100, TimeUnit.MILLISECONDS);
- verify(connection).subscribe(eq("state"), eq(c));
+ public void noInteractionTimeoutTest() throws Exception {
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, textValue, channelStateUpdateListenerMock));
+ c.start(connectionMock, scheduler, 50).get(100, TimeUnit.MILLISECONDS);
+ verify(connectionMock).subscribe(eq("state"), eq(c));
c.stop().get();
- verify(connection).unsubscribe(eq("state"), eq(c));
+ verify(connectionMock).unsubscribe(eq("state"), eq(c));
}
@Test
- public void publishFormatTest() throws InterruptedException, ExecutionException, TimeoutException {
- ChannelState c = spy(new ChannelState(config, channelUID, textValue, channelStateUpdateListener));
+ public void publishFormatTest() throws Exception {
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, textValue, channelStateUpdateListenerMock));
- c.start(connection, scheduler, 0).get(50, TimeUnit.MILLISECONDS);
- verify(connection).subscribe(eq("state"), eq(c));
+ c.start(connectionMock, scheduler, 0).get(50, TimeUnit.MILLISECONDS);
+ verify(connectionMock).subscribe(eq("state"), eq(c));
c.publishValue(new StringType("UPDATE")).get();
- verify(connection).publish(eq("command"), argThat(p -> Arrays.equals(p, "UPDATE".getBytes())), anyInt(),
+ verify(connectionMock).publish(eq("command"), argThat(p -> Arrays.equals(p, "UPDATE".getBytes())), anyInt(),
eq(false));
c.config.formatBeforePublish = "prefix%s";
c.publishValue(new StringType("UPDATE")).get();
- verify(connection).publish(eq("command"), argThat(p -> Arrays.equals(p, "prefixUPDATE".getBytes())), anyInt(),
- eq(false));
+ verify(connectionMock).publish(eq("command"), argThat(p -> Arrays.equals(p, "prefixUPDATE".getBytes())),
+ anyInt(), eq(false));
c.config.formatBeforePublish = "%1$s-%1$s";
c.publishValue(new StringType("UPDATE")).get();
- verify(connection).publish(eq("command"), argThat(p -> Arrays.equals(p, "UPDATE-UPDATE".getBytes())), anyInt(),
- eq(false));
+ verify(connectionMock).publish(eq("command"), argThat(p -> Arrays.equals(p, "UPDATE-UPDATE".getBytes())),
+ anyInt(), eq(false));
c.config.formatBeforePublish = "%s";
c.config.retained = true;
c.publishValue(new StringType("UPDATE")).get();
- verify(connection).publish(eq("command"), any(), anyInt(), eq(true));
+ verify(connectionMock).publish(eq("command"), any(), anyInt(), eq(true));
c.stop().get();
- verify(connection).unsubscribe(eq("state"), eq(c));
+ verify(connectionMock).unsubscribe(eq("state"), eq(c));
}
@Test
- public void receiveWildcardTest() throws InterruptedException, ExecutionException, TimeoutException {
+ public void receiveWildcardTest() throws Exception {
ChannelState c = spy(new ChannelState(ChannelConfigBuilder.create("state/+/topic", "command").build(),
- channelUID, textValue, channelStateUpdateListener));
+ channelUIDMock, textValue, channelStateUpdateListenerMock));
- CompletableFuture<@Nullable Void> future = c.start(connection, scheduler, 100);
+ CompletableFuture<@Nullable Void> future = c.start(connectionMock, scheduler, 100);
c.processMessage("state/bla/topic", "A TEST".getBytes());
future.get(300, TimeUnit.MILLISECONDS);
assertThat(textValue.getChannelState().toString(), is("A TEST"));
- verify(channelStateUpdateListener).updateChannelState(eq(channelUID), any());
+ verify(channelStateUpdateListenerMock).updateChannelState(eq(channelUIDMock), any());
}
@Test
- public void receiveStringTest() throws InterruptedException, ExecutionException, TimeoutException {
- ChannelState c = spy(new ChannelState(config, channelUID, textValue, channelStateUpdateListener));
+ public void receiveStringTest() throws Exception {
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, textValue, channelStateUpdateListenerMock));
- CompletableFuture<@Nullable Void> future = c.start(connection, scheduler, 100);
+ CompletableFuture<@Nullable Void> future = c.start(connectionMock, scheduler, 100);
c.processMessage("state", "A TEST".getBytes());
future.get(300, TimeUnit.MILLISECONDS);
assertThat(textValue.getChannelState().toString(), is("A TEST"));
- verify(channelStateUpdateListener).updateChannelState(eq(channelUID), any());
+ verify(channelStateUpdateListenerMock).updateChannelState(eq(channelUIDMock), any());
}
@Test
public void receiveDecimalTest() {
NumberValue value = new NumberValue(null, null, new BigDecimal(10), null);
- ChannelState c = spy(new ChannelState(config, channelUID, value, channelStateUpdateListener));
- c.start(connection, mock(ScheduledExecutorService.class), 100);
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, value, channelStateUpdateListenerMock));
+ c.start(connectionMock, mock(ScheduledExecutorService.class), 100);
c.processMessage("state", "15".getBytes());
assertThat(value.getChannelState().toString(), is("15"));
c.processMessage("state", "DECREASE".getBytes());
assertThat(value.getChannelState().toString(), is("15"));
- verify(channelStateUpdateListener, times(3)).updateChannelState(eq(channelUID), any());
+ verify(channelStateUpdateListenerMock, times(3)).updateChannelState(eq(channelUIDMock), any());
}
@Test
public void receiveDecimalFractionalTest() {
NumberValue value = new NumberValue(null, null, new BigDecimal(10.5), null);
- ChannelState c = spy(new ChannelState(config, channelUID, value, channelStateUpdateListener));
- c.start(connection, mock(ScheduledExecutorService.class), 100);
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, value, channelStateUpdateListenerMock));
+ c.start(connectionMock, mock(ScheduledExecutorService.class), 100);
c.processMessage("state", "5.5".getBytes());
assertThat(value.getChannelState().toString(), is("5.5"));
@Test
public void receiveDecimalUnitTest() {
NumberValue value = new NumberValue(null, null, new BigDecimal(10), Units.WATT);
- ChannelState c = spy(new ChannelState(config, channelUID, value, channelStateUpdateListener));
- c.start(connection, mock(ScheduledExecutorService.class), 100);
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, value, channelStateUpdateListenerMock));
+ c.start(connectionMock, mock(ScheduledExecutorService.class), 100);
c.processMessage("state", "15".getBytes());
assertThat(value.getChannelState().toString(), is("15 W"));
c.processMessage("state", "DECREASE".getBytes());
assertThat(value.getChannelState().toString(), is("15 W"));
- verify(channelStateUpdateListener, times(3)).updateChannelState(eq(channelUID), any());
+ verify(channelStateUpdateListenerMock, times(3)).updateChannelState(eq(channelUIDMock), any());
}
@Test
public void receiveDecimalAsPercentageUnitTest() {
NumberValue value = new NumberValue(null, null, new BigDecimal(10), Units.PERCENT);
- ChannelState c = spy(new ChannelState(config, channelUID, value, channelStateUpdateListener));
- c.start(connection, mock(ScheduledExecutorService.class), 100);
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, value, channelStateUpdateListenerMock));
+ c.start(connectionMock, mock(ScheduledExecutorService.class), 100);
c.processMessage("state", "63.7".getBytes());
assertThat(value.getChannelState().toString(), is("63.7 %"));
- verify(channelStateUpdateListener, times(1)).updateChannelState(eq(channelUID), any());
+ verify(channelStateUpdateListenerMock, times(1)).updateChannelState(eq(channelUIDMock), any());
}
@Test
public void receivePercentageTest() {
PercentageValue value = new PercentageValue(new BigDecimal(-100), new BigDecimal(100), new BigDecimal(10), null,
null);
- ChannelState c = spy(new ChannelState(config, channelUID, value, channelStateUpdateListener));
- c.start(connection, mock(ScheduledExecutorService.class), 100);
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, value, channelStateUpdateListenerMock));
+ c.start(connectionMock, mock(ScheduledExecutorService.class), 100);
c.processMessage("state", "-100".getBytes()); // 0%
assertThat(value.getChannelState().toString(), is("0"));
@Test
public void receiveRGBColorTest() {
ColorValue value = new ColorValue(ColorMode.RGB, "FON", "FOFF", 10);
- ChannelState c = spy(new ChannelState(config, channelUID, value, channelStateUpdateListener));
- c.start(connection, mock(ScheduledExecutorService.class), 100);
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, value, channelStateUpdateListenerMock));
+ c.start(connectionMock, mock(ScheduledExecutorService.class), 100);
c.processMessage("state", "ON".getBytes()); // Normal on state
assertThat(value.getChannelState().toString(), is("0,0,10"));
@Test
public void receiveHSBColorTest() {
ColorValue value = new ColorValue(ColorMode.HSB, "FON", "FOFF", 10);
- ChannelState c = spy(new ChannelState(config, channelUID, value, channelStateUpdateListener));
- c.start(connection, mock(ScheduledExecutorService.class), 100);
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, value, channelStateUpdateListenerMock));
+ c.start(connectionMock, mock(ScheduledExecutorService.class), 100);
c.processMessage("state", "ON".getBytes()); // Normal on state
assertThat(value.getChannelState().toString(), is("0,0,10"));
@Test
public void receiveXYYColorTest() {
ColorValue value = new ColorValue(ColorMode.XYY, "FON", "FOFF", 10);
- ChannelState c = spy(new ChannelState(config, channelUID, value, channelStateUpdateListener));
- c.start(connection, mock(ScheduledExecutorService.class), 100);
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, value, channelStateUpdateListenerMock));
+ c.start(connectionMock, mock(ScheduledExecutorService.class), 100);
c.processMessage("state", "ON".getBytes()); // Normal on state
assertThat(value.getChannelState().toString(), is("0,0,10"));
@Test
public void receiveLocationTest() {
LocationValue value = new LocationValue();
- ChannelState c = spy(new ChannelState(config, channelUID, value, channelStateUpdateListener));
- c.start(connection, mock(ScheduledExecutorService.class), 100);
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, value, channelStateUpdateListenerMock));
+ c.start(connectionMock, mock(ScheduledExecutorService.class), 100);
c.processMessage("state", "46.833974, 7.108433".getBytes());
assertThat(value.getChannelState().toString(), is("46.833974,7.108433"));
@Test
public void receiveDateTimeTest() {
DateTimeValue value = new DateTimeValue();
- ChannelState subject = spy(new ChannelState(config, channelUID, value, channelStateUpdateListener));
- subject.start(connection, mock(ScheduledExecutorService.class), 100);
+ ChannelState subject = spy(new ChannelState(config, channelUIDMock, value, channelStateUpdateListenerMock));
+ subject.start(connectionMock, mock(ScheduledExecutorService.class), 100);
ZonedDateTime zd = ZonedDateTime.now();
String datetime = zd.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
@Test
public void receiveImageTest() {
ImageValue value = new ImageValue();
- ChannelState c = spy(new ChannelState(config, channelUID, value, channelStateUpdateListener));
- c.start(connection, mock(ScheduledExecutorService.class), 100);
+ ChannelState c = spy(new ChannelState(config, channelUIDMock, value, channelStateUpdateListenerMock));
+ c.start(connectionMock, mock(ScheduledExecutorService.class), 100);
- byte[] payload = new byte[] { (byte) 0xFF, (byte) 0xD8, 0x01, 0x02, (byte) 0xFF, (byte) 0xD9 };
+ byte[] payload = { (byte) 0xFF, (byte) 0xD8, 0x01, 0x02, (byte) 0xFF, (byte) 0xD9 };
c.processMessage("state", payload);
assertThat(value.getChannelState(), is(instanceOf(RawType.class)));
assertThat(((RawType) value.getChannelState()).getMimeType(), is("image/jpeg"));
import java.util.concurrent.CompletableFuture;
-import javax.naming.ConfigurationException;
-
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openhab.binding.mqtt.handler.AbstractBrokerHandler;
import org.openhab.core.config.core.Configuration;
import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
-import org.openhab.core.io.transport.mqtt.MqttException;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
+@NonNullByDefault
public class ChannelStateTransformationTests {
- private @Mock TransformationService jsonPathService;
- private @Mock TransformationServiceProvider transformationServiceProvider;
- private @Mock ThingHandlerCallback callback;
- private @Mock Thing thing;
- private @Mock AbstractBrokerHandler bridgeHandler;
- private @Mock MqttBrokerConnection connection;
+ private @Mock @NonNullByDefault({}) TransformationService jsonPathServiceMock;
+ private @Mock @NonNullByDefault({}) TransformationServiceProvider transformationServiceProviderMock;
+ private @Mock @NonNullByDefault({}) ThingHandlerCallback callbackMock;
+ private @Mock @NonNullByDefault({}) Thing thingMock;
+ private @Mock @NonNullByDefault({}) AbstractBrokerHandler bridgeHandlerMock;
+ private @Mock @NonNullByDefault({}) MqttBrokerConnection connectionMock;
- private GenericMQTTThingHandler thingHandler;
+ private @NonNullByDefault({}) GenericMQTTThingHandler thingHandler;
@BeforeEach
- public void setUp() throws ConfigurationException, MqttException {
+ public void setUp() throws Exception {
ThingStatusInfo thingStatus = new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null);
// Mock the thing: We need the thingUID and the bridgeUID
- when(thing.getUID()).thenReturn(testGenericThing);
- when(thing.getChannels()).thenReturn(thingChannelListWithJson);
- when(thing.getStatusInfo()).thenReturn(thingStatus);
- when(thing.getConfiguration()).thenReturn(new Configuration());
+ when(thingMock.getUID()).thenReturn(TEST_GENERIC_THING);
+ when(thingMock.getChannels()).thenReturn(THING_CHANNEL_LIST_WITH_JSON);
+ when(thingMock.getStatusInfo()).thenReturn(thingStatus);
+ when(thingMock.getConfiguration()).thenReturn(new Configuration());
// Return the mocked connection object if the bridge handler is asked for it
- when(bridgeHandler.getConnectionAsync()).thenReturn(CompletableFuture.completedFuture(connection));
+ when(bridgeHandlerMock.getConnectionAsync()).thenReturn(CompletableFuture.completedFuture(connectionMock));
- CompletableFuture<Void> voidFutureComplete = new CompletableFuture<>();
+ CompletableFuture<@Nullable Void> voidFutureComplete = new CompletableFuture<>();
voidFutureComplete.complete(null);
- doReturn(voidFutureComplete).when(connection).unsubscribeAll();
- doReturn(CompletableFuture.completedFuture(true)).when(connection).subscribe(any(), any());
- doReturn(CompletableFuture.completedFuture(true)).when(connection).unsubscribe(any(), any());
+ doReturn(voidFutureComplete).when(connectionMock).unsubscribeAll();
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).subscribe(any(), any());
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).unsubscribe(any(), any());
- thingHandler = spy(new GenericMQTTThingHandler(thing, mock(MqttChannelStateDescriptionProvider.class),
- transformationServiceProvider, 1500));
- when(transformationServiceProvider.getTransformationService(anyString())).thenReturn(jsonPathService);
+ thingHandler = spy(new GenericMQTTThingHandler(thingMock, mock(MqttChannelStateDescriptionProvider.class),
+ transformationServiceProviderMock, 1500));
+ when(transformationServiceProviderMock.getTransformationService(anyString())).thenReturn(jsonPathServiceMock);
- thingHandler.setCallback(callback);
+ thingHandler.setCallback(callbackMock);
// Return the bridge handler if the thing handler asks for it
- doReturn(bridgeHandler).when(thingHandler).getBridgeHandler();
+ doReturn(bridgeHandlerMock).when(thingHandler).getBridgeHandler();
// We are by default online
doReturn(thingStatus).when(thingHandler).getBridgeStatus();
@SuppressWarnings("null")
@Test
- public void initialize() throws MqttException {
- when(thing.getChannels()).thenReturn(thingChannelListWithJson);
+ public void initialize() throws Exception {
+ when(thingMock.getChannels()).thenReturn(THING_CHANNEL_LIST_WITH_JSON);
thingHandler.initialize();
- ChannelState channelConfig = thingHandler.getChannelState(textChannelUID);
- assertThat(channelConfig.transformationsIn.get(0).pattern, is(jsonPathPattern));
+ ChannelState channelConfig = thingHandler.getChannelState(TEXT_CHANNEL_UID);
+ assertThat(channelConfig.transformationsIn.get(0).pattern, is(JSON_PATH_PATTERN));
}
@SuppressWarnings("null")
@Test
public void processMessageWithJSONPath() throws Exception {
- when(jsonPathService.transform(jsonPathPattern, jsonPathJSON)).thenReturn("23.2");
+ when(jsonPathServiceMock.transform(JSON_PATH_PATTERN, JSON_PATH_JSON)).thenReturn("23.2");
thingHandler.initialize();
- ChannelState channelConfig = thingHandler.getChannelState(textChannelUID);
+ ChannelState channelConfig = thingHandler.getChannelState(TEXT_CHANNEL_UID);
channelConfig.setChannelStateUpdateListener(thingHandler);
ChannelStateTransformation transformation = channelConfig.transformationsIn.get(0);
- byte payload[] = jsonPathJSON.getBytes();
- assertThat(transformation.pattern, is(jsonPathPattern));
+ byte payload[] = JSON_PATH_JSON.getBytes();
+ assertThat(transformation.pattern, is(JSON_PATH_PATTERN));
// Test process message
channelConfig.processMessage(channelConfig.getStateTopic(), payload);
- verify(callback).stateUpdated(eq(textChannelUID), argThat(arg -> "23.2".equals(arg.toString())));
+ verify(callbackMock).stateUpdated(eq(TEXT_CHANNEL_UID), argThat(arg -> "23.2".equals(arg.toString())));
assertThat(channelConfig.getCache().getChannelState().toString(), is("23.2"));
}
}
import java.util.concurrent.CompletableFuture;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
+@NonNullByDefault
public class GenericThingHandlerTests {
- private @Mock ThingHandlerCallback callback;
- private @Mock Thing thing;
- private @Mock AbstractBrokerHandler bridgeHandler;
- private @Mock MqttBrokerConnection connection;
+ private @Mock @NonNullByDefault({}) ThingHandlerCallback callbackMock;
+ private @Mock @NonNullByDefault({}) Thing thingMock;
+ private @Mock @NonNullByDefault({}) AbstractBrokerHandler bridgeHandlerMock;
+ private @Mock @NonNullByDefault({}) MqttBrokerConnection connectionMock;
- private GenericMQTTThingHandler thingHandler;
+ private @NonNullByDefault({}) GenericMQTTThingHandler thingHandler;
@BeforeEach
public void setUp() {
ThingStatusInfo thingStatus = new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null);
// Mock the thing: We need the thingUID and the bridgeUID
- when(thing.getUID()).thenReturn(testGenericThing);
- when(thing.getChannels()).thenReturn(thingChannelList);
- when(thing.getStatusInfo()).thenReturn(thingStatus);
- when(thing.getConfiguration()).thenReturn(new Configuration());
+ when(thingMock.getUID()).thenReturn(TEST_GENERIC_THING);
+ when(thingMock.getChannels()).thenReturn(THING_CHANNEL_LIST);
+ when(thingMock.getStatusInfo()).thenReturn(thingStatus);
+ when(thingMock.getConfiguration()).thenReturn(new Configuration());
// Return the mocked connection object if the bridge handler is asked for it
- when(bridgeHandler.getConnectionAsync()).thenReturn(CompletableFuture.completedFuture(connection));
+ when(bridgeHandlerMock.getConnectionAsync()).thenReturn(CompletableFuture.completedFuture(connectionMock));
- CompletableFuture<Void> voidFutureComplete = new CompletableFuture<>();
+ CompletableFuture<@Nullable Void> voidFutureComplete = new CompletableFuture<>();
voidFutureComplete.complete(null);
- doReturn(voidFutureComplete).when(connection).unsubscribeAll();
- doReturn(CompletableFuture.completedFuture(true)).when(connection).subscribe(any(), any());
- doReturn(CompletableFuture.completedFuture(true)).when(connection).unsubscribe(any(), any());
- doReturn(CompletableFuture.completedFuture(true)).when(connection).publish(any(), any(), anyInt(),
+ doReturn(voidFutureComplete).when(connectionMock).unsubscribeAll();
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).subscribe(any(), any());
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).unsubscribe(any(), any());
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).publish(any(), any(), anyInt(),
anyBoolean());
- thingHandler = spy(new GenericMQTTThingHandler(thing, mock(MqttChannelStateDescriptionProvider.class),
+ thingHandler = spy(new GenericMQTTThingHandler(thingMock, mock(MqttChannelStateDescriptionProvider.class),
mock(TransformationServiceProvider.class), 1500));
- thingHandler.setCallback(callback);
+ thingHandler.setCallback(callbackMock);
// Return the bridge handler if the thing handler asks for it
- doReturn(bridgeHandler).when(thingHandler).getBridgeHandler();
+ doReturn(bridgeHandlerMock).when(thingHandler).getBridgeHandler();
// The broker connection bridge is by default online
doReturn(thingStatus).when(thingHandler).getBridgeStatus();
public void initializeWithUnknownThingUID() {
ChannelConfig config = textConfiguration().as(ChannelConfig.class);
assertThrows(IllegalArgumentException.class,
- () -> thingHandler.createChannelState(config, new ChannelUID(testGenericThing, "test"),
- ValueFactory.createValueState(config, unknownChannel.getId())));
+ () -> thingHandler.createChannelState(config, new ChannelUID(TEST_GENERIC_THING, "test"),
+ ValueFactory.createValueState(config, UNKNOWN_CHANNEL.getId())));
}
@Test
thingHandler.initialize();
verify(thingHandler).bridgeStatusChanged(any());
verify(thingHandler).start(any());
- assertThat(thingHandler.getConnection(), is(connection));
+ assertThat(thingHandler.getConnection(), is(connectionMock));
- ChannelState channelConfig = thingHandler.channelStateByChannelUID.get(textChannelUID);
+ ChannelState channelConfig = thingHandler.channelStateByChannelUID.get(TEXT_CHANNEL_UID);
assertThat(channelConfig.getStateTopic(), is("test/state"));
assertThat(channelConfig.getCommandTopic(), is("test/command"));
- verify(connection).subscribe(eq(channelConfig.getStateTopic()), eq(channelConfig));
+ verify(connectionMock).subscribe(eq(channelConfig.getStateTopic()), eq(channelConfig));
- verify(callback).statusUpdated(eq(thing), argThat((arg) -> arg.getStatus().equals(ThingStatus.ONLINE)
- && arg.getStatusDetail().equals(ThingStatusDetail.NONE)));
+ verify(callbackMock).statusUpdated(eq(thingMock), argThat(arg -> ThingStatus.ONLINE.equals(arg.getStatus())
+ && ThingStatusDetail.NONE.equals(arg.getStatusDetail())));
}
@Test
doReturn(channelConfig).when(thingHandler).createChannelState(any(), any(), any());
thingHandler.initialize();
- ThingHandlerHelper.setConnection(thingHandler, connection);
+ ThingHandlerHelper.setConnection(thingHandler, connectionMock);
- thingHandler.handleCommand(textChannelUID, RefreshType.REFRESH);
- verify(callback).stateUpdated(eq(textChannelUID), argThat(arg -> "DEMOVALUE".equals(arg.toString())));
+ thingHandler.handleCommand(TEXT_CHANNEL_UID, RefreshType.REFRESH);
+ verify(callbackMock).stateUpdated(eq(TEXT_CHANNEL_UID), argThat(arg -> "DEMOVALUE".equals(arg.toString())));
}
@Test
public void handleCommandUpdateString() {
TextValue value = spy(new TextValue());
ChannelState channelConfig = spy(
- new ChannelState(ChannelConfigBuilder.create("stateTopic", "commandTopic").build(), textChannelUID,
+ new ChannelState(ChannelConfigBuilder.create("stateTopic", "commandTopic").build(), TEXT_CHANNEL_UID,
value, thingHandler));
doReturn(channelConfig).when(thingHandler).createChannelState(any(), any(), any());
thingHandler.initialize();
- ThingHandlerHelper.setConnection(thingHandler, connection);
+ ThingHandlerHelper.setConnection(thingHandler, connectionMock);
StringType updateValue = new StringType("UPDATE");
- thingHandler.handleCommand(textChannelUID, updateValue);
+ thingHandler.handleCommand(TEXT_CHANNEL_UID, updateValue);
verify(value).update(eq(updateValue));
assertThat(channelConfig.getCache().getChannelState().toString(), is("UPDATE"));
}
public void handleCommandUpdateBoolean() {
OnOffValue value = spy(new OnOffValue("ON", "OFF"));
ChannelState channelConfig = spy(
- new ChannelState(ChannelConfigBuilder.create("stateTopic", "commandTopic").build(), textChannelUID,
+ new ChannelState(ChannelConfigBuilder.create("stateTopic", "commandTopic").build(), TEXT_CHANNEL_UID,
value, thingHandler));
doReturn(channelConfig).when(thingHandler).createChannelState(any(), any(), any());
thingHandler.initialize();
- ThingHandlerHelper.setConnection(thingHandler, connection);
+ ThingHandlerHelper.setConnection(thingHandler, connectionMock);
StringType updateValue = new StringType("ON");
- thingHandler.handleCommand(textChannelUID, updateValue);
+ thingHandler.handleCommand(TEXT_CHANNEL_UID, updateValue);
verify(value).update(eq(updateValue));
assertThat(channelConfig.getCache().getChannelState(), is(OnOffType.ON));
public void processMessage() {
TextValue textValue = new TextValue();
ChannelState channelConfig = spy(
- new ChannelState(ChannelConfigBuilder.create("test/state", "test/state/set").build(), textChannelUID,
+ new ChannelState(ChannelConfigBuilder.create("test/state", "test/state/set").build(), TEXT_CHANNEL_UID,
textValue, thingHandler));
doReturn(channelConfig).when(thingHandler).createChannelState(any(), any(), any());
thingHandler.initialize();
// Test process message
channelConfig.processMessage("test/state", payload);
- verify(callback, atLeastOnce()).statusUpdated(eq(thing),
- argThat(arg -> arg.getStatus().equals(ThingStatus.ONLINE)));
+ verify(callbackMock, atLeastOnce()).statusUpdated(eq(thingMock),
+ argThat(arg -> ThingStatus.ONLINE.equals(arg.getStatus())));
- verify(callback).stateUpdated(eq(textChannelUID), argThat(arg -> "UPDATE".equals(arg.toString())));
+ verify(callbackMock).stateUpdated(eq(TEXT_CHANNEL_UID), argThat(arg -> "UPDATE".equals(arg.toString())));
assertThat(textValue.getChannelState().toString(), is("UPDATE"));
}
public void handleBridgeStatusChange() {
Configuration config = new Configuration();
config.put("availabilityTopic", "test/LWT");
- when(thing.getConfiguration()).thenReturn(config);
+ when(thingMock.getConfiguration()).thenReturn(config);
thingHandler.initialize();
thingHandler
.bridgeStatusChanged(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, null));
thingHandler.bridgeStatusChanged(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null));
- verify(connection, times(2)).subscribe(eq("test/LWT"), any());
+ verify(connectionMock, times(2)).subscribe(eq("test/LWT"), any());
}
}
@NonNullByDefault
public class ThingChannelConstants {
// Common ThingUID and ChannelUIDs
- public static final ThingUID testGenericThing = new ThingUID(GENERIC_MQTT_THING, "genericthing");
+ public static final ThingUID TEST_GENERIC_THING = new ThingUID(GENERIC_MQTT_THING, "genericthing");
- public static final ChannelTypeUID textChannel = new ChannelTypeUID(BINDING_ID, MqttBindingConstants.STRING);
- public static final ChannelTypeUID textWithJsonChannel = new ChannelTypeUID(BINDING_ID,
+ public static final ChannelTypeUID TEXT_CHANNEL = new ChannelTypeUID(BINDING_ID, MqttBindingConstants.STRING);
+ public static final ChannelTypeUID TEXT_WITH_JSON_CHANNEL = new ChannelTypeUID(BINDING_ID,
MqttBindingConstants.STRING);
- public static final ChannelTypeUID onoffChannel = new ChannelTypeUID(BINDING_ID, MqttBindingConstants.SWITCH);
- public static final ChannelTypeUID numberChannel = new ChannelTypeUID(BINDING_ID, MqttBindingConstants.NUMBER);
- public static final ChannelTypeUID percentageChannel = new ChannelTypeUID(BINDING_ID, MqttBindingConstants.DIMMER);
- public static final ChannelTypeUID unknownChannel = new ChannelTypeUID(BINDING_ID, "unknown");
+ public static final ChannelTypeUID ON_OFF_CHANNEL = new ChannelTypeUID(BINDING_ID, MqttBindingConstants.SWITCH);
+ public static final ChannelTypeUID NUMBER_CHANNEL = new ChannelTypeUID(BINDING_ID, MqttBindingConstants.NUMBER);
+ public static final ChannelTypeUID PERCENTAGE_CHANNEL = new ChannelTypeUID(BINDING_ID, MqttBindingConstants.DIMMER);
+ public static final ChannelTypeUID UNKNOWN_CHANNEL = new ChannelTypeUID(BINDING_ID, "unknown");
- public static final ChannelUID textChannelUID = new ChannelUID(testGenericThing, "mytext");
+ public static final ChannelUID TEXT_CHANNEL_UID = new ChannelUID(TEST_GENERIC_THING, "mytext");
- public static final String jsonPathJSON = "{ \"device\": { \"status\": { \"temperature\": 23.2 }}}";
- public static final String jsonPathPattern = "$.device.status.temperature";
+ public static final String JSON_PATH_JSON = "{ \"device\": { \"status\": { \"temperature\": 23.2 }}}";
+ public static final String JSON_PATH_PATTERN = "$.device.status.temperature";
- public static final List<Channel> thingChannelList = new ArrayList<>();
- public static final List<Channel> thingChannelListWithJson = new ArrayList<>();
+ public static final List<Channel> THING_CHANNEL_LIST = new ArrayList<>();
+ public static final List<Channel> THING_CHANNEL_LIST_WITH_JSON = new ArrayList<>();
/**
* Create a channel with exact the parameters we need for the tests
* @return
*/
public static Channel cb(String id, String acceptedType, Configuration config, ChannelTypeUID channelTypeUID) {
- return ChannelBuilder.create(new ChannelUID(testGenericThing, id), acceptedType).withConfiguration(config)
+ return ChannelBuilder.create(new ChannelUID(TEST_GENERIC_THING, id), acceptedType).withConfiguration(config)
.withType(channelTypeUID).build();
}
static {
- thingChannelList.add(cb("mytext", "TextItemType", textConfiguration(), textChannel));
- thingChannelList.add(cb("onoff", "OnOffType", onoffConfiguration(), onoffChannel));
- thingChannelList.add(cb("num", "NumberType", numberConfiguration(), numberChannel));
- thingChannelList.add(cb("percent", "NumberType", percentageConfiguration(), percentageChannel));
-
- thingChannelListWithJson.add(cb("mytext", "TextItemType", textConfigurationWithJson(), textWithJsonChannel));
- thingChannelListWithJson.add(cb("onoff", "OnOffType", onoffConfiguration(), onoffChannel));
- thingChannelListWithJson.add(cb("num", "NumberType", numberConfiguration(), numberChannel));
- thingChannelListWithJson.add(cb("percent", "NumberType", percentageConfiguration(), percentageChannel));
+ THING_CHANNEL_LIST.add(cb("mytext", "TextItemType", textConfiguration(), TEXT_CHANNEL));
+ THING_CHANNEL_LIST.add(cb("onoff", "OnOffType", onoffConfiguration(), ON_OFF_CHANNEL));
+ THING_CHANNEL_LIST.add(cb("num", "NumberType", numberConfiguration(), NUMBER_CHANNEL));
+ THING_CHANNEL_LIST.add(cb("percent", "NumberType", percentageConfiguration(), PERCENTAGE_CHANNEL));
+
+ THING_CHANNEL_LIST_WITH_JSON
+ .add(cb("mytext", "TextItemType", textConfigurationWithJson(), TEXT_WITH_JSON_CHANNEL));
+ THING_CHANNEL_LIST_WITH_JSON.add(cb("onoff", "OnOffType", onoffConfiguration(), ON_OFF_CHANNEL));
+ THING_CHANNEL_LIST_WITH_JSON.add(cb("num", "NumberType", numberConfiguration(), NUMBER_CHANNEL));
+ THING_CHANNEL_LIST_WITH_JSON.add(cb("percent", "NumberType", percentageConfiguration(), PERCENTAGE_CHANNEL));
}
static Configuration textConfiguration() {
Map<String, Object> data = new HashMap<>();
data.put("stateTopic", "test/state");
data.put("commandTopic", "test/command");
- data.put("transformationPattern", "JSONPATH:" + jsonPathPattern);
+ data.put("transformationPattern", "JSONPATH:" + JSON_PATH_PATTERN);
return new Configuration(data);
}
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Stream;
-import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
+@NonNullByDefault
public class MqttTopicClassMapperTests {
@Retention(RetentionPolicy.RUNTIME)
@Target({ FIELD })
public transient String ignoreTransient = "";
public final String ignoreFinal = "";
- public @TestValue("string") String aString;
- public @TestValue("false") Boolean aBoolean;
- public @TestValue("10") Long aLong;
- public @TestValue("10") Integer aInteger;
- public @TestValue("10") BigDecimal aDecimal;
+ public @TestValue("string") @Nullable String aString;
+ public @TestValue("false") @Nullable Boolean aBoolean;
+ public @TestValue("10") @Nullable Long aLong;
+ public @TestValue("10") @Nullable Integer aInteger;
+ public @TestValue("10") @Nullable BigDecimal aDecimal;
- public @TestValue("10") @TopicPrefix("a") int Int = 24;
+ public @TestValue("10") @TopicPrefix("a") int aInt = 24;
public @TestValue("false") boolean aBool = true;
- public @TestValue("abc,def") @MQTTvalueTransform(splitCharacter = ",") String[] properties;
+ public @TestValue("abc,def") @MQTTvalueTransform(splitCharacter = ",") String @Nullable [] properties;
public enum ReadyState {
unknown,
public @TestValue("integer") @MQTTvalueTransform(suffix = "_") DataTypeEnum datatype = DataTypeEnum.unknown;
@Override
- public @NonNull Object getFieldsOf() {
+ public Object getFieldsOf() {
return this;
}
}
- @Mock
- MqttBrokerConnection connection;
+ private @Mock @NonNullByDefault({}) MqttBrokerConnection connectionMock;
+ private @Mock @NonNullByDefault({}) ScheduledExecutorService executorMock;
+ private @Mock @NonNullByDefault({}) AttributeChanged fieldChangedObserverMock;
+ private @Spy Object countInjectedFields = new Object();
- @Mock
- ScheduledExecutorService executor;
-
- @Mock
- AttributeChanged fieldChangedObserver;
-
- @Spy
- Object countInjectedFields = new Object();
int injectedFields = 0;
// A completed future is returned for a subscribe call to the attributes
@BeforeEach
public void setUp() {
- doReturn(CompletableFuture.completedFuture(true)).when(connection).subscribe(any(), any());
- doReturn(CompletableFuture.completedFuture(true)).when(connection).unsubscribe(any(), any());
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).subscribe(any(), any());
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).unsubscribe(any(), any());
injectedFields = (int) Stream.of(countInjectedFields.getClass().getDeclaredFields())
.filter(AbstractMqttAttributeClass::filterField).count();
}
anyBoolean());
// Subscribe now to all fields
- CompletableFuture<Void> future = attributes.subscribeAndReceive(connection, executor, "homie/device123", null,
- 10);
+ CompletableFuture<@Nullable Void> future = attributes.subscribeAndReceive(connectionMock, executorMock,
+ "homie/device123", null, 10);
assertThat(future.isDone(), is(true));
assertThat(attributes.subscriptions.size(), is(10 + injectedFields));
}
// TODO timeout
@SuppressWarnings({ "null", "unused" })
@Test
- public void subscribeAndReceive() throws IllegalArgumentException, IllegalAccessException {
+ public void subscribeAndReceive() throws Exception {
final Attributes attributes = spy(new Attributes());
doAnswer(this::createSubscriberAnswer).when(attributes).createSubscriber(any(), any(), anyString(),
anyBoolean());
- verify(connection, times(0)).subscribe(anyString(), any());
+ verify(connectionMock, times(0)).subscribe(anyString(), any());
// Subscribe now to all fields
- CompletableFuture<Void> future = attributes.subscribeAndReceive(connection, executor, "homie/device123",
- fieldChangedObserver, 10);
+ CompletableFuture<@Nullable Void> future = attributes.subscribeAndReceive(connectionMock, executorMock,
+ "homie/device123", fieldChangedObserverMock, 10);
assertThat(future.isDone(), is(true));
// We expect 10 subscriptions now
// Simulate a received MQTT value and use the annotation data as input.
f.processMessage(f.topic, annotation.value().getBytes());
- verify(fieldChangedObserver, times(++loopCounter)).attributeChanged(any(), any(), any(), any(),
+ verify(fieldChangedObserverMock, times(++loopCounter)).attributeChanged(any(), any(), any(), any(),
anyBoolean());
// Check each value if the assignment worked
}
@Test
- public void ignoresInvalidEnum() throws IllegalArgumentException, IllegalAccessException {
+ public void ignoresInvalidEnum() throws Exception {
final Attributes attributes = spy(new Attributes());
doAnswer(this::createSubscriberAnswer).when(attributes).createSubscriber(any(), any(), anyString(),
anyBoolean());
- verify(connection, times(0)).subscribe(anyString(), any());
+ verify(connectionMock, times(0)).subscribe(anyString(), any());
// Subscribe now to all fields
- CompletableFuture<Void> future = attributes.subscribeAndReceive(connection, executor, "homie/device123",
- fieldChangedObserver, 10);
+ CompletableFuture<@Nullable Void> future = attributes.subscribeAndReceive(connectionMock, executorMock,
+ "homie/device123", fieldChangedObserverMock, 10);
assertThat(future.isDone(), is(true));
SubscribeFieldToMQTTtopic field = attributes.subscriptions.stream().filter(f -> f.field.getName() == "state")
.findFirst().get();
field.processMessage(field.topic, "garbage".getBytes());
- verify(fieldChangedObserver, times(0)).attributeChanged(any(), any(), any(), any(), anyBoolean());
+ verify(fieldChangedObserverMock, times(0)).attributeChanged(any(), any(), any(), any(), anyBoolean());
assertThat(attributes.state.toString(), is("unknown"));
}
}
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
+@NonNullByDefault
public class SubscribeFieldToMQTTtopicTests {
@Retention(RetentionPolicy.RUNTIME)
@Target({ FIELD })
@SuppressWarnings("unused")
public final String ignoreFinal = "";
- public @TestValue("string") String aString;
- public @TestValue("false") Boolean aBoolean;
- public @TestValue("10") Long aLong;
- public @TestValue("10") Integer aInteger;
- public @TestValue("10") BigDecimal aDecimal;
+ public @TestValue("string") @Nullable String aString;
+ public @TestValue("false") @Nullable Boolean aBoolean;
+ public @TestValue("10") @Nullable Long aLong;
+ public @TestValue("10") @Nullable Integer aInteger;
+ public @TestValue("10") @Nullable BigDecimal aDecimal;
- public @TestValue("10") @TopicPrefix("a") int Int = 24;
+ public @TestValue("10") @TopicPrefix("a") int aInt = 24;
public @TestValue("false") boolean aBool = true;
- public @TestValue("abc,def") @MQTTvalueTransform(splitCharacter = ",") String[] properties;
+ public @TestValue("abc,def") @MQTTvalueTransform(splitCharacter = ",") String @Nullable [] properties;
public enum ReadyState {
unknown,
public @TestValue("integer") @MQTTvalueTransform(suffix = "_") DataTypeEnum datatype = DataTypeEnum.unknown;
@Override
- public @NonNull Object getFieldsOf() {
+ public Object getFieldsOf() {
return this;
}
}
Attributes attributes = new Attributes();
- @Mock
- MqttBrokerConnection connection;
-
- @Mock
- SubscribeFieldToMQTTtopic fieldSubscriber;
-
- @Mock
- FieldChanged fieldChanged;
+ private @Mock @NonNullByDefault({}) MqttBrokerConnection connectionMock;
+ private @Mock @NonNullByDefault({}) FieldChanged fieldChangedMock;
@BeforeEach
public void setUp() {
- doReturn(CompletableFuture.completedFuture(true)).when(connection).subscribe(any(), any());
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).subscribe(any(), any());
}
@Test
- public void TimeoutIfNoMessageReceive()
- throws InterruptedException, NoSuchFieldException, ExecutionException, TimeoutException {
- final Field field = Attributes.class.getField("Int");
+ public void timeoutIfNoMessageReceive() throws Exception {
+ final Field field = Attributes.class.getField("aInt");
ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
- SubscribeFieldToMQTTtopic subscriber = new SubscribeFieldToMQTTtopic(scheduler, field, fieldChanged,
+ SubscribeFieldToMQTTtopic subscriber = new SubscribeFieldToMQTTtopic(scheduler, field, fieldChangedMock,
"homie/device123", false);
assertThrows(TimeoutException.class,
- () -> subscriber.subscribeAndReceive(connection, 1000).get(50, TimeUnit.MILLISECONDS));
+ () -> subscriber.subscribeAndReceive(connectionMock, 1000).get(50, TimeUnit.MILLISECONDS));
}
@Test
- public void MandatoryMissing()
- throws InterruptedException, NoSuchFieldException, ExecutionException, TimeoutException {
- final Field field = Attributes.class.getField("Int");
+ public void mandatoryMissing() throws Exception {
+ final Field field = Attributes.class.getField("aInt");
ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
- SubscribeFieldToMQTTtopic subscriber = new SubscribeFieldToMQTTtopic(scheduler, field, fieldChanged,
+ SubscribeFieldToMQTTtopic subscriber = new SubscribeFieldToMQTTtopic(scheduler, field, fieldChangedMock,
"homie/device123", true);
- assertThrows(ExecutionException.class, () -> subscriber.subscribeAndReceive(connection, 50).get());
+ assertThrows(ExecutionException.class, () -> subscriber.subscribeAndReceive(connectionMock, 50).get());
}
@Test
- public void MessageReceive()
- throws InterruptedException, NoSuchFieldException, ExecutionException, TimeoutException {
+ public void messageReceive() throws Exception {
final FieldChanged changed = (field, value) -> {
try {
field.set(attributes.getFieldsOf(), value);
fail(e.getMessage());
}
};
- final Field field = Attributes.class.getField("Int");
+ final Field field = Attributes.class.getField("aInt");
ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
SubscribeFieldToMQTTtopic subscriber = new SubscribeFieldToMQTTtopic(scheduler, field, changed,
"homie/device123", false);
- CompletableFuture<@Nullable Void> future = subscriber.subscribeAndReceive(connection, 1000);
+ CompletableFuture<@Nullable Void> future = subscriber.subscribeAndReceive(connectionMock, 1000);
// Simulate a received MQTT message
subscriber.processMessage("ignored", "10".getBytes());
// No timeout should happen
future.get(50, TimeUnit.MILLISECONDS);
- assertThat(attributes.Int, is(10));
+ assertThat(attributes.aInt, is(10));
}
}
import static org.junit.jupiter.api.Assertions.*;
import java.math.BigDecimal;
+import java.util.Objects;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.mapping.ColorMode;
import org.openhab.core.library.types.DecimalType;
*
* @author David Graeff - Initial contribution
*/
+@NonNullByDefault
public class ValueTests {
- Command p(Value v, String str) {
- return TypeParser.parseCommand(v.getSupportedCommandTypes(), str);
+ private Command p(Value v, String str) {
+ return Objects.requireNonNull(TypeParser.parseCommand(v.getSupportedCommandTypes(), str));
}
@Test
import org.openhab.binding.mqtt.homeassistant.internal.exception.ConfigurationException;
import org.openhab.binding.mqtt.homeassistant.internal.exception.UnsupportedComponentException;
import org.openhab.core.thing.ThingUID;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
*/
@NonNullByDefault
public class ComponentFactory {
- private static final Logger LOGGER = LoggerFactory.getLogger(ComponentFactory.class);
-
/**
* Create a HA MQTT component. The configuration JSon string is required.
*
field.set(config, newValue);
} catch (IllegalArgumentException | IllegalAccessException e) {
- throw new RuntimeException(e);
+ throw new IllegalStateException(e);
}
}
}
*/
package org.openhab.binding.mqtt.homeassistant.internal.exception;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+
/**
* Exception class for errors in HomeAssistant components configurations
*
* @author Anton Kharuzhy - Initial contribution
*/
+@NonNullByDefault
public class ConfigurationException extends RuntimeException {
public ConfigurationException(String message) {
super(message);
*/
package org.openhab.binding.mqtt.homeassistant.internal.exception;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+
/**
* Exception class for unsupported components
*
* @author Anton Kharuzhy - Initial contribution
*/
+@NonNullByDefault
public class UnsupportedComponentException extends ConfigurationException {
public UnsupportedComponentException(String message) {
super(message);
import java.util.Collection;
import java.util.Collections;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.Configuration;
/**
* @author Jochen Klein - Initial contribution
*/
+@NonNullByDefault
public class HaIDTests {
@Test
import java.nio.charset.StandardCharsets;
import java.util.List;
+import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
-import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.Mock;
* @author Anton Kharuzhy - Initial contribution
*/
@SuppressWarnings({ "ConstantConditions" })
+@NonNullByDefault
public abstract class AbstractComponentTests extends AbstractHomeAssistantTests {
- private final static int SUBSCRIBE_TIMEOUT = 10000;
- private final static int ATTRIBUTE_RECEIVE_TIMEOUT = 2000;
+ private static final int SUBSCRIBE_TIMEOUT = 10000;
+ private static final int ATTRIBUTE_RECEIVE_TIMEOUT = 2000;
- private @Mock ThingHandlerCallback callback;
- private LatchThingHandler thingHandler;
+ private @Mock @NonNullByDefault({}) ThingHandlerCallback callbackMock;
+ private @NonNullByDefault({}) LatchThingHandler thingHandler;
@BeforeEach
public void setupThingHandler() {
config.put(HandlerConfiguration.PROPERTY_BASETOPIC, HandlerConfiguration.DEFAULT_BASETOPIC);
config.put(HandlerConfiguration.PROPERTY_TOPICS, getConfigTopics());
- when(callback.getBridge(eq(BRIDGE_UID))).thenReturn(bridgeThing);
+ when(callbackMock.getBridge(eq(BRIDGE_UID))).thenReturn(bridgeThing);
thingHandler = new LatchThingHandler(haThing, channelTypeProvider, transformationServiceProvider,
SUBSCRIBE_TIMEOUT, ATTRIBUTE_RECEIVE_TIMEOUT);
thingHandler.setConnection(bridgeConnection);
- thingHandler.setCallback(callback);
+ thingHandler.setCallback(callbackMock);
thingHandler = spy(thingHandler);
thingHandler.initialize();
} catch (InterruptedException e) {
assertThat(e.getMessage(), false);
}
- var component = thingHandler.getDiscoveredComponent();
- assertThat(component, CoreMatchers.notNullValue());
- return component;
+ return Objects.requireNonNull(thingHandler.getDiscoveredComponent());
}
/**
*/
protected static void assertChannel(AbstractComponent<@NonNull ? extends AbstractChannelConfiguration> component,
String channelId, String stateTopic, String commandTopic, String label, Class<? extends Value> valueClass) {
- var stateChannel = component.getChannel(channelId);
+ var stateChannel = Objects.requireNonNull(component.getChannel(channelId));
assertChannel(stateChannel, stateTopic, commandTopic, label, valueClass);
}
return false;
}
- @NonNullByDefault
protected static class LatchThingHandler extends HomeAssistantThingHandler {
private @Nullable CountDownLatch latch;
private @Nullable AbstractComponent<@NonNull ? extends AbstractChannelConfiguration> discoveredComponent;
super(thing, channelTypeProvider, transformationServiceProvider, subscribeTimeout, attributeReceiveTimeout);
}
+ @Override
public void componentDiscovered(HaID homeAssistantTopicID, AbstractComponent<@NonNull ?> component) {
accept(List.of(component));
discoveredComponent = component;
import java.util.Set;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.values.TextValue;
import org.openhab.core.library.types.StringType;
* @author Anton Kharuzhy - Initial contribution
*/
@SuppressWarnings("ConstantConditions")
+@NonNullByDefault
public class AlarmControlPanelTests extends AbstractComponentTests {
public static final String CONFIG_TOPIC = "alarm_control_panel/0x0000000000000000_alarm_control_panel_zigbee2mqtt";
assertPublished("zigbee2mqtt/alarm/set/state", "ARM_HOME_");
}
+ @Override
protected Set<String> getConfigTopics() {
return Set.of(CONFIG_TOPIC);
}
import java.util.Set;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.values.OnOffValue;
import org.openhab.core.library.types.OnOffType;
*
* @author Anton Kharuzhy - Initial contribution
*/
+@NonNullByDefault
public class BinarySensorTests extends AbstractComponentTests {
public static final String CONFIG_TOPIC = "binary_sensor/0x0000000000000000_binary_sensor_zigbee2mqtt";
waitForAssert(() -> assertState(component, BinarySensor.SENSOR_CHANNEL_ID, UnDefType.UNDEF), 10000, 200);
}
+ @Override
protected Set<String> getConfigTopics() {
return Set.of(CONFIG_TOPIC);
}
import java.util.Set;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.values.ImageValue;
import org.openhab.core.library.types.RawType;
*
* @author Anton Kharuzhy - Initial contribution
*/
+@NonNullByDefault
public class CameraTests extends AbstractComponentTests {
public static final String CONFIG_TOPIC = "camera/0x0000000000000000_camera_zigbee2mqtt";
assertState(component, Camera.CAMERA_CHANNEL_ID, new RawType(imageBytes, "image/png"));
}
+ @Override
protected Set<String> getConfigTopics() {
return Set.of(CONFIG_TOPIC);
}
import java.util.Set;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.values.NumberValue;
import org.openhab.binding.mqtt.generic.values.OnOffValue;
* @author Anton Kharuzhy - Initial contribution
*/
@SuppressWarnings("ConstantConditions")
+@NonNullByDefault
public class ClimateTests extends AbstractComponentTests {
public static final String CONFIG_TOPIC = "climate/0x847127fffe11dd6a_climate_zigbee2mqtt";
import java.util.Set;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.values.RollershutterValue;
import org.openhab.core.library.types.PercentType;
* @author Anton Kharuzhy - Initial contribution
*/
@SuppressWarnings("ConstantConditions")
+@NonNullByDefault
public class CoverTests extends AbstractComponentTests {
public static final String CONFIG_TOPIC = "cover/0x0000000000000000_cover_zigbee2mqtt";
assertPublished("zigbee2mqtt/cover/set/state", "STOP_", 2);
}
+ @Override
protected Set<String> getConfigTopics() {
return Set.of(CONFIG_TOPIC);
}
import java.util.Set;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.values.OnOffValue;
import org.openhab.core.library.types.OnOffType;
* @author Anton Kharuzhy - Initial contribution
*/
@SuppressWarnings("ALL")
+@NonNullByDefault
public class FanTests extends AbstractComponentTests {
public static final String CONFIG_TOPIC = "fan/0x0000000000000000_fan_zigbee2mqtt";
assertPublished("zigbee2mqtt/fan/set/state", "ON_");
}
+ @Override
protected Set<String> getConfigTopics() {
return Set.of(CONFIG_TOPIC);
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
+import java.io.UncheckedIOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
-import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.homeassistant.internal.config.ChannelConfigurationTypeAdapterFactory;
import org.openhab.binding.mqtt.homeassistant.internal.config.dto.AbstractChannelConfiguration;
/**
* @author Jochen Klein - Initial contribution
*/
+@NonNullByDefault
public class HAConfigurationTests {
private Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ChannelConfigurationTypeAdapterFactory())
}
return result.toString();
} catch (IOException e) {
- throw new RuntimeException(e);
+ throw new UncheckedIOException(e);
}
}
if (device != null) {
assertThat(device.getIdentifiers(), contains("H"));
assertThat(device.getConnections(), is(notNullValue()));
- List<@NonNull Connection> connections = device.getConnections();
+ List<Connection> connections = device.getConnections();
if (connections != null) {
assertThat(connections.get(0).getType(), is("I1"));
assertThat(connections.get(0).getIdentifier(), is("I2"));
import java.util.Set;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.values.ColorValue;
import org.openhab.core.library.types.HSBType;
*
* @author Anton Kharuzhy - Initial contribution
*/
+@NonNullByDefault
public class LightTests extends AbstractComponentTests {
public static final String CONFIG_TOPIC = "light/0x0000000000000000_light_zigbee2mqtt";
assertPublished("zigbee2mqtt/light/set/state", "0,0,0");
}
+ @Override
protected Set<String> getConfigTopics() {
return Set.of(CONFIG_TOPIC);
}
import java.util.Set;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.values.OnOffValue;
import org.openhab.core.library.types.OnOffType;
* @author Anton Kharuzhy - Initial contribution
*/
@SuppressWarnings("ALL")
+@NonNullByDefault
public class LockTests extends AbstractComponentTests {
public static final String CONFIG_TOPIC = "lock/0x0000000000000000_lock_zigbee2mqtt";
import java.util.Set;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.values.NumberValue;
import org.openhab.core.library.types.QuantityType;
* @author Anton Kharuzhy - Initial contribution
*/
@SuppressWarnings("ConstantConditions")
+@NonNullByDefault
public class SensorTests extends AbstractComponentTests {
public static final String CONFIG_TOPIC = "sensor/0x0000000000000000_sensor_zigbee2mqtt";
import java.util.Set;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.values.OnOffValue;
import org.openhab.core.library.types.OnOffType;
* @author Anton Kharuzhy - Initial contribution
*/
@SuppressWarnings("ConstantConditions")
+@NonNullByDefault
public class SwitchTests extends AbstractComponentTests {
public static final String CONFIG_TOPIC = "switch/0x847127fffe11dd6a_auto_lock_zigbee2mqtt";
assertPublished("zigbee2mqtt/th1/set/auto_lock", "AUTO");
}
+ @Override
protected Set<String> getConfigTopics() {
return Set.of(CONFIG_TOPIC);
}
import java.util.Set;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.mqtt.generic.values.OnOffValue;
import org.openhab.binding.mqtt.generic.values.PercentageValue;
* @author Anton Kharuzhy - Initial contribution
*/
@SuppressWarnings("ConstantConditions")
+@NonNullByDefault
public class VacuumTests extends AbstractComponentTests {
public static final String CONFIG_TOPIC = "vacuum/rockrobo_vacuum";
assertPublished("vacuum/send_command", "custom_command");
}
+ @Override
protected Set<String> getConfigTopics() {
return Set.of(CONFIG_TOPIC);
}
*/
package org.openhab.binding.mqtt.homeassistant.internal.discovery;
-import static org.hamcrest.CoreMatchers.hasItems;
-import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Collection;
*/
@SuppressWarnings({ "ConstantConditions", "unchecked" })
@ExtendWith(MockitoExtension.class)
+@NonNullByDefault
public class HomeAssistantDiscoveryTests extends AbstractHomeAssistantTests {
- private HomeAssistantDiscovery discovery;
+ private @NonNullByDefault({}) HomeAssistantDiscovery discovery;
@BeforeEach
public void beforeEach() {
}
}
- @NonNullByDefault
private static class LatchDiscoveryListener implements DiscoveryListener {
private final CopyOnWriteArrayList<DiscoveryResult> discoveryResults = new CopyOnWriteArrayList<>();
private @Nullable CountDownLatch latch;
+ @Override
public void thingDiscovered(DiscoveryService source, DiscoveryResult result) {
discoveryResults.add(result);
if (latch != null) {
}
}
+ @Override
public void thingRemoved(DiscoveryService source, ThingUID thingUID) {
}
+ @Override
public @Nullable Collection<ThingUID> removeOlderResults(DiscoveryService source, long timestamp,
@Nullable Collection<ThingTypeUID> thingTypeUIDs, @Nullable ThingUID bridgeUID) {
return Collections.emptyList();
package org.openhab.binding.mqtt.homeassistant.internal.handler;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.timeout;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
*/
@SuppressWarnings({ "ConstantConditions" })
@ExtendWith(MockitoExtension.class)
+@NonNullByDefault
public class HomeAssistantThingHandlerTests extends AbstractHomeAssistantTests {
private static final int SUBSCRIBE_TIMEOUT = 10000;
private static final int ATTRIBUTE_RECEIVE_TIMEOUT = 2000;
private static final List<String> MQTT_TOPICS = CONFIG_TOPICS.stream()
.map(AbstractHomeAssistantTests::configTopicToMqtt).collect(Collectors.toList());
- private @Mock ThingHandlerCallback callback;
- private HomeAssistantThingHandler thingHandler;
+ private @Mock @NonNullByDefault({}) ThingHandlerCallback callbackMock;
+ private @NonNullByDefault({}) HomeAssistantThingHandler thingHandler;
@BeforeEach
public void setup() {
config.put(HandlerConfiguration.PROPERTY_BASETOPIC, HandlerConfiguration.DEFAULT_BASETOPIC);
config.put(HandlerConfiguration.PROPERTY_TOPICS, CONFIG_TOPICS);
- when(callback.getBridge(eq(BRIDGE_UID))).thenReturn(bridgeThing);
+ when(callbackMock.getBridge(eq(BRIDGE_UID))).thenReturn(bridgeThing);
thingHandler = new HomeAssistantThingHandler(haThing, channelTypeProvider, transformationServiceProvider,
SUBSCRIBE_TIMEOUT, ATTRIBUTE_RECEIVE_TIMEOUT);
thingHandler.setConnection(bridgeConnection);
- thingHandler.setCallback(callback);
+ thingHandler.setCallback(callbackMock);
thingHandler = spy(thingHandler);
}
// When initialize
thingHandler.initialize();
- verify(callback).statusUpdated(eq(haThing), any());
+ verify(callbackMock).statusUpdated(eq(haThing), any());
// Expect a call to the bridge status changed, the start, the propertiesChanged method
verify(thingHandler).bridgeStatusChanged(any());
verify(thingHandler, timeout(SUBSCRIBE_TIMEOUT)).start(any());
package org.openhab.binding.mqtt.homie.generic.internal;
import java.util.Set;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
-import org.openhab.binding.mqtt.generic.MqttChannelStateDescriptionProvider;
import org.openhab.binding.mqtt.generic.MqttChannelTypeProvider;
import org.openhab.binding.mqtt.generic.TransformationServiceProvider;
import org.openhab.binding.mqtt.homie.internal.handler.HomieThingHandler;
@NonNullByDefault
public class MqttThingHandlerFactory extends BaseThingHandlerFactory implements TransformationServiceProvider {
private @NonNullByDefault({}) MqttChannelTypeProvider typeProvider;
- private @NonNullByDefault({}) MqttChannelStateDescriptionProvider stateDescriptionProvider;
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Stream
- .of(MqttBindingConstants.HOMIE300_MQTT_THING).collect(Collectors.toSet());
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(MqttBindingConstants.HOMIE300_MQTT_THING);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
super.deactivate(componentContext);
}
- @Reference
- protected void setStateDescriptionProvider(MqttChannelStateDescriptionProvider stateDescription) {
- this.stateDescriptionProvider = stateDescription;
- }
-
- protected void unsetStateDescriptionProvider(MqttChannelStateDescriptionProvider stateDescription) {
- this.stateDescriptionProvider = null;
- }
-
@Reference
protected void setChannelProvider(MqttChannelTypeProvider provider) {
this.typeProvider = provider;
import java.util.ArrayList;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
CompletableFuture<@Nullable Void> applyNodes(MqttBrokerConnection connection, ScheduledExecutorService scheduler,
int timeout) {
- return nodes.apply(attributes.nodes, node -> node.subscribe(connection, scheduler, timeout), this::createNode,
- this::notifyNodeRemoved).exceptionally(e -> {
+ return nodes.apply(Objects.requireNonNull(attributes.nodes),
+ node -> node.subscribe(connection, scheduler, timeout), this::createNode, this::notifyNodeRemoved)
+ .exceptionally(e -> {
logger.warn("Could not subscribe", e);
return null;
});
* @return Returns a list of relative topics
*/
public List<String> getRetainedTopics() {
- List<String> topics = new ArrayList<>();
+ List<String> topics = new ArrayList<>(Stream.of(this.attributes.getClass().getDeclaredFields())
+ .map(f -> String.format("%s/$%s", this.deviceID, f.getName())).collect(Collectors.toList()));
- topics.addAll(Stream.of(this.attributes.getClass().getDeclaredFields()).map(f -> {
- return String.format("%s/$%s", this.deviceID, f.getName());
- }).collect(Collectors.toList()));
-
- this.nodes.stream().map(n -> n.getRetainedTopics().stream().map(a -> {
- return String.format("%s/%s", this.deviceID, a);
- }).collect(Collectors.toList())).collect(Collectors.toList()).forEach(topics::addAll);
+ this.nodes.stream().map(n -> n.getRetainedTopics().stream().map(a -> String.format("%s/%s", this.deviceID, a))
+ .collect(Collectors.toList())).collect(Collectors.toList()).forEach(topics::addAll);
return topics;
}
*/
package org.openhab.binding.mqtt.homie.internal.homie300;
-import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.mqtt.generic.mapping.AbstractMqttAttributeClass;
import org.openhab.binding.mqtt.generic.mapping.MQTTvalueTransform;
import org.openhab.binding.mqtt.generic.mapping.MandatoryField;
* @author David Graeff - Initial contribution
*/
@TopicPrefix
+@NonNullByDefault
public class DeviceAttributes extends AbstractMqttAttributeClass {
// Lower-case enum value names required. Those are identifiers for the MQTT/homie protocol.
public enum ReadyState {
alert
}
- public @MandatoryField String homie;
- public @MandatoryField String name;
+ public @MandatoryField @Nullable String homie;
+ public @MandatoryField @Nullable String name;
public @MandatoryField ReadyState state = ReadyState.unknown;
- public @MandatoryField @MQTTvalueTransform(splitCharacter = ",") String[] nodes;
+ public @MandatoryField @MQTTvalueTransform(splitCharacter = ",") String @Nullable [] nodes;
@Override
- public @NonNull Object getFieldsOf() {
+ public Object getFieldsOf() {
return this;
}
}
import java.util.ArrayList;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
protected CompletableFuture<@Nullable Void> applyProperties(MqttBrokerConnection connection,
ScheduledExecutorService scheduler, int timeout) {
- return properties.apply(attributes.properties, prop -> prop.subscribe(connection, scheduler, timeout),
- this::createProperty, this::notifyPropertyRemoved).exceptionally(e -> {
+ return properties.apply(Objects.requireNonNull(attributes.properties),
+ prop -> prop.subscribe(connection, scheduler, timeout), this::createProperty,
+ this::notifyPropertyRemoved).exceptionally(e -> {
logger.warn("Could not subscribe", e);
return null;
});
// Special case: Not all fields were known before
if (!attributes.isComplete()) {
attributesReceived(connection, scheduler, 500);
- } else {
- if ("properties".equals(name)) {
- applyProperties(connection, scheduler, 500);
- }
+ } else if ("properties".equals(name)) {
+ applyProperties(connection, scheduler, 500);
}
callback.nodeAddedOrChanged(this);
}
* @return Returns a list of relative topics
*/
public List<String> getRetainedTopics() {
- List<String> topics = new ArrayList<>();
+ List<String> topics = new ArrayList<>(Stream.of(this.attributes.getClass().getDeclaredFields())
+ .map(f -> String.format("%s/$%s", this.nodeID, f.getName())).collect(Collectors.toList()));
- topics.addAll(Stream.of(this.attributes.getClass().getDeclaredFields()).map(f -> {
- return String.format("%s/$%s", this.nodeID, f.getName());
- }).collect(Collectors.toList()));
-
- this.properties.stream().map(p -> p.getRetainedTopics().stream().map(a -> {
- return String.format("%s/%s", this.nodeID, a);
- }).collect(Collectors.toList())).collect(Collectors.toList()).forEach(topics::addAll);
+ this.properties.stream().map(p -> p.getRetainedTopics().stream()
+ .map(a -> String.format("%s/%s", this.nodeID, a)).collect(Collectors.toList()))
+ .collect(Collectors.toList()).forEach(topics::addAll);
return topics;
}
*/
package org.openhab.binding.mqtt.homie.internal.homie300;
-import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.mqtt.generic.mapping.AbstractMqttAttributeClass;
import org.openhab.binding.mqtt.generic.mapping.MQTTvalueTransform;
import org.openhab.binding.mqtt.generic.mapping.MandatoryField;
* @author David Graeff - Initial contribution
*/
@TopicPrefix
+@NonNullByDefault
public class NodeAttributes extends AbstractMqttAttributeClass {
- public @MandatoryField String name;
- public @MandatoryField @MQTTvalueTransform(splitCharacter = ",") String[] properties;
+ public @MandatoryField String name = "";
+ public @MandatoryField @MQTTvalueTransform(splitCharacter = ",") String @Nullable [] properties;
// Type has no meaning yet and is currently purely of textual, descriptive nature
- public String type;
+ public @Nullable String type;
@Override
- public @NonNull Object getFieldsOf() {
+ public Object getFieldsOf() {
return this;
}
}
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
+@NonNullByDefault
public class HomieChildMapTests {
- private @Mock DeviceCallback callback;
+ private @Mock @NonNullByDefault({}) DeviceCallback callbackMock;
private final String deviceID = ThingChannelConstants.TEST_HOMIE_THING.getId();
private final String deviceTopic = "homie/" + deviceID;
ChildMap<Node> subject = new ChildMap<>();
private Node createNode(String id) {
- Node node = new Node(deviceTopic, id, ThingChannelConstants.TEST_HOMIE_THING, callback,
+ Node node = new Node(deviceTopic, id, ThingChannelConstants.TEST_HOMIE_THING, callbackMock,
spy(new NodeAttributes()));
doReturn(future).when(node.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
doReturn(future).when(node.attributes).unsubscribe();
}
private void removedNode(Node node) {
- callback.nodeRemoved(node);
+ callbackMock.nodeRemoved(node);
}
public static class AddedAction implements Function<Node, CompletableFuture<Void>> {
Node soonToBeRemoved = subject.get("def");
subject.apply(new String[] { "abc" }, addedAction, this::createNode, this::removedNode);
- verify(callback).nodeRemoved(eq(soonToBeRemoved));
+ verify(callbackMock).nodeRemoved(eq(soonToBeRemoved));
}
}
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
-import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
+@NonNullByDefault
public class HomieThingHandlerTests {
- private Thing thing;
+ private @Mock @NonNullByDefault({}) AbstractBrokerHandler bridgeHandlerMock;
+ private @Mock @NonNullByDefault({}) ThingHandlerCallback callbackMock;
+ private @Mock @NonNullByDefault({}) MqttBrokerConnection connectionMock;
+ private @Mock @NonNullByDefault({}) ScheduledExecutorService schedulerMock;
+ private @Mock @NonNullByDefault({}) ScheduledFuture<?> scheduledFutureMock;
+ private @Mock @NonNullByDefault({}) ThingTypeRegistry thingTypeRegistryMock;
- private @Mock AbstractBrokerHandler bridgeHandler;
- private @Mock ThingHandlerCallback callback;
- private @Mock MqttBrokerConnection connection;
- private @Mock ScheduledExecutorService scheduler;
- private @Mock ScheduledFuture<?> scheduledFuture;
- private @Mock ThingTypeRegistry thingTypeRegistry;
+ private @NonNullByDefault({}) Thing thing;
+ private @NonNullByDefault({}) HomieThingHandler thingHandler;
- private HomieThingHandler thingHandler;
-
- private final MqttChannelTypeProvider channelTypeProvider = new MqttChannelTypeProvider(thingTypeRegistry);
+ private final MqttChannelTypeProvider channelTypeProvider = new MqttChannelTypeProvider(thingTypeRegistryMock);
private final String deviceID = ThingChannelConstants.TEST_HOMIE_THING.getId();
private final String deviceTopic = "homie/" + deviceID;
thing.setStatusInfo(thingStatus);
// Return the mocked connection object if the bridge handler is asked for it
- when(bridgeHandler.getConnectionAsync()).thenReturn(CompletableFuture.completedFuture(connection));
+ when(bridgeHandlerMock.getConnectionAsync()).thenReturn(CompletableFuture.completedFuture(connectionMock));
- doReturn(CompletableFuture.completedFuture(true)).when(connection).subscribe(any(), any());
- doReturn(CompletableFuture.completedFuture(true)).when(connection).unsubscribe(any(), any());
- doReturn(CompletableFuture.completedFuture(true)).when(connection).unsubscribeAll();
- doReturn(CompletableFuture.completedFuture(true)).when(connection).publish(any(), any(), anyInt(),
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).subscribe(any(), any());
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).unsubscribe(any(), any());
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).unsubscribeAll();
+ doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).publish(any(), any(), anyInt(),
anyBoolean());
- doReturn(false).when(scheduledFuture).isDone();
- doReturn(scheduledFuture).when(scheduler).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ doReturn(false).when(scheduledFutureMock).isDone();
+ doReturn(scheduledFutureMock).when(schedulerMock).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
final HomieThingHandler handler = new HomieThingHandler(thing, channelTypeProvider, 1000, 30, 5);
thingHandler = spy(handler);
- thingHandler.setCallback(callback);
+ thingHandler.setCallback(callbackMock);
final Device device = new Device(thing.getUID(), thingHandler, spy(new DeviceAttributes()),
spy(new ChildMap<>()));
- thingHandler.setInternalObjects(spy(device), spy(new DelayedBatchProcessing<>(500, thingHandler, scheduler)));
+ thingHandler.setInternalObjects(spy(device),
+ spy(new DelayedBatchProcessing<>(500, thingHandler, schedulerMock)));
// Return the bridge handler if the thing handler asks for it
- doReturn(bridgeHandler).when(thingHandler).getBridgeHandler();
+ doReturn(bridgeHandlerMock).when(thingHandler).getBridgeHandler();
// We are by default online
doReturn(thingStatus).when(thingHandler).getBridgeStatus();
// Pretend that a device state change arrived.
thingHandler.device.attributes.state = ReadyState.ready;
- verify(callback, times(0)).statusUpdated(eq(thing), any());
+ verify(callbackMock, times(0)).statusUpdated(eq(thing), any());
thingHandler.initialize();
assertThat(thingHandler.device.isInitialized(), is(true));
- verify(callback).statusUpdated(eq(thing), argThat((arg) -> arg.getStatus().equals(ThingStatus.ONLINE)
- && arg.getStatusDetail().equals(ThingStatusDetail.NONE)));
+ verify(callbackMock).statusUpdated(eq(thing), argThat(arg -> ThingStatus.ONLINE.equals(arg.getStatus())
+ && ThingStatusDetail.NONE.equals(arg.getStatusDetail())));
}
@Test
thingHandler.initialize();
- verify(callback).statusUpdated(eq(thing), argThat((arg) -> arg.getStatus().equals(ThingStatus.OFFLINE)
- && arg.getStatusDetail().equals(ThingStatusDetail.COMMUNICATION_ERROR)));
+ verify(callbackMock).statusUpdated(eq(thing), argThat(arg -> ThingStatus.OFFLINE.equals(arg.getStatus())
+ && ThingStatusDetail.COMMUNICATION_ERROR.equals(arg.getStatusDetail())));
}
@Test
thingHandler.initialize();
assertThat(thingHandler.device.isInitialized(), is(true));
- verify(callback).statusUpdated(eq(thing), argThat((arg) -> arg.getStatus().equals(ThingStatus.OFFLINE)
- && arg.getStatusDetail().equals(ThingStatusDetail.GONE)));
+ verify(callbackMock).statusUpdated(eq(thing), argThat(arg -> ThingStatus.OFFLINE.equals(arg.getStatus())
+ && ThingStatusDetail.GONE.equals(arg.getStatusDetail())));
}
@SuppressWarnings("null")
node.properties.put(property.propertyID, property);
thingHandler.device.nodes.put(node.nodeID, node);
- ThingHandlerHelper.setConnection(thingHandler, connection);
+ ThingHandlerHelper.setConnection(thingHandler, connectionMock);
// we need to set a channel value first, undefined values ignored on REFRESH
property.getChannelState().getCache().update(new StringType("testString"));
thingHandler.handleCommand(property.channelUID, RefreshType.REFRESH);
- verify(callback).stateUpdated(argThat(arg -> property.channelUID.equals(arg)),
+ verify(callbackMock).stateUpdated(argThat(arg -> property.channelUID.equals(arg)),
argThat(arg -> property.getChannelState().getCache().getChannelState().equals(arg)));
}
ChannelState channelState = requireNonNull(property.getChannelState());
assertNotNull(channelState);
- ChannelStateHelper.setConnection(channelState, connection);// Pretend we called start()
- ThingHandlerHelper.setConnection(thingHandler, connection);
+ ChannelStateHelper.setConnection(channelState, connectionMock);// Pretend we called start()
+ ThingHandlerHelper.setConnection(thingHandler, connectionMock);
StringType updateValue = new StringType("UPDATE");
thingHandler.handleCommand(property.channelUID, updateValue);
assertThat(property.getChannelState().getCache().getChannelState().toString(), is("UPDATE"));
- verify(connection, times(1)).publish(any(), any(), anyInt(), anyBoolean());
+ verify(connectionMock, times(1)).publish(any(), any(), anyInt(), anyBoolean());
// Check non writable property
property.attributes.settable = false;
thingHandler.handleCommand(property.channelUID, updateValue);
// Expect old value and no MQTT publish
assertThat(property.getChannelState().getCache().getChannelState().toString(), is("OLDVALUE"));
- verify(connection, times(1)).publish(any(), any(), anyInt(), anyBoolean());
+ verify(connectionMock, times(1)).publish(any(), any(), anyInt(), anyBoolean());
}
}
@Test
public void propertiesChanged() throws InterruptedException, ExecutionException {
thingHandler.device.initialize("homie", "device", new ArrayList<>());
- ThingHandlerHelper.setConnection(thingHandler, connection);
+ ThingHandlerHelper.setConnection(thingHandler, connectionMock);
// Create mocked homie device tree with one node and one property
doAnswer(this::createSubscriberAnswer).when(thingHandler.device.attributes).createSubscriber(any(), any(),
thingHandler.delayedProcessing.forceProcessNow();
// Called for the updated property + for the new channels
- verify(callback, atLeast(2)).thingUpdated(any());
+ verify(callbackMock, atLeast(2)).thingUpdated(any());
- final List<@NonNull Channel> channels = thingHandler.getThing().getChannels();
+ final List<Channel> channels = thingHandler.getThing().getChannels();
assertThat(channels.size(), is(1));
assertThat(channels.get(0).getLabel(), is("testprop"));
assertThat(channels.get(0).getKind(), is(ChannelKind.STATE));
- final Map<@NonNull String, @NonNull String> properties = thingHandler.getThing().getProperties();
+ final Map<String, String> properties = thingHandler.getThing().getProperties();
assertThat(properties.get(MqttBindingConstants.HOMIE_PROPERTY_VERSION), is("3.0"));
assertThat(properties.size(), is(1));
}
*/
package org.openhab.binding.mqtt.homie.internal.handler;
-import static org.openhab.binding.mqtt.homie.generic.internal.MqttBindingConstants.*;
+import static org.openhab.binding.mqtt.homie.generic.internal.MqttBindingConstants.HOMIE300_MQTT_THING;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.thing.ThingUID;
/**
*
* @author David Graeff - Initial contribution
*/
+@NonNullByDefault
public class ThingChannelConstants {
public static final ThingUID TEST_HOMIE_THING = new ThingUID(HOMIE300_MQTT_THING, "device123");
}
try {
Pin pin;
if (config.certificate.isBlank()) {
- pin = Pin.LearningPin(PinType.CERTIFICATE_TYPE);
+ pin = Pin.learningPin(PinType.CERTIFICATE_TYPE);
} else {
String[] split = config.certificate.split(":");
if (split.length != 2) {
throw new NoSuchAlgorithmException("Algorithm is missing");
}
- pin = Pin.CheckingPin(PinType.CERTIFICATE_TYPE, new PinMessageDigest(split[0]),
+ pin = Pin.checkingPin(PinType.CERTIFICATE_TYPE, new PinMessageDigest(split[0]),
HexUtils.hexToBytes(split[1]));
}
trustManager.addPinning(pin);
try {
Pin pin;
if (config.publickey.isBlank()) {
- pin = Pin.LearningPin(PinType.PUBLIC_KEY_TYPE);
+ pin = Pin.learningPin(PinType.PUBLIC_KEY_TYPE);
} else {
String[] split = config.publickey.split(":");
if (split.length != 2) {
throw new NoSuchAlgorithmException("Algorithm is missing");
}
- pin = Pin.CheckingPin(PinType.PUBLIC_KEY_TYPE, new PinMessageDigest(split[0]),
+ pin = Pin.checkingPin(PinType.PUBLIC_KEY_TYPE, new PinMessageDigest(split[0]),
HexUtils.hexToBytes(split[1]));
}
trustManager.addPinning(pin);
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerFactory;
import org.osgi.service.component.annotations.Component;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* The {@link MqttBrokerHandlerFactory} is responsible for creating things and thing
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Stream
.of(MqttBindingConstants.BRIDGE_TYPE_BROKER).collect(Collectors.toSet());
- private final Logger logger = LoggerFactory.getLogger(MqttBrokerHandlerFactory.class);
-
/**
* This Map provides a lookup between a Topic string (key) and a Set of MQTTTopicDiscoveryParticipants (value),
* where the Set itself is a list of participants which are subscribed to the respective Topic.
*/
package org.openhab.binding.mqtt.internal;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.mqtt.MqttBindingConstants;
import org.openhab.core.thing.ThingUID;
*
* @author David Graeff - Initial contribution
*/
+@NonNullByDefault
public class MqttThingID {
/**
* Convert the url (tcp://122.123.111.123:1883) to a version without colons, dots or slashes
this.pinData = data;
}
- public static Pin LearningPin(PinType pinType) {
+ public static Pin learningPin(PinType pinType) {
return new Pin(pinType, null, true, null);
}
- public static Pin CheckingPin(PinType pinType, PinMessageDigest method, byte[] pinData) {
+ public static Pin checkingPin(PinType pinType, PinMessageDigest method, byte[] pinData) {
return new Pin(pinType, method, false, pinData);
}
*/
package org.openhab.binding.mqtt.internal.ssl;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+
/**
* A {@link Pin} is either a Public Key or Certificate Pin.
*
* @author David Graeff - Initial contribution
*/
+@NonNullByDefault
public enum PinType {
PUBLIC_KEY_TYPE,
CERTIFICATE_TYPE
import static org.mockito.Mockito.verify;
-import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.mockito.Mockito;
import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
import org.openhab.core.thing.Bridge;
*
* @author David Graeff - Initial contribution
*/
+@NonNullByDefault
public class BrokerHandlerEx extends BrokerHandler {
final MqttBrokerConnectionEx e;
}
@Override
- protected @NonNull MqttBrokerConnection createBrokerConnection() throws IllegalArgumentException {
+ protected MqttBrokerConnection createBrokerConnection() throws IllegalArgumentException {
return e;
}
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
+@NonNullByDefault
public class BrokerHandlerTest extends JavaTest {
- private ScheduledExecutorService scheduler;
- private @Mock ThingHandlerCallback callback;
- private @Mock Bridge thing;
+ private @Mock @NonNullByDefault({}) ThingHandlerCallback callbackMock;
+ private @Mock @NonNullByDefault({}) Bridge thingMock;
- private MqttBrokerConnectionEx connection;
-
- private BrokerHandler handler;
+ private @NonNullByDefault({}) MqttBrokerConnectionEx connection;
+ private @NonNullByDefault({}) BrokerHandler handler;
+ private @NonNullByDefault({}) ScheduledExecutorService scheduler;
@BeforeEach
public void setUp() {
connection.setConnectionCallback(connection);
Configuration config = new Configuration();
- when(thing.getConfiguration()).thenReturn(config);
+ when(thingMock.getConfiguration()).thenReturn(config);
- handler = spy(new BrokerHandlerEx(thing, connection));
- handler.setCallback(callback);
+ handler = spy(new BrokerHandlerEx(thingMock, connection));
+ handler.setCallback(callbackMock);
}
@AfterEach
@Test
public void handlerInitWithoutUrl() throws IllegalArgumentException {
// Assume it is a real handler and not a mock as defined above
- handler = new BrokerHandler(thing);
+ handler = new BrokerHandler(thingMock);
assertThrows(IllegalArgumentException.class, this::initializeHandlerWaitForTimeout);
}
Configuration config = new Configuration();
config.put("host", "10.10.0.10");
config.put("port", 80);
- when(thing.getConfiguration()).thenReturn(config);
+ when(thingMock.getConfiguration()).thenReturn(config);
handler.initialize();
verify(handler).createBrokerConnection();
}
assertThat(initializeHandlerWaitForTimeout(), is(true));
ArgumentCaptor<ThingStatusInfo> statusInfoCaptor = ArgumentCaptor.forClass(ThingStatusInfo.class);
- verify(callback, atLeast(3)).statusUpdated(eq(thing), statusInfoCaptor.capture());
+ verify(callbackMock, atLeast(3)).statusUpdated(eq(thingMock), statusInfoCaptor.capture());
assertThat(statusInfoCaptor.getValue().getStatus(), is(ThingStatus.ONLINE));
}
import java.util.Map;
-import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
}
@Override
- public @NonNull MqttConnectionState connectionState() {
+ public MqttConnectionState connectionState() {
return connectionStateOverwrite;
}
}
import java.util.concurrent.Semaphore;
-import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.io.transport.mqtt.MqttConnectionObserver;
import org.openhab.core.io.transport.mqtt.MqttConnectionState;
*
* @author David Graeff - Initial contribution
*/
+@NonNullByDefault
public class MqttConnectionObserverEx implements MqttConnectionObserver {
public int counter = 0;
public Semaphore semaphore = new Semaphore(1);
}
@Override
- public void connectionStateChanged(@NonNull MqttConnectionState state, @Nullable Throwable error) {
+ public void connectionStateChanged(MqttConnectionState state, @Nullable Throwable error) {
// First we expect a CONNECTING state and then a DISCONNECTED state change
if (counter == 0 && state == MqttConnectionState.CONNECTING) {
counter = 1;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
+@NonNullByDefault
public class MQTTTopicDiscoveryServiceTest {
- private ScheduledExecutorService scheduler;
- private MqttBrokerHandlerFactory subject;
+ private @Mock @NonNullByDefault({}) Bridge thingMock;
+ private @Mock @NonNullByDefault({}) ThingHandlerCallback callbackMock;
+ private @Mock @NonNullByDefault({}) MQTTTopicDiscoveryParticipant listenerMock;
- @Mock
- private Bridge thing;
-
- @Mock
- private ThingHandlerCallback callback;
-
- @Mock
- MQTTTopicDiscoveryParticipant listener;
-
- private MqttBrokerConnectionEx connection;
-
- private BrokerHandler handler;
+ private @NonNullByDefault({}) MqttBrokerConnectionEx connection;
+ private @NonNullByDefault({}) BrokerHandler handler;
+ private @NonNullByDefault({}) ScheduledExecutorService scheduler;
+ private @NonNullByDefault({}) MqttBrokerHandlerFactory subject;
@BeforeEach
public void setUp() {
scheduler = new ScheduledThreadPoolExecutor(1);
- when(thing.getUID()).thenReturn(MqttThingID.getThingUID("10.10.0.10", 80));
+ when(thingMock.getUID()).thenReturn(MqttThingID.getThingUID("10.10.0.10", 80));
connection = spy(new MqttBrokerConnectionEx("10.10.0.10", 80, false, "BrokerHandlerTest"));
connection.setTimeoutExecutor(scheduler, 10);
connection.setConnectionCallback(connection);
Configuration config = new Configuration();
config.put("host", "10.10.0.10");
config.put("port", 80);
- when(thing.getConfiguration()).thenReturn(config);
+ when(thingMock.getConfiguration()).thenReturn(config);
- handler = spy(new BrokerHandlerEx(thing, connection));
- handler.setCallback(callback);
+ handler = spy(new BrokerHandlerEx(thingMock, connection));
+ handler.setCallback(callbackMock);
subject = new MqttBrokerHandlerFactory();
}
handler.initialize();
BrokerHandlerEx.verifyCreateBrokerConnection(handler, 1);
- subject.subscribe(listener, "topic");
+ subject.subscribe(listenerMock, "topic");
subject.createdHandler(handler);
- assertThat(subject.discoveryTopics.get("topic"), hasItem(listener));
+ assertThat(subject.discoveryTopics.get("topic"), hasItem(listenerMock));
// Simulate receiving
final byte[] bytes = "TEST".getBytes();
connection.getSubscribers().get("topic").messageArrived("topic", bytes, false);
- verify(listener).receivedMessage(eq(thing.getUID()), eq(connection), eq("topic"), eq(bytes));
+ verify(listenerMock).receivedMessage(eq(thingMock.getUID()), eq(connection), eq("topic"), eq(bytes));
}
@Test
BrokerHandlerEx.verifyCreateBrokerConnection(handler, 1);
subject.createdHandler(handler);
- subject.subscribe(listener, "topic");
- assertThat(subject.discoveryTopics.get("topic"), hasItem(listener));
+ subject.subscribe(listenerMock, "topic");
+ assertThat(subject.discoveryTopics.get("topic"), hasItem(listenerMock));
// Simulate receiving
final byte[] bytes = "TEST".getBytes();
connection.getSubscribers().get("topic").messageArrived("topic", bytes, false);
- verify(listener).receivedMessage(eq(thing.getUID()), eq(connection), eq("topic"), eq(bytes));
+ verify(listenerMock).receivedMessage(eq(thingMock.getUID()), eq(connection), eq("topic"), eq(bytes));
}
@Test
public void handlerInitializeAfterSubscribe() {
subject.createdHandler(handler);
- subject.subscribe(listener, "topic");
- assertThat(subject.discoveryTopics.get("topic"), hasItem(listener));
+ subject.subscribe(listenerMock, "topic");
+ assertThat(subject.discoveryTopics.get("topic"), hasItem(listenerMock));
// Init handler -> create connection
handler.initialize();
// Simulate receiving
final byte[] bytes = "TEST".getBytes();
connection.getSubscribers().get("topic").messageArrived("topic", bytes, false);
- verify(listener).receivedMessage(eq(thing.getUID()), eq(connection), eq("topic"), eq(bytes));
+ verify(listenerMock).receivedMessage(eq(thingMock.getUID()), eq(connection), eq("topic"), eq(bytes));
}
@Test
BrokerHandlerEx.verifyCreateBrokerConnection(handler, 1);
subject.createdHandler(handler);
- subject.subscribe(listener, "topic");
- assertThat(subject.discoveryTopics.get("topic"), hasItem(listener));
+ subject.subscribe(listenerMock, "topic");
+ assertThat(subject.discoveryTopics.get("topic"), hasItem(listenerMock));
// Simulate receiving
final byte[] bytes = "".getBytes();
connection.getSubscribers().get("topic").messageArrived("topic", bytes, false);
- verify(listener).topicVanished(eq(thing.getUID()), eq(connection), eq("topic"));
+ verify(listenerMock).topicVanished(eq(thingMock.getUID()), eq(connection), eq("topic"));
}
}
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
-import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.util.HexUtils;
*
* @author David Graeff - Initial contribution
*/
+@NonNullByDefault
public class PinningSSLContextProviderTest {
@Test
@Test
public void certPinCallsX509CertificateGetEncoded() throws NoSuchAlgorithmException, CertificateException {
PinTrustManager pinTrustManager = new PinTrustManager();
- pinTrustManager.addPinning(Pin.LearningPin(PinType.CERTIFICATE_TYPE));
+ pinTrustManager.addPinning(Pin.learningPin(PinType.CERTIFICATE_TYPE));
// Mock a certificate
X509Certificate certificate = mock(X509Certificate.class);
@Test
public void pubKeyPinCallsX509CertificateGetPublicKey() throws NoSuchAlgorithmException, CertificateException {
PinTrustManager pinTrustManager = new PinTrustManager();
- pinTrustManager.addPinning(Pin.LearningPin(PinType.PUBLIC_KEY_TYPE));
+ pinTrustManager.addPinning(Pin.learningPin(PinType.PUBLIC_KEY_TYPE));
// Mock a certificate
PublicKey publicKey = mock(PublicKey.class);
}
@Override
- @NonNull
- PinMessageDigest getMessageDigestForSigAlg(@NonNull String sigAlg) throws CertificateException {
+ PinMessageDigest getMessageDigestForSigAlg(String sigAlg) throws CertificateException {
return pinMessageDigest;
}
}
byte[] digestOfTestCert = pinMessageDigest.digest(testCert);
// Add a certificate pin in learning mode to a trust manager
- Pin pin = Pin.LearningPin(PinType.CERTIFICATE_TYPE);
+ Pin pin = Pin.learningPin(PinType.CERTIFICATE_TYPE);
pinTrustManager.addPinning(pin);
assertThat(pinTrustManager.pins.size(), is(1));
byte[] digestOfTestCert = pinMessageDigest.digest(testCert);
// Add a certificate pin in checking mode to a trust manager
- Pin pin = Pin.CheckingPin(PinType.CERTIFICATE_TYPE, pinMessageDigest, digestOfTestCert);
+ Pin pin = Pin.checkingPin(PinType.CERTIFICATE_TYPE, pinMessageDigest, digestOfTestCert);
pinTrustManager.addPinning(pin);
assertThat(pinTrustManager.pins.size(), is(1));