2 * Copyright (c) 2010-2023 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.hueemulation.internal.rest;
15 import static org.mockito.ArgumentMatchers.*;
16 import static org.mockito.Mockito.when;
18 import java.io.IOException;
19 import java.net.InetSocketAddress;
20 import java.net.ServerSocket;
22 import java.util.Collections;
23 import java.util.Dictionary;
24 import java.util.Hashtable;
25 import java.util.concurrent.ScheduledExecutorService;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
29 import javax.ws.rs.client.Client;
30 import javax.ws.rs.client.ClientBuilder;
32 import org.glassfish.grizzly.http.server.HttpServer;
33 import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
34 import org.glassfish.jersey.logging.LoggingFeature;
35 import org.glassfish.jersey.logging.LoggingFeature.Verbosity;
36 import org.glassfish.jersey.server.ResourceConfig;
37 import org.mockito.Mock;
38 import org.mockito.Mockito;
39 import org.mockito.MockitoAnnotations;
40 import org.openhab.core.events.EventPublisher;
41 import org.openhab.core.items.MetadataRegistry;
42 import org.openhab.core.net.NetworkAddressService;
43 import org.openhab.core.storage.Storage;
44 import org.openhab.core.storage.StorageService;
45 import org.openhab.io.hueemulation.internal.ConfigStore;
46 import org.openhab.io.hueemulation.internal.rest.mocks.ConfigStoreWithoutMetadata;
47 import org.openhab.io.hueemulation.internal.rest.mocks.DummyMetadataRegistry;
48 import org.openhab.io.hueemulation.internal.rest.mocks.DummyUsersStorage;
49 import org.osgi.service.cm.ConfigurationAdmin;
52 * We have no OSGi framework in the background. This class resolves
53 * dependencies between the different classes and mocks common services like the configAdmin.
55 * The {@link UserManagement} rest components is always
56 * setup and started in this common test setup, because all other rest components require
57 * user authentication.
59 * @author David Graeff - Initial contribution
61 public class CommonSetup {
63 public String basePath;
65 public ConfigStore cs;
66 public HttpServer server;
68 UserManagement userManagement;
70 AutoCloseable mocksCloseable;
73 EventPublisher eventPublisher;
76 ConfigurationAdmin configAdmin;
79 ScheduledExecutorService scheduler;
82 org.osgi.service.cm.Configuration configAdminConfig;
85 NetworkAddressService networkAddressService;
87 MetadataRegistry metadataRegistry = new DummyMetadataRegistry();
89 StorageService storageService = new StorageService() {
91 public <T> Storage<T> getStorage(String name, ClassLoader classLoader) {
92 return getStorage(name);
95 @SuppressWarnings("unchecked")
97 public <T> Storage<T> getStorage(String name) {
98 if (name.equals("hueEmulationUsers")) {
99 return (Storage<T>) new DummyUsersStorage();
101 throw new IllegalStateException();
105 public CommonSetup(boolean withMetadata) throws IOException {
106 mocksCloseable = MockitoAnnotations.openMocks(this);
108 when(configAdmin.getConfiguration(anyString())).thenReturn(configAdminConfig);
109 when(configAdmin.getConfiguration(anyString(), any())).thenReturn(configAdminConfig);
110 Dictionary<String, Object> mockProperties = new Hashtable<>();
111 when(configAdminConfig.getProperties()).thenReturn(mockProperties);
112 when(networkAddressService.getPrimaryIpv4HostAddress()).thenReturn("127.0.0.1");
114 // If anything is scheduled, immediately run it instead
115 when(scheduler.schedule(any(Runnable.class), anyLong(), any())).thenAnswer(answer -> {
116 ((Runnable) answer.getArgument(0)).run();
121 cs = new ConfigStore(networkAddressService, configAdmin, metadataRegistry, scheduler);
123 cs = new ConfigStoreWithoutMetadata(networkAddressService, configAdmin, scheduler);
125 cs.activate(Collections.singletonMap("uuid", "a668dc9b-7172-49c3-832f-acb07dda2a20"));
126 cs.switchFilter = Collections.singleton("Switchable");
127 cs.whiteFilter = Collections.singleton("Switchable");
128 cs.colorFilter = Collections.singleton("ColorLighting");
130 userManagement = Mockito.spy(new UserManagement(storageService, cs));
132 try (ServerSocket serverSocket = new ServerSocket()) {
133 serverSocket.bind(new InetSocketAddress(0));
134 basePath = "http://localhost:" + serverSocket.getLocalPort() + "/api";
139 * Start the http server to serve all registered jax-rs resources. Also setup a client for testing, see
142 * @param rc A resource config. Add objects and object instance resources to your needs. Example:
143 * "new ResourceConfig().registerInstances(configurationAccess)"
145 public void start(ResourceConfig resourceConfig) {
146 ResourceConfig rc = resourceConfig.registerInstances(userManagement).register(new LoggingFeature(
147 Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), Level.OFF, Verbosity.HEADERS_ONLY, 10));
149 Logger log2 = Logger.getLogger("org.glassfish");
150 log2.setLevel(Level.OFF);
152 server = GrizzlyHttpServerFactory.createHttpServer(URI.create(basePath), rc);
153 client = ClientBuilder.newClient();
156 public void dispose() throws Exception {
157 if (client != null) {
160 if (server != null) {
161 server.shutdownNow();
164 mocksCloseable.close();