2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.io.mqttembeddedbroker.internal;
15 import static org.hamcrest.CoreMatchers.is;
16 import static org.hamcrest.MatcherAssert.assertThat;
17 import static org.junit.jupiter.api.Assertions.*;
18 import static org.mockito.ArgumentMatchers.*;
19 import static org.mockito.Mockito.verify;
22 import java.io.IOException;
23 import java.nio.file.Path;
24 import java.nio.file.Paths;
25 import java.security.GeneralSecurityException;
26 import java.util.HashMap;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.Semaphore;
30 import java.util.concurrent.TimeUnit;
32 import javax.naming.ConfigurationException;
34 import org.apache.commons.io.FileUtils;
35 import org.h2.mvstore.MVMap;
36 import org.h2.mvstore.MVStore;
37 import org.junit.jupiter.api.AfterEach;
38 import org.junit.jupiter.api.BeforeEach;
39 import org.junit.jupiter.api.Test;
40 import org.junit.jupiter.api.extension.ExtendWith;
41 import org.mockito.Mock;
42 import org.mockito.junit.jupiter.MockitoExtension;
43 import org.openhab.core.OpenHAB;
44 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
45 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection.MqttVersion;
46 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection.Protocol;
47 import org.openhab.core.io.transport.mqtt.MqttConnectionObserver;
48 import org.openhab.core.io.transport.mqtt.MqttConnectionState;
49 import org.openhab.core.io.transport.mqtt.MqttException;
50 import org.openhab.core.io.transport.mqtt.MqttService;
51 import org.openhab.core.test.java.JavaTest;
53 import io.moquette.broker.RetainedMessage;
54 import io.moquette.broker.subscriptions.Topic;
57 * Tests connections with the embedded broker. Checks for credential based login,
58 * check for SSL connections.
60 * @author David Graeff - Initial contribution
62 @ExtendWith(MockitoExtension.class)
63 public class MqttEmbeddedBrokerServiceTest extends JavaTest {
65 private EmbeddedBrokerService subject;
66 private Map<String, Object> config = new HashMap<>();
67 private @Mock MqttService service;
70 public void setUp() throws ConfigurationException, MqttException, GeneralSecurityException, IOException {
71 config.put("username", "username");
72 config.put("password", "password");
73 config.put("port", 12345);
74 config.put("secure", false);
75 config.put("persistenceFile", "");
77 subject = new EmbeddedBrokerService(service, config);
81 public void cleanUp() {
85 public void waitForConnectionChange(MqttBrokerConnection c, MqttConnectionState expectedState)
86 throws InterruptedException {
87 Semaphore semaphore = new Semaphore(1);
90 MqttConnectionObserver mqttConnectionObserver = (state, error) -> {
91 if (state == expectedState) {
95 c.addConnectionObserver(mqttConnectionObserver);
96 if (c.connectionState() == expectedState) {
100 // Start the connection and wait until timeout or connected callback returns.
101 semaphore.tryAcquire(3000, TimeUnit.MILLISECONDS);
103 c.removeConnectionObserver(mqttConnectionObserver);
107 public void connectUnsecureAndTestCredentials() throws InterruptedException, IOException, ExecutionException {
108 MqttBrokerConnection c = subject.getConnection();
110 waitForConnectionChange(c, MqttConnectionState.CONNECTED);
112 assertThat(c.getUser(), is("username"));
113 assertThat(c.getPassword(), is("password"));
115 assertThat(c.connectionState(), is(MqttConnectionState.CONNECTED));
116 verify(service).addBrokerConnection(anyString(), eq(c));
118 // Connect with a second connection but wrong credentials
119 MqttBrokerConnection wrongCredentials = new MqttBrokerConnection(Protocol.TCP, MqttVersion.V3, c.getHost(),
120 c.getPort(), false, "wrongCred");
121 wrongCredentials.setCredentials("someUser", "somePassword");
123 if (wrongCredentials.start().get()) {
124 fail("Wrong credentials accepted!");
127 wrongCredentials.stop().get();
129 // Connect with a second connection but correct credentials
130 MqttBrokerConnection correctCredentials = new MqttBrokerConnection(Protocol.TCP, MqttVersion.V3, c.getHost(),
131 c.getPort(), false, "correctCred");
132 correctCredentials.setCredentials(c.getUser(), c.getPassword());
134 if (!correctCredentials.start().get()) {
135 fail("Couldn't connect although correct credentials");
138 correctCredentials.stop().get();
142 public void connectSecure() throws InterruptedException, IOException {
143 config.put("secure", true);
144 subject.modified(config);
146 MqttBrokerConnection c = subject.getConnection();
149 waitForConnectionChange(c, MqttConnectionState.CONNECTED);
151 assertThat(c.getUser(), is("username"));
152 assertThat(c.getPassword(), is("password"));
154 assertThat(c.connectionState(), is(MqttConnectionState.CONNECTED));
155 verify(service).addBrokerConnection(anyString(), eq(c));
159 public void testPersistence() throws InterruptedException, IOException, ExecutionException {
160 config.put("persistenceFile", "persist.mqtt");
161 Path path = Paths.get(OpenHAB.getUserDataFolder()).toAbsolutePath();
162 File jksFile = path.resolve("persist.mqtt").toFile();
164 if (jksFile.exists()) {
168 subject.modified(config);
170 MqttBrokerConnection c = subject.getConnection();
173 waitForConnectionChange(c, MqttConnectionState.CONNECTED);
175 c.publish("demotopic", "testtest".getBytes(), 2, true).get();
177 // Stop server -> close persistence storage and sync it to disk
178 subject.deactivate();
179 assertTrue(jksFile.exists());
180 // this is needed to ensure the file is correctly written
181 waitForAssert(() -> assertEquals(12288, jksFile.length()));
183 // The original file is still open, create a temp file for examination
184 File temp = File.createTempFile("abc", ".tmp");
186 FileUtils.copyFile(jksFile, temp);
188 MVStore mvStore = new MVStore.Builder().fileName(temp.getAbsolutePath()).autoCommitDisabled().open();
189 MVMap<Topic, RetainedMessage> openMap = mvStore.openMap("retained_store");
191 assertThat(openMap.size(), is(1));
192 for (Map.Entry<Topic, RetainedMessage> entry : openMap.entrySet()) {
193 assertThat(entry.getKey().toString(), is("demotopic"));
194 assertThat(new String(entry.getValue().getPayload()), is("testtest"));