added migrated 2.x add-ons

Signed-off-by: Kai Kreuzer <kai@openhab.org>
This commit is contained in:
Kai Kreuzer
2020-09-21 01:58:32 +02:00
parent bbf1a7fd29
commit 6df6783b60
11662 changed files with 1302875 additions and 11 deletions

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.openhab.binding.ntp.tests</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,13 @@
This content is produced and maintained by the openHAB project.
* Project home: https://www.openhab.org
== Declared Project Licenses
This program and the accompanying materials are made available under the terms
of the Eclipse Public License 2.0 which is available at
https://www.eclipse.org/legal/epl-2.0/.
== Source Code
https://github.com/openhab/openhab-addons

View File

@@ -0,0 +1,57 @@
-include: ../itest-common.bndrun
Bundle-SymbolicName: ${project.artifactId}
Fragment-Host: org.openhab.binding.ntp
-runrequires: \
bnd.identity;id='org.openhab.binding.ntp.tests',\
bnd.identity;id='org.openhab.core.binding.xml',\
bnd.identity;id='org.openhab.core.thing.xml'
#
# done
#
-runbundles: \
ch.qos.logback.classic;version='[1.2.3,1.2.4)',\
ch.qos.logback.core;version='[1.2.3,1.2.4)',\
com.google.gson;version='[2.8.2,2.8.3)',\
javax.measure.unit-api;version='[1.0.0,1.0.1)',\
org.apache.commons.io;version='[2.2.0,2.2.1)',\
org.apache.commons.lang;version='[2.6.0,2.6.1)',\
org.apache.commons.net;version='[3.3.0,3.3.1)',\
org.apache.felix.configadmin;version='[1.9.8,1.9.9)',\
org.apache.felix.http.servlet-api;version='[1.1.2,1.1.3)',\
org.apache.felix.scr;version='[2.1.10,2.1.11)',\
org.eclipse.equinox.event;version='[1.4.300,1.4.301)',\
org.objenesis;version='[2.6.0,2.6.1)',\
org.openhab.core;version='[2.5.0,2.5.1)',\
org.openhab.core.config.core;version='[2.5.0,2.5.1)',\
org.openhab.core.config.discovery;version='[2.5.0,2.5.1)',\
org.openhab.core.io.console;version='[2.5.0,2.5.1)',\
org.openhab.core.test;version='[2.5.0,2.5.1)',\
org.openhab.core.thing;version='[2.5.0,2.5.1)',\
org.osgi.service.event;version='[1.4.0,1.4.1)',\
osgi.enroute.hamcrest.wrapper;version='[1.3.0,1.3.1)',\
osgi.enroute.junit.wrapper;version='[4.12.0,4.12.1)',\
slf4j.api;version='[1.7.25,1.7.26)',\
org.apache.servicemix.bundles.xstream;version='[1.4.7,1.4.8)',\
org.openhab.core.binding.xml;version='[2.5.0,2.5.1)',\
org.openhab.core.config.xml;version='[2.5.0,2.5.1)',\
org.openhab.core.thing.xml;version='[2.5.0,2.5.1)',\
org.apache.servicemix.specs.activation-api-1.1;version='[2.9.0,2.9.1)',\
org.apache.servicemix.specs.jaxb-api-2.2;version='[2.9.0,2.9.1)',\
org.apache.servicemix.specs.stax-api-1.2;version='[2.9.0,2.9.1)',\
tec.uom.lib.uom-lib-common;version='[1.0.3,1.0.4)',\
tec.uom.se;version='[1.0.10,1.0.11)',\
org.apache.servicemix.bundles.jaxb-impl;version='[2.2.11,2.2.12)',\
net.bytebuddy.byte-buddy;version='[1.9.10,1.9.11)',\
net.bytebuddy.byte-buddy-agent;version='[1.9.10,1.9.11)',\
org.mockito.mockito-core;version='[3.1.0,3.1.1)',\
org.eclipse.jetty.http;version='[9.4.20,9.4.21)',\
org.eclipse.jetty.io;version='[9.4.20,9.4.21)',\
org.eclipse.jetty.security;version='[9.4.20,9.4.21)',\
org.eclipse.jetty.server;version='[9.4.20,9.4.21)',\
org.eclipse.jetty.servlet;version='[9.4.20,9.4.21)',\
org.eclipse.jetty.util;version='[9.4.20,9.4.21)',\
org.openhab.binding.ntp;version='[2.5.9,2.5.10)',\
org.openhab.binding.ntp.tests;version='[2.5.9,2.5.10)'

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.openhab.addons.itests</groupId>
<artifactId>org.openhab.addons.reactor.itests</artifactId>
<version>3.0.0-SNAPSHOT</version>
</parent>
<artifactId>org.openhab.binding.ntp.tests</artifactId>
<name>openHAB Add-ons :: Integration Tests :: NTP Binding Tests</name>
<dependencies>
<dependency>
<groupId>org.openhab.addons.bundles</groupId>
<artifactId>org.openhab.binding.ntp</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.openhab.addons.itests</groupId>
<artifactId>org.openhab.addons.reactor.itests</artifactId>
<version>2.5.9-SNAPSHOT</version>
</parent>
<artifactId>org.openhab.binding.ntp.tests</artifactId>
<name>openHAB Add-ons :: Integration Tests :: NTP Binding Tests</name>
<dependencies>
<dependency>
<groupId>org.openhab.addons.bundles</groupId>
<artifactId>org.openhab.binding.ntp</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,105 @@
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.ntp.server;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import org.apache.commons.net.ntp.NtpV3Impl;
import org.apache.commons.net.ntp.NtpV3Packet;
import org.apache.commons.net.ntp.TimeStamp;
import org.openhab.binding.ntp.test.NtpOSGiTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is a simple NTP server which provides timestamps to the {@link NtpOSGiTest} tests.
* Its main purpose is to remove the dependence on a remote ntp server because it is hosted locally.
*
* @author Erdoan Hadzhiyusein - Initial Contribution
*
*/
public class SimpleNTPServer {
private DatagramSocket socket;
private int port;
private volatile boolean isRunning;
private byte[] array = new byte[48];
private final DatagramPacket request = new DatagramPacket(array, array.length);
private Logger logger = LoggerFactory.getLogger(SimpleNTPServer.class);
/**
* The server must use an available port to be able to start.
* According to RFC 793, the port is a 16 bit unsigned int.
*
* @param port
*/
public SimpleNTPServer(int port) {
if (port > 0 && port < 65535) {
this.port = port;
} else {
throw new IllegalArgumentException(
"Please choose an available port! This port cannot be used at the moment" + port);
}
}
/**
* This method opens a new socket and receives requests calling handleRequest() for each one.
*/
public void startServer() {
isRunning = true;
new Thread() {
@Override
public void run() {
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
logger.error("Occured an error {}. Couldn't open a socket on this port:", port, e);
}
while (isRunning) {
try {
socket.receive(request);
handleRequest(request);
} catch (IOException e) {
logger.error("There was an error {} while processing the request!", request, e);
}
}
}
}.start();
}
/**
* Stopping the server which causes closing the socket too
*/
public void stopServer() {
isRunning = false;
if (socket != null) {
socket.close(); // force closing of the socket
socket = null;
}
}
private void handleRequest(DatagramPacket requestPacket) throws IOException {
final long receivedTime = System.currentTimeMillis();
NtpV3Packet responsePacket = new NtpV3Impl();
responsePacket.setMode(NtpV3Packet.MODE_SERVER);
responsePacket.setTransmitTime(TimeStamp.getNtpTime(receivedTime));
DatagramPacket dataPacket = responsePacket.getDatagramPacket();
dataPacket.setPort(requestPacket.getPort());
dataPacket.setAddress(requestPacket.getAddress());
socket.send(dataPacket);
}
}

View File

@@ -0,0 +1,499 @@
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.ntp.test;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.commons.lang.StringUtils;
import org.openhab.core.config.core.Configuration;
import org.openhab.core.events.Event;
import org.openhab.core.events.EventSubscriber;
import org.openhab.core.items.GenericItem;
import org.openhab.core.items.Item;
import org.openhab.core.items.ItemNotFoundException;
import org.openhab.core.items.ItemRegistry;
import org.openhab.core.items.events.ItemStateEvent;
import org.openhab.core.library.CoreItemFactory;
import org.openhab.core.library.items.DateTimeItem;
import org.openhab.core.library.items.StringItem;
import org.openhab.core.library.types.DateTimeType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.thing.Channel;
import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.ManagedThingProvider;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingProvider;
import org.openhab.core.thing.ThingRegistry;
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.builder.ChannelBuilder;
import org.openhab.core.thing.binding.builder.ThingBuilder;
import org.openhab.core.thing.link.ItemChannelLink;
import org.openhab.core.thing.link.ManagedItemChannelLinkProvider;
import org.openhab.core.thing.type.ChannelKind;
import org.openhab.core.thing.type.ChannelTypeBuilder;
import org.openhab.core.thing.type.ChannelTypeProvider;
import org.openhab.core.thing.type.ChannelTypeUID;
import org.openhab.core.types.State;
import org.openhab.core.test.java.JavaOSGiTest;
import org.openhab.core.test.storage.VolatileStorageService;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.openhab.binding.ntp.internal.NtpBindingConstants;
import org.openhab.binding.ntp.internal.handler.NtpHandler;
import org.openhab.binding.ntp.server.SimpleNTPServer;
/**
* OSGi tests for the {@link NtpHandler}
*
* @author Petar Valchev - Initial Contribution
* @author Markus Rathgeb - Migrated tests from Groovy to pure Java
* @author Erdoan Hadzhiyusein - Migrated tests to Java 8 and integrated the new DateTimeType
*/
public class NtpOSGiTest extends JavaOSGiTest {
private static TimeZone systemTimeZone;
private static Locale locale;
private NtpHandler ntpHandler;
private Thing ntpThing;
private GenericItem testItem;
private ManagedThingProvider managedThingProvider;
private ThingRegistry thingRegistry;
private ItemRegistry itemRegistry;
private ChannelTypeProvider channelTypeProvider;
private static final ZoneId DEFAULT_TIME_ZONE_ID = ZoneId.of("Europe/Bucharest");
private static final String TEST_TIME_ZONE_ID = "America/Los_Angeles";
private static final String TEST_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss z";
private static final String TEST_ITEM_NAME = "testItem";
private static final String TEST_THING_ID = "testThingId";
// No bundle in ESH is exporting a package from which we can use item types
// as constants, so we will use String.
private static final String ACCEPTED_ITEM_TYPE_STRING = "String";
private static final String ACCEPTED_ITEM_TYPE_DATE_TIME = "DateTime";
private static final String TEST_HOSTNAME = "127.0.0.1";
private static final int TEST_PORT = 9002;
static SimpleNTPServer timeServer;
private ChannelTypeUID channelTypeUID;
enum UpdateEventType {
HANDLE_COMMAND("handleCommand"),
CHANNEL_LINKED("channelLinked");
private final String updateEventType;
private UpdateEventType(String updateEventType) {
this.updateEventType = updateEventType;
}
public String getUpdateEventType() {
return updateEventType;
}
}
@BeforeClass
public static void setUpClass() {
// Initializing a new local server on this port
timeServer = new SimpleNTPServer(TEST_PORT);
// Starting the local server
timeServer.startServer();
/*
* Store the initial system time zone and locale value, so that we can
* restore them at the test end.
*/
systemTimeZone = TimeZone.getDefault();
locale = Locale.getDefault();
/*
* Set new default time zone and locale, which will be used during the
* tests execution.
*/
TimeZone.setDefault(TimeZone.getTimeZone(DEFAULT_TIME_ZONE_ID));
Locale.setDefault(Locale.US);
}
@Before
public void setUp() {
VolatileStorageService volatileStorageService = new VolatileStorageService();
registerService(volatileStorageService);
managedThingProvider = getService(ThingProvider.class, ManagedThingProvider.class);
assertNotNull(managedThingProvider);
thingRegistry = getService(ThingRegistry.class);
assertNotNull(thingRegistry);
itemRegistry = getService(ItemRegistry.class);
assertNotNull(itemRegistry);
channelTypeUID = new ChannelTypeUID(NtpBindingConstants.BINDING_ID + ":channelType");
channelTypeProvider = mock(ChannelTypeProvider.class);
when(channelTypeProvider.getChannelType(any(ChannelTypeUID.class), any(Locale.class)))
.thenReturn(ChannelTypeBuilder.state(channelTypeUID, "label", CoreItemFactory.SWITCH).build());
registerService(channelTypeProvider);
}
@After
public void tearDown() {
if (ntpThing != null) {
Thing removedThing = thingRegistry.forceRemove(ntpThing.getUID());
assertNotNull(removedThing);
}
if (testItem != null) {
itemRegistry.remove(TEST_ITEM_NAME);
}
}
@AfterClass
public static void tearDownClass() {
// Stopping the local time server
timeServer.stopServer();
// Set the default time zone and locale to their initial value.
TimeZone.setDefault(systemTimeZone);
Locale.setDefault(locale);
}
@Test
public void testStringChannelTimeZoneUpdate() {
final String expectedTimeZonePDT = "PDT";
final String expectedTimeZonePST = "PST";
Configuration configuration = new Configuration();
configuration.put(NtpBindingConstants.PROPERTY_TIMEZONE, TEST_TIME_ZONE_ID);
Configuration channelConfig = new Configuration();
/*
* Set the format of the date, so it is updated in the item registry in
* a format from which we can easily get the time zone.
*/
channelConfig.put(NtpBindingConstants.PROPERTY_DATE_TIME_FORMAT, TEST_DATE_TIME_FORMAT);
initialize(configuration, NtpBindingConstants.CHANNEL_STRING, ACCEPTED_ITEM_TYPE_STRING, channelConfig, null);
String timeZoneFromItemRegistry = getStringChannelTimeZoneFromItemRegistry();
assertThat(timeZoneFromItemRegistry, is(anyOf(equalTo(expectedTimeZonePDT), equalTo(expectedTimeZonePST))));
}
@Test
public void testDateTimeChannelTimeZoneUpdate() {
Configuration configuration = new Configuration();
configuration.put(NtpBindingConstants.PROPERTY_TIMEZONE, TEST_TIME_ZONE_ID);
initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null, null);
String testItemState = getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME).toString();
assertFormat(testItemState, DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS);
ZonedDateTime timeZoneFromItemRegistry = ((DateTimeType) getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME))
.getZonedDateTime();
ZoneOffset expectedOffset = ZoneId.of(TEST_TIME_ZONE_ID).getRules()
.getOffset(timeZoneFromItemRegistry.toInstant());
assertEquals(expectedOffset, timeZoneFromItemRegistry.getOffset());
}
@Test
public void testDateTimeChannelCalendarTimeZoneUpdate() {
Configuration configuration = new Configuration();
configuration.put(NtpBindingConstants.PROPERTY_TIMEZONE, TEST_TIME_ZONE_ID);
initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null, null);
ZonedDateTime timeZoneIdFromItemRegistry = ((DateTimeType) getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME))
.getZonedDateTime();
ZoneOffset expectedOffset = ZoneId.of(TEST_TIME_ZONE_ID).getRules()
.getOffset(timeZoneIdFromItemRegistry.toInstant());
assertEquals(expectedOffset, timeZoneIdFromItemRegistry.getOffset());
}
@Test
public void testStringChannelDefaultTimeZoneUpdate() {
final String expectedTimeZoneEEST = "EEST";
final String expectedTimeZoneEET = "EET";
Configuration configuration = new Configuration();
Configuration channelConfig = new Configuration();
/*
* Set the format of the date, so it is updated in the item registry in
* a format from which we can easily get the time zone.
*/
channelConfig.put(NtpBindingConstants.PROPERTY_DATE_TIME_FORMAT, TEST_DATE_TIME_FORMAT);
// Initialize with configuration with no time zone property set.
initialize(configuration, NtpBindingConstants.CHANNEL_STRING, ACCEPTED_ITEM_TYPE_STRING, null, null);
String timeZoneFromItemRegistry = getStringChannelTimeZoneFromItemRegistry();
assertThat(timeZoneFromItemRegistry, is(anyOf(equalTo(expectedTimeZoneEEST), equalTo(expectedTimeZoneEET))));
}
@Test
public void testDateTimeChannelDefaultTimeZoneUpdate() {
ZonedDateTime zoned = ZonedDateTime.now();
ZoneOffset expectedTimeZone = zoned.getOffset();
Configuration configuration = new Configuration();
// Initialize with configuration with no time zone property set.
initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null, null);
String testItemState = getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME).toString();
assertFormat(testItemState, DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS);
ZoneOffset timeZoneFromItemRegistry = new DateTimeType(testItemState).getZonedDateTime().getOffset();
assertEquals(expectedTimeZone, timeZoneFromItemRegistry);
}
@Test
@Ignore("https://github.com/eclipse/smarthome/issues/5224")
public void testDateTimeChannelCalendarDefaultTimeZoneUpdate() {
Configuration configuration = new Configuration();
// Initialize with configuration with no time zone property set.
initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null, null);
ZonedDateTime timeZoneIdFromItemRegistry = ((DateTimeType) getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME))
.getZonedDateTime();
ZoneOffset expectedOffset = ZoneId.systemDefault().getRules().getOffset(timeZoneIdFromItemRegistry.toInstant());
assertEquals(expectedOffset, timeZoneIdFromItemRegistry.getOffset());
}
@Test
public void testStringChannelFormatting() {
final String formatPattern = "EEE, d MMM yyyy HH:mm:ss z";
Configuration configuration = new Configuration();
Configuration channelConfig = new Configuration();
channelConfig.put(NtpBindingConstants.PROPERTY_DATE_TIME_FORMAT, formatPattern);
initialize(configuration, NtpBindingConstants.CHANNEL_STRING, ACCEPTED_ITEM_TYPE_STRING, channelConfig, null);
String dateFromItemRegistry = getItemState(ACCEPTED_ITEM_TYPE_STRING).toString();
assertFormat(dateFromItemRegistry, formatPattern);
}
@Test
public void testStringChannelDefaultFormatting() {
Configuration configuration = new Configuration();
// Initialize with configuration with no property for formatting set.
initialize(configuration, NtpBindingConstants.CHANNEL_STRING, ACCEPTED_ITEM_TYPE_STRING, null, null);
String dateFromItemRegistryString = getItemState(ACCEPTED_ITEM_TYPE_STRING).toString();
assertFormat(dateFromItemRegistryString, NtpHandler.DATE_PATTERN_WITH_TZ);
}
@Test
public void testEmptyStringPropertyFormatting() {
Configuration configuration = new Configuration();
Configuration channelConfig = new Configuration();
// Empty string
channelConfig.put(NtpBindingConstants.PROPERTY_DATE_TIME_FORMAT, "");
initialize(configuration, NtpBindingConstants.CHANNEL_STRING, ACCEPTED_ITEM_TYPE_STRING, channelConfig, null);
String dateFromItemRegistry = getItemState(ACCEPTED_ITEM_TYPE_STRING).toString();
assertFormat(dateFromItemRegistry, NtpHandler.DATE_PATTERN_WITH_TZ);
}
@Test
public void testNullPropertyFormatting() {
Configuration configuration = new Configuration();
Configuration channelConfig = new Configuration();
channelConfig.put(NtpBindingConstants.PROPERTY_DATE_TIME_FORMAT, null);
initialize(configuration, NtpBindingConstants.CHANNEL_STRING, ACCEPTED_ITEM_TYPE_STRING, channelConfig, null);
String dateFromItemRegistry = getItemState(ACCEPTED_ITEM_TYPE_STRING).toString();
assertFormat(dateFromItemRegistry, NtpHandler.DATE_PATTERN_WITH_TZ);
}
@Test
public void testDateTimeChannelWithUnknownHost() {
assertCommunicationError(ACCEPTED_ITEM_TYPE_DATE_TIME);
}
@Test
public void testStringChannelWithUnknownHost() {
assertCommunicationError(ACCEPTED_ITEM_TYPE_STRING);
}
@Test
public void testStringChannelHandleCommand() {
assertEventIsReceived(UpdateEventType.HANDLE_COMMAND, NtpBindingConstants.CHANNEL_STRING,
ACCEPTED_ITEM_TYPE_STRING);
}
@Test
public void testDateTimeChannelHandleCommand() {
assertEventIsReceived(UpdateEventType.HANDLE_COMMAND, NtpBindingConstants.CHANNEL_DATE_TIME,
ACCEPTED_ITEM_TYPE_DATE_TIME);
}
@Test
public void testStringChannelLinking() {
assertEventIsReceived(UpdateEventType.CHANNEL_LINKED, NtpBindingConstants.CHANNEL_STRING,
ACCEPTED_ITEM_TYPE_STRING);
}
@Test
public void testDateTimeChannelLinking() {
assertEventIsReceived(UpdateEventType.CHANNEL_LINKED, NtpBindingConstants.CHANNEL_DATE_TIME,
ACCEPTED_ITEM_TYPE_DATE_TIME);
}
private void initialize(Configuration configuration, String channelID, String acceptedItemType,
Configuration channelConfiguration, String wrongHostname) {
// There are 2 tests which require wrong hostnames.
boolean isWrongHostNameTest = wrongHostname != null;
if (isWrongHostNameTest) {
configuration.put(NtpBindingConstants.PROPERTY_NTP_SERVER_HOST, wrongHostname);
} else {
configuration.put(NtpBindingConstants.PROPERTY_NTP_SERVER_HOST, TEST_HOSTNAME);
}
initialize(configuration, channelID, acceptedItemType, channelConfiguration);
}
private void initialize(Configuration configuration, String channelID, String acceptedItemType,
Configuration channelConfiguration) {
configuration.put(NtpBindingConstants.PROPERTY_NTP_SERVER_PORT, TEST_PORT);
ThingUID ntpUid = new ThingUID(NtpBindingConstants.THING_TYPE_NTP, TEST_THING_ID);
ChannelUID channelUID = new ChannelUID(ntpUid, channelID);
Channel channel = ChannelBuilder.create(channelUID, acceptedItemType).withType(channelTypeUID)
.withConfiguration(channelConfiguration).withLabel("label").withKind(ChannelKind.STATE).build();
ntpThing = ThingBuilder.create(NtpBindingConstants.THING_TYPE_NTP, ntpUid).withConfiguration(configuration)
.withChannel(channel).build();
managedThingProvider.add(ntpThing);
// Wait for the NTP thing to be added to the ManagedThingProvider.
ntpHandler = waitForAssert(() -> {
final ThingHandler thingHandler = ntpThing.getHandler();
assertThat(thingHandler, is(instanceOf(NtpHandler.class)));
return (NtpHandler) thingHandler;
}, DFL_TIMEOUT * 3, DFL_SLEEP_TIME);
if (acceptedItemType.equals(ACCEPTED_ITEM_TYPE_STRING)) {
testItem = new StringItem(TEST_ITEM_NAME);
} else if (acceptedItemType.equals(ACCEPTED_ITEM_TYPE_DATE_TIME)) {
testItem = new DateTimeItem(TEST_ITEM_NAME);
}
itemRegistry.add(testItem);
// Wait for the item , linked to the NTP thing to be added to the
// ManagedThingProvider.
final ManagedItemChannelLinkProvider itemChannelLinkProvider = waitForAssert(() -> {
final ManagedItemChannelLinkProvider tmp = getService(ManagedItemChannelLinkProvider.class);
assertNotNull(tmp);
return tmp;
});
itemChannelLinkProvider.add(new ItemChannelLink(TEST_ITEM_NAME, channelUID));
}
private State getItemState(String acceptedItemType) {
final Item testItem = waitForAssert(() -> {
Item tmp;
try {
tmp = itemRegistry.getItem(TEST_ITEM_NAME);
} catch (ItemNotFoundException e) {
tmp = null;
}
assertNotNull(tmp);
return tmp;
});
return waitForAssert(() -> {
final State testItemState = testItem.getState();
if (acceptedItemType.equals(ACCEPTED_ITEM_TYPE_STRING)) {
assertThat(testItemState, is(instanceOf(StringType.class)));
} else if (acceptedItemType.equals(ACCEPTED_ITEM_TYPE_DATE_TIME)) {
assertThat(testItemState, is(instanceOf(DateTimeType.class)));
}
return testItemState;
}, 3 * DFL_TIMEOUT, 2 * DFL_SLEEP_TIME);
}
private String getStringChannelTimeZoneFromItemRegistry() {
String itemState = getItemState(ACCEPTED_ITEM_TYPE_STRING).toString();
String timeZoneFromItemRegistry = StringUtils.substringAfterLast(itemState, " ");
return timeZoneFromItemRegistry;
}
private void assertFormat(String initialDate, String formatPattern) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern);
final ZonedDateTime date;
date = ZonedDateTime.parse(initialDate, formatter);
String formattedDate = formatter.format(date);
assertEquals(initialDate, formattedDate);
}
private void assertCommunicationError(String acceptedItemType) {
Configuration configuration = new Configuration();
final String WRONG_HOSTNAME = "wrong.hostname";
if (acceptedItemType.equals(ACCEPTED_ITEM_TYPE_DATE_TIME)) {
initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null,
WRONG_HOSTNAME);
} else if (acceptedItemType.equals(ACCEPTED_ITEM_TYPE_STRING)) {
initialize(configuration, NtpBindingConstants.CHANNEL_STRING, ACCEPTED_ITEM_TYPE_STRING, null,
WRONG_HOSTNAME);
}
waitForAssert(() -> {
assertEquals(ThingStatusDetail.COMMUNICATION_ERROR, ntpThing.getStatusInfo().getStatusDetail());
}, 60000, DFL_SLEEP_TIME);
}
private void assertEventIsReceived(UpdateEventType updateEventType, String channelID, String acceptedItemType) {
Configuration configuration = new Configuration();
initialize(configuration, channelID, acceptedItemType, null, null);
EventSubscriber eventSubscriberMock = mock(EventSubscriber.class);
when(eventSubscriberMock.getSubscribedEventTypes()).thenReturn(Collections.singleton(ItemStateEvent.TYPE));
registerService(eventSubscriberMock);
if (updateEventType.equals(UpdateEventType.HANDLE_COMMAND)) {
ntpHandler.handleCommand(new ChannelUID("ntp:test:chan:1"), new StringType("test"));
} else if (updateEventType.equals(UpdateEventType.CHANNEL_LINKED)) {
ntpHandler.channelLinked(new ChannelUID("ntp:test:chan:1"));
}
waitForAssert(() -> {
verify(eventSubscriberMock, atLeastOnce()).receive(ArgumentMatchers.any(Event.class));
});
}
}