From 4eb5c2c48a0887be23e17e045aae33c0a30da29a Mon Sep 17 00:00:00 2001 From: Romain Manni-Bucau Date: Mon, 21 Nov 2022 12:09:50 +0100 Subject: [PATCH 1/2] rebase --- .../org/apache/karaf/minho/boot/Main.java | 56 +++++++----- .../org/apache/karaf/minho/boot/Minho.java | 30 ++----- .../apache/karaf/minho/boot/SimpleMain.java | 56 ++++++++++++ .../karaf/minho/boot/config/Application.java | 8 +- .../karaf/minho/boot/config/Config.java | 12 ++- .../karaf/minho/boot/config/Profile.java | 8 -- .../boot/service/ClassLoaderService.java | 17 ++-- .../minho/boot/service/LifeCycleService.java | 5 +- .../minho/boot/service/ServiceRegistry.java | 1 - .../apache/karaf/boot/minho/ConfigTest.java | 8 +- .../apache/karaf/boot/minho/MinhoTest.java | 4 +- pom.xml | 12 +++ .../minho/banner/WelcomeBannerService.java | 4 +- services/minho-config-json/pom.xml | 12 +-- .../config/json/JsonConfigLoaderService.java | 86 +++++++++++-------- .../json/JsonConfigLoaderServiceTest.java | 16 ++-- .../PropertiesConfigLoaderService.java | 52 ++++++----- .../PropertiesConfigLoaderServiceTest.java | 16 ++-- .../minho/extractor/ExtractorService.java | 40 +++++---- .../web/jetty/JettyWebContainerService.java | 16 ++-- .../apache/karaf/minho/jmx/JmxService.java | 28 +++--- .../minho/rest/jersey/JerseyRestService.java | 6 +- tooling/common/pom.xml | 44 +++++----- .../minho/tooling/common/maven/Parser.java | 39 +++++++-- .../tooling/common/model/MinhoBuild.java | 11 +-- 25 files changed, 348 insertions(+), 239 deletions(-) create mode 100644 boot/src/main/java/org/apache/karaf/minho/boot/SimpleMain.java diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/Main.java b/boot/src/main/java/org/apache/karaf/minho/boot/Main.java index 03efb62..11b3d91 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/Main.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/Main.java @@ -20,41 +20,55 @@ import lombok.extern.java.Log; import java.io.IOException; +import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; -import java.nio.file.*; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.function.Predicate; + +import static java.util.Optional.ofNullable; @Log public class Main { + private Main() { + // no-op + } - public static final void main(String[] args) throws Exception { - boolean minhoJar = false; - minhoJar = (System.getenv("MINHO_JAR") != null) ? System.getenv("MINHO_JAR").equalsIgnoreCase("true") : minhoJar; - minhoJar = (System.getProperty("minho.jar") != null) ? System.getProperty("minho.jar").equalsIgnoreCase("true") : minhoJar; + public static void main(final String... args) throws Exception { + final boolean minhoJar = Boolean.parseBoolean(System.getenv("MINHO_JAR")) || Boolean.parseBoolean(System.getProperty("minho.jar")); if (!minhoJar) { log.info("Starting runtime in exploded mode"); // try to load classpath - String minhoLib = (System.getProperty("minho.lib") != null) ? System.getProperty("minho.lib") : System.getProperty("user.dir"); + final var minhoLib = ofNullable(System.getProperty("minho.lib")) + .orElseGet(() -> System.getProperty("user.dir")); System.out.println("Minho lib: " + minhoLib); - Path libFolder = Paths.get(minhoLib); - ArrayList urls = new ArrayList(); - Files.walkFileTree(libFolder, new SimpleFileVisitor<>() { - public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { - if (!Files.isDirectory(file)) { - urls.add(file.toFile().toURI().toURL()); + final var libFolder = Paths.get(minhoLib); + try (final var walk = Files.walk(libFolder)) { + final var urls = walk + .filter(Predicate.not(Files::isDirectory)) + .map(it -> { + try { + return it.toUri().toURL(); + } catch (final MalformedURLException e) { + throw new IllegalStateException(e); + } + }) + .toArray(URL[]::new); + final var classLoader = new URLClassLoader(urls); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { + classLoader.close(); + } catch (final IOException e) { + // no-op, not critical } - return FileVisitResult.CONTINUE; - } - }); - URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[]{})); - Thread.currentThread().setContextClassLoader(classLoader); + }, Main.class.getName() + "-classloader-close")); + Thread.currentThread().setContextClassLoader(classLoader); + } } else { log.info("Starting runtime in uber jar mode"); } - Minho.builder().build().start(); + SimpleMain.main(args); } - } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/Minho.java b/boot/src/main/java/org/apache/karaf/minho/boot/Minho.java index e225169..3959c49 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/Minho.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/Minho.java @@ -25,6 +25,7 @@ import org.apache.karaf.minho.boot.spi.ServiceLoader; import java.util.Comparator; +import java.util.Objects; import java.util.stream.Stream; /** @@ -34,9 +35,6 @@ @Builder @Data public class Minho implements AutoCloseable { - - private static Minho instance; - private final ServiceLoader loader; private final ServiceRegistry serviceRegistry = new ServiceRegistry(); @@ -47,22 +45,19 @@ public class Minho implements AutoCloseable { */ public Minho start() { // log format - if (System.getProperty("java.util.logging.config.file") == null) { - if (System.getenv("KARAF_LOG_FORMAT") != null) { - System.setProperty("java.util.logging.SimpleFormatter.format", System.getenv("KARAF_LOG_FORMAT")); - } - if (System.getProperty("java.util.logging.SimpleFormatter.format") == null) { - System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tN %4$s [ %2$s ] : %5$s%6$s%n"); - } + if (System.getProperty("java.util.logging.config.file") == null && + System.getProperty("java.util.logging.SimpleFormatter.format") == null) { + System.setProperty("java.util.logging.SimpleFormatter.format", + Objects.requireNonNullElse(System.getenv("KARAF_LOG_FORMAT"), "%1$tF %1$tT.%1$tN %4$s [ %2$s ] : %5$s%6$s%n")); } (this.loader == null ? loadServices() : this.loader.load()).forEach(serviceRegistry::add); serviceRegistry.start(); - instance = this; - return instance; + return this; } private Stream loadServices() { - return java.util.ServiceLoader.load(Service.class).stream().map(java.util.ServiceLoader.Provider::get) + return java.util.ServiceLoader.load(Service.class).stream() + .map(java.util.ServiceLoader.Provider::get) .sorted(Comparator.comparingInt(service -> Integer.getInteger(service.name() + ".priority", service.priority()))); } @@ -74,13 +69,4 @@ public void close() { serviceRegistry.close(); } - /** - * Retrieve the Minho instance. - * - * @return the Minho instance. - */ - public static Minho getInstance() { - return instance; - } - } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/SimpleMain.java b/boot/src/main/java/org/apache/karaf/minho/boot/SimpleMain.java new file mode 100644 index 0000000..86ff0dd --- /dev/null +++ b/boot/src/main/java/org/apache/karaf/minho/boot/SimpleMain.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.karaf.minho.boot; + +import lombok.extern.java.Log; +import org.apache.karaf.minho.boot.service.ConfigService; +import org.apache.karaf.minho.boot.service.ServiceRegistry; + +import java.util.concurrent.CountDownLatch; + +import static java.util.Optional.ofNullable; + +@Log +public class SimpleMain { + private SimpleMain() { + // no-op + } + + public static void main(final String... args) throws Exception { + try (final var instance = Minho.builder().build().start()) { + final var registry = instance.getServiceRegistry(); + final var awaiter = registry.get(Awaiter.class); + if (awaiter != null) { + awaiter.await(); + } else if (Boolean.getBoolean(registry.get(ConfigService.class).property("minho.awaiter.implicit", "false"))) { + new CountDownLatch(1).await(); + } + } + } + + /** + * Service implementation enabling the main to not quit immediately if set. + * Often used for servers. + */ + public interface Awaiter { + /** + * Wait until the application completes and can exit. + */ + void await(); + } +} diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/config/Application.java b/boot/src/main/java/org/apache/karaf/minho/boot/config/Application.java index 1e8e266..83c697b 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/config/Application.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/config/Application.java @@ -32,12 +32,12 @@ public class Application { private String profile; private Map properties = new HashMap<>(); - public String getProperty(String key) { - return getProperty(key, null); + public String property(final String key) { + return property(key, null); } - public String getProperty(String key, String defaultValue) { - return Config.getProperty(key, properties, defaultValue); + public String property(String key, String defaultValue) { + return Config.property(key, properties, defaultValue); } } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/config/Config.java b/boot/src/main/java/org/apache/karaf/minho/boot/config/Config.java index 37588e6..b4dcc21 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/config/Config.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/config/Config.java @@ -27,7 +27,6 @@ @Data public class Config { - private static Pattern envKeyPattern = Pattern.compile("\\."); private Map properties = new HashMap<>(); @@ -44,15 +43,15 @@ public void merge(final Config config) { applications.addAll(config.getApplications()); } - public String getProperty(String key) { - return getProperty(key, null); + public String property(String key) { + return property(key, null); } - public String getProperty(String key, String defaultValue) { - return getProperty(key, this.properties, defaultValue); + public String property(String key, String defaultValue) { + return property(key, this.properties, defaultValue); } - protected static String getProperty(String key, Map properties, String defaultValue) { + protected static String property(String key, Map properties, String defaultValue) { String envKey = envKeyPattern.matcher(key).replaceAll("_").toUpperCase(); if (System.getenv(envKey) != null) { return System.getenv(envKey); @@ -65,5 +64,4 @@ protected static String getProperty(String key, Map properties, } return defaultValue; } - } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/config/Profile.java b/boot/src/main/java/org/apache/karaf/minho/boot/config/Profile.java index ba0d7bf..c8a7656 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/config/Profile.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/config/Profile.java @@ -31,12 +31,4 @@ public class Profile { private Map properties = new HashMap<>(); private List urls = new ArrayList<>(); - public String getProperty(String key) { - return getProperty(key, null); - } - - public String getProperty(String key, String defaultValue) { - return Config.getProperty(key, properties, defaultValue); - } - } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/service/ClassLoaderService.java b/boot/src/main/java/org/apache/karaf/minho/boot/service/ClassLoaderService.java index d210d93..db9f9c3 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/service/ClassLoaderService.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/service/ClassLoaderService.java @@ -20,6 +20,7 @@ import org.apache.karaf.minho.boot.config.Config; import org.apache.karaf.minho.boot.spi.Service; +import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.HashMap; @@ -30,7 +31,7 @@ */ public class ClassLoaderService implements Service, AutoCloseable { - private Map profiles = new HashMap<>(); + private final Map profiles = new HashMap<>(); @Override public String name() { @@ -44,19 +45,25 @@ public int priority() { @Override public void close() { - // no-op + profiles.values().forEach(it -> { + try { + it.close(); + } catch (final IOException e) { + // no-op, not critical + } + }); } @Override public void onRegister(ServiceRegistry serviceRegistry) throws Exception { Config configService = serviceRegistry.get(Config.class); - configService.getProfiles().stream().forEach(profile -> { - URLClassLoader profileClassLoader = new URLClassLoader(profile.getUrls().toArray(new URL[]{}), this.getClass().getClassLoader()); + configService.getProfiles().forEach(profile -> { + URLClassLoader profileClassLoader = new URLClassLoader(profile.getUrls().toArray(new URL[0]), this.getClass().getClassLoader()); profiles.put(profile.getName(), profileClassLoader); }); } - public URLClassLoader getClassLoader(String profile) { + public URLClassLoader getClassLoader(final String profile) { return profiles.get(profile); } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/service/LifeCycleService.java b/boot/src/main/java/org/apache/karaf/minho/boot/service/LifeCycleService.java index caa567b..9cbef21 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/service/LifeCycleService.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/service/LifeCycleService.java @@ -46,7 +46,7 @@ public int priority() { * Add a start callback in the lifecycle. * @param callback The runnable start callback. */ - public void onStart(Runnable callback) { + public void onStart(final Runnable callback) { startCallbacks.add(callback); } @@ -54,7 +54,7 @@ public void onStart(Runnable callback) { * Add a stop callback in the lifecycle. * @param callback The runnable stop callback. */ - public void onShutdown(Runnable callback) { + public void onShutdown(final Runnable callback) { shutdownCallbacks.add(callback); } @@ -94,5 +94,4 @@ public void close() { throw ise; } } - } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/service/ServiceRegistry.java b/boot/src/main/java/org/apache/karaf/minho/boot/service/ServiceRegistry.java index 9530854..c21b6da 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/service/ServiceRegistry.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/service/ServiceRegistry.java @@ -32,7 +32,6 @@ */ @Log public class ServiceRegistry implements AutoCloseable { - private final Map, Service> registry = new ConcurrentHashMap<>(); public Map, Service> getAll() { diff --git a/boot/src/test/java/org/apache/karaf/boot/minho/ConfigTest.java b/boot/src/test/java/org/apache/karaf/boot/minho/ConfigTest.java index 6cbd742..de7f884 100644 --- a/boot/src/test/java/org/apache/karaf/boot/minho/ConfigTest.java +++ b/boot/src/test/java/org/apache/karaf/boot/minho/ConfigTest.java @@ -30,10 +30,10 @@ public void defaultTest() { Config config = new Config(); config.getProperties().put("foo", "bar"); - Assertions.assertEquals("world", config.getProperty("hello", "world")); - Assertions.assertEquals("bar", config.getProperty("foo")); - Assertions.assertEquals("bar.test", config.getProperty("foo.test")); - Assertions.assertNull(config.getProperty("not.defined")); + Assertions.assertEquals("world", config.property("hello", "world")); + Assertions.assertEquals("bar", config.property("foo")); + Assertions.assertEquals("bar.test", config.property("foo.test")); + Assertions.assertNull(config.property("not.defined")); } } diff --git a/boot/src/test/java/org/apache/karaf/boot/minho/MinhoTest.java b/boot/src/test/java/org/apache/karaf/boot/minho/MinhoTest.java index 21e4755..b2bc252 100644 --- a/boot/src/test/java/org/apache/karaf/boot/minho/MinhoTest.java +++ b/boot/src/test/java/org/apache/karaf/boot/minho/MinhoTest.java @@ -48,8 +48,8 @@ void simpleRunWithConfig() { .start()) { final var configService = minho.getServiceRegistry().get(Config.class); assertNotNull(configService); - assertEquals("bar", configService.getProperty("foo")); - assertEquals("world", configService.getProperty("hello")); + assertEquals("bar", configService.property("foo")); + assertEquals("world", configService.property("hello")); } } diff --git a/pom.xml b/pom.xml index 6af052b..fc4a2c9 100644 --- a/pom.xml +++ b/pom.xml @@ -101,6 +101,18 @@ minho-http ${project.version} + + io.yupiik.uship + json-dependencies + 1.0.15 + pom + + + io.yupiik.uship + backbone-johnzon + 1.0.15 + pom + diff --git a/services/minho-banner/src/main/java/org/apache/karaf/minho/banner/WelcomeBannerService.java b/services/minho-banner/src/main/java/org/apache/karaf/minho/banner/WelcomeBannerService.java index ce16f67..65e6bf8 100644 --- a/services/minho-banner/src/main/java/org/apache/karaf/minho/banner/WelcomeBannerService.java +++ b/services/minho-banner/src/main/java/org/apache/karaf/minho/banner/WelcomeBannerService.java @@ -43,8 +43,8 @@ public int priority() { public void onRegister(ServiceRegistry serviceRegistry) { if (serviceRegistry.get(ConfigService.class) != null) { ConfigService configService = serviceRegistry.get(ConfigService.class); - if (configService.getProperty("minho.banner") != null) { - log.info(configService.getProperty("minho.banner")); + if (configService.property("minho.banner") != null) { + log.info(configService.property("minho.banner")); return; } } diff --git a/services/minho-config-json/pom.xml b/services/minho-config-json/pom.xml index 56573ae..6d0133f 100644 --- a/services/minho-config-json/pom.xml +++ b/services/minho-config-json/pom.xml @@ -48,14 +48,14 @@ 1.4 - org.apache.geronimo.specs - geronimo-json_1.1_spec - 1.5 + io.yupiik.uship + json-dependencies + pom - org.apache.johnzon - johnzon-jsonb - 1.2.19 + io.yupiik.uship + backbone-johnzon + pom diff --git a/services/minho-config-json/src/main/java/org/apache/karaf/minho/config/json/JsonConfigLoaderService.java b/services/minho-config-json/src/main/java/org/apache/karaf/minho/config/json/JsonConfigLoaderService.java index 1cc07a8..65fd509 100644 --- a/services/minho-config-json/src/main/java/org/apache/karaf/minho/config/json/JsonConfigLoaderService.java +++ b/services/minho-config-json/src/main/java/org/apache/karaf/minho/config/json/JsonConfigLoaderService.java @@ -22,18 +22,19 @@ import org.apache.karaf.minho.boot.service.ServiceRegistry; import org.apache.karaf.minho.boot.spi.Service; -import javax.json.bind.Jsonb; -import javax.json.bind.JsonbBuilder; -import java.io.*; +import jakarta.json.bind.JsonbBuilder; +import jakarta.json.bind.JsonbConfig; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.nio.file.Files; +import java.nio.file.Path; /** * Load Config from a JSON file. */ @Log public class JsonConfigLoaderService implements Service { - - private Jsonb jsonb = null; - @Override public String name() { return "minho-config-json-service"; @@ -46,44 +47,61 @@ public int priority() { @Override public void onRegister(final ServiceRegistry serviceRegistry) throws Exception { - Config config = null; - if (System.getenv("MINHO_CONFIG") != null) { + final var config = System.getProperty("minho.config"); + if (config != null) { + log.info(() -> "Loading JSON configuration from " + config); + try (final var in = Files.newBufferedReader(Path.of(config))) { + doMerge(serviceRegistry, loadJson(in)); + } + return; + } + + final var envConfigFile = System.getenv("MINHO_CONFIG_FILE"); + if (envConfigFile != null) { + log.info(() -> "Loading JSON configuration from " + envConfigFile); + try (final var in = Files.newBufferedReader(Path.of(envConfigFile))) { + doMerge(serviceRegistry, loadJson(in)); + } + return; + } + + final var envConfig = System.getenv("MINHO_CONFIG"); + if (envConfig != null) { log.info("Loading JSON configuration from MINHO_CONFIG env variable"); - StringReader reader = new StringReader(System.getenv("MINHO_CONFIG")); - config = loadJson(new StringReader(System.getenv("MINHO_CONFIG"))); - } else if (System.getenv("MINHO_CONFIG_FILE") != null) { - log.info("Loading JSON configuration from " + System.getenv("MINHO_CONFIG_FILE")); - config = loadJson(new FileInputStream(System.getenv("MINHO_CONFIG_FILE"))); - } else if (System.getProperty("minho.config") != null) { - log.info("Loading JSON configuration from " + System.getProperty("minho.config")); - config = loadJson(new FileInputStream(System.getProperty("minho.config"))); - } else if (JsonConfigLoaderService.class.getResourceAsStream("/META-INF/minho.json") != null) { + try (final var reader = new StringReader(envConfig)) { + doMerge(serviceRegistry, loadJson(reader)); + } + return; + } + + final var metaInfMinHo = JsonConfigLoaderService.class.getResourceAsStream("/META-INF/minho.json"); + if (metaInfMinHo != null) { log.info("Loading JSON configuration from classpath META-INF/minho.json"); - config = loadJson(JsonConfigLoaderService.class.getResourceAsStream("/META-INF/minho.json")); - } else if (JsonConfigLoaderService.class.getResourceAsStream("/minho.json") != null) { + try (final var reader = new InputStreamReader(metaInfMinHo)) { + doMerge(serviceRegistry, loadJson(reader)); + } + return; + } + + final var rootMinho = JsonConfigLoaderService.class.getResourceAsStream("/minho.json"); + if (rootMinho != null) { log.info("Loading JSON configuration from classpath minho.json"); - config = loadJson(JsonConfigLoaderService.class.getResourceAsStream("/minho.json")); - } else { - log.info("JSON configuration not found"); + try (final var reader = new InputStreamReader(rootMinho)) { + doMerge(serviceRegistry, loadJson(reader)); + } return; } - final var existing = serviceRegistry.get(Config.class); - existing.merge(config); + log.info("JSON configuration not found"); } - private Config loadJson(InputStream inputStream) { - if (jsonb == null) { - jsonb = JsonbBuilder.create(); - } - return jsonb.fromJson(inputStream, Config.class); + private void doMerge(final ServiceRegistry serviceRegistry, final Config config) { + serviceRegistry.get(Config.class).merge(config); } - private Config loadJson(Reader reader) { - if (jsonb == null) { - jsonb = JsonbBuilder.create(); + private Config loadJson(final Reader reader) throws Exception { + try (final var jsonb = JsonbBuilder.create(new JsonbConfig().setProperty("johnzon.skip-cdi", true))) { + return jsonb.fromJson(reader, Config.class); } - return jsonb.fromJson(reader, Config.class); } - } diff --git a/services/minho-config-json/src/test/java/org/apache/karaf/minho/config/json/JsonConfigLoaderServiceTest.java b/services/minho-config-json/src/test/java/org/apache/karaf/minho/config/json/JsonConfigLoaderServiceTest.java index 732b58d..d508a7b 100644 --- a/services/minho-config-json/src/test/java/org/apache/karaf/minho/config/json/JsonConfigLoaderServiceTest.java +++ b/services/minho-config-json/src/test/java/org/apache/karaf/minho/config/json/JsonConfigLoaderServiceTest.java @@ -39,7 +39,7 @@ public void loadingTestFromSystemProp() throws Exception { Config config = serviceRegistry.get(ConfigService.class); - Assertions.assertEquals("bar", config.getProperty("foo")); + Assertions.assertEquals("bar", config.property("foo")); Assertions.assertEquals(0, config.getProfiles().size()); Assertions.assertEquals(0, config.getApplications().size()); @@ -57,11 +57,11 @@ public void loadingTestFromClasspath() throws Exception { Config config = serviceRegistry.get(Config.class); // properties - Assertions.assertEquals("bar", config.getProperty("foo")); - Assertions.assertTrue(Boolean.parseBoolean(config.getProperty("lifecycle.enabled"))); - Assertions.assertEquals("%m %n", config.getProperty("log.patternLayout")); - Assertions.assertEquals("./osgi/cache", config.getProperty("osgi.storageDirectory")); - Assertions.assertEquals(1, Long.parseLong(config.getProperty("osgi.priority"))); + Assertions.assertEquals("bar", config.property("foo")); + Assertions.assertTrue(Boolean.parseBoolean(config.property("lifecycle.enabled"))); + Assertions.assertEquals("%m %n", config.property("log.patternLayout")); + Assertions.assertEquals("./osgi/cache", config.property("osgi.storageDirectory")); + Assertions.assertEquals(1, Long.parseLong(config.property("osgi.priority"))); // profiles Assertions.assertEquals(1, config.getProfiles().size()); @@ -71,8 +71,8 @@ public void loadingTestFromClasspath() throws Exception { Application springBootApp = config.getApplications().get(0); Assertions.assertEquals("/path/to/app/spring-boot.jar", springBootApp.getUrl()); Assertions.assertEquals("spring-boot", springBootApp.getType()); - Assertions.assertTrue(Boolean.parseBoolean(springBootApp.getProperty("enableHttp"))); - Assertions.assertTrue(Boolean.parseBoolean(springBootApp.getProperty("enablePrometheus"))); + Assertions.assertTrue(Boolean.parseBoolean(springBootApp.property("enableHttp"))); + Assertions.assertTrue(Boolean.parseBoolean(springBootApp.property("enablePrometheus"))); } @Test diff --git a/services/minho-config-properties/src/main/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderService.java b/services/minho-config-properties/src/main/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderService.java index 663a1db..d6d5ce8 100644 --- a/services/minho-config-properties/src/main/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderService.java +++ b/services/minho-config-properties/src/main/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderService.java @@ -25,10 +25,12 @@ import java.io.FileInputStream; import java.io.StringReader; -import java.util.List; -import java.util.Map; import java.util.Properties; -import java.util.stream.Collectors; + +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; /** * Load Config from a properties. @@ -49,6 +51,10 @@ public int priority() { @Override public void onRegister(final ServiceRegistry serviceRegistry) throws Exception { Properties properties = new Properties(); + + // todo: + // - revisit, it uses the same keys than json service so it can't work reliably since both should be usable at the same time + // - avoid the leaks -- see json config loader service if (System.getenv("MINHO_CONFIG") != null) { log.info("Loading properties from MINHO_CONFIG env variable"); properties.load(new StringReader(System.getenv("MINHO_CONFIG"))); @@ -71,32 +77,32 @@ public void onRegister(final ServiceRegistry serviceRegistry) throws Exception { } private Config parse(final Properties properties) { - Config config = new Config(); + final var config = new Config(); - properties.keySet().stream().filter(key -> !((String) key).startsWith("application.")) - .forEach(key -> { - config.getProperties().put(((String) key), properties.get(key).toString()); - }); + config.getProperties() + .putAll(properties.stringPropertyNames().stream() + .filter(key -> !key.startsWith("application.")) + .collect(toMap(identity(), properties::getProperty))); - List applicationKeys = properties.keySet().stream().filter(key -> ((String) key).startsWith("application.")) - .collect(Collectors.toList()); - Map> groupBy = applicationKeys.stream() - .collect(Collectors.groupingBy(key -> { - String local = ((String) key).substring("application.".length()); + final var applicationKeys = properties.stringPropertyNames().stream() + .filter(key -> key.startsWith("application.")) + .collect(toList()); + final var groupBy = applicationKeys.stream() + .collect(groupingBy(key -> { + final var local = key.substring("application.".length()); return local.substring(0, local.indexOf(".")); })); - groupBy.entrySet().forEach(entry -> { + groupBy.forEach((appName, value) -> { Application application = new Application(); - String appName = (String) entry.getKey(); - entry.getValue().forEach(value -> { - if (value.equals("application." + appName + ".type")) { - application.setType((String) properties.get(value)); - } else if (value.equals("application." + appName + ".url")) { - application.setUrl((String) properties.get(value)); - } else if (value.equals("application." + appName + ".profile")) { - application.setProfile((String) properties.get(value)); + value.forEach(v -> { + if (v.equals("application." + appName + ".type")) { + application.setType((String) properties.get(v)); + } else if (v.equals("application." + appName + ".url")) { + application.setUrl((String) properties.get(v)); + } else if (v.equals("application." + appName + ".profile")) { + application.setProfile((String) properties.get(v)); } else { - application.getProperties().put(((String) value).substring(("application." + appName).length() + 1), properties.get(value).toString()); + application.getProperties().put(v.substring(("application." + appName).length() + 1), properties.get(v).toString()); } }); config.getApplications().add(application); diff --git a/services/minho-config-properties/src/test/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderServiceTest.java b/services/minho-config-properties/src/test/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderServiceTest.java index 24b101a..49216f4 100644 --- a/services/minho-config-properties/src/test/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderServiceTest.java +++ b/services/minho-config-properties/src/test/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderServiceTest.java @@ -39,7 +39,7 @@ public void loadingTestFromSysProp() throws Exception { Config config = serviceRegistry.get(ConfigService.class); - Assertions.assertEquals("bar", config.getProperty("foo")); + Assertions.assertEquals("bar", config.property("foo")); System.clearProperty("minho.config"); } @@ -55,11 +55,11 @@ public void loadingTestFromClasspath() throws Exception { Config config = serviceRegistry.get(Config.class); // properties - Assertions.assertEquals("bar", config.getProperty("foo")); - Assertions.assertEquals("true", config.getProperty("lifecycle.enabled")); - Assertions.assertEquals("%m %n", config.getProperty("log.patternLayout")); - Assertions.assertEquals("./osgi/cache", config.getProperty("osgi.storageDirectory")); - Assertions.assertEquals("1", config.getProperty("osgi.priority")); + Assertions.assertEquals("bar", config.property("foo")); + Assertions.assertEquals("true", config.property("lifecycle.enabled")); + Assertions.assertEquals("%m %n", config.property("log.patternLayout")); + Assertions.assertEquals("./osgi/cache", config.property("osgi.storageDirectory")); + Assertions.assertEquals("1", config.property("osgi.priority")); // TODO profiles // Assertions.assertEquals(1, config.getProfiles().size()); @@ -69,8 +69,8 @@ public void loadingTestFromClasspath() throws Exception { Application springBootApp = config.getApplications().get(1); Assertions.assertEquals("/path/to/app/spring-boot.jar", springBootApp.getUrl()); Assertions.assertEquals("spring-boot", springBootApp.getType()); - Assertions.assertEquals("true", springBootApp.getProperty("enableHttp")); - Assertions.assertEquals("true", springBootApp.getProperty("enablePrometheus")); + Assertions.assertEquals("true", springBootApp.property("enableHttp")); + Assertions.assertEquals("true", springBootApp.property("enablePrometheus")); } @Test diff --git a/services/minho-extractor/src/main/java/org/apache/karaf/minho/extractor/ExtractorService.java b/services/minho-extractor/src/main/java/org/apache/karaf/minho/extractor/ExtractorService.java index 0022154..37980a1 100644 --- a/services/minho-extractor/src/main/java/org/apache/karaf/minho/extractor/ExtractorService.java +++ b/services/minho-extractor/src/main/java/org/apache/karaf/minho/extractor/ExtractorService.java @@ -44,12 +44,12 @@ public void onRegister(ServiceRegistry serviceRegistry) throws Exception { return; } String sources = "resources"; - if (config.getProperty("extractor.sources") != null) { - sources = config.getProperty("extractor.sources").toString(); + if (config.property("extractor.sources") != null) { + sources = config.property("extractor.sources").toString(); } String target = "."; - if (config.getProperty("extractor.target") != null) { - target = config.getProperty("extractor.target").toString(); + if (config.property("extractor.target") != null) { + target = config.property("extractor.target").toString(); } String[] urls = sources.split(","); @@ -61,22 +61,24 @@ public void onRegister(ServiceRegistry serviceRegistry) throws Exception { if (resource != null) { try (FileSystem fs = FileSystems.newFileSystem(resource.toURI(), Collections.emptyMap())) { String finalTarget = target; - Files.walk(fs.getPath(".")).filter(Files::isRegularFile) - .forEach(path -> { - try { - String resourceTarget = path.getParent().toAbsolutePath().toString(); - if (resourceTarget.startsWith("/" + url)) { - resourceTarget = resourceTarget.substring(("/" + url).length()); - Path directory = Paths.get(finalTarget + Paths.get(resourceTarget)); - Files.createDirectories(directory); - Path copy = Paths.get(directory.toAbsolutePath() + "/" + path.getFileName()); - Files.copy(path, copy, StandardCopyOption.REPLACE_EXISTING); + try (final var walk = Files.walk(fs.getPath("."))) { + walk.filter(Files::isRegularFile) + .forEach(path -> { + try { + String resourceTarget = path.getParent().toAbsolutePath().toString(); + if (resourceTarget.startsWith("/" + url)) { + resourceTarget = resourceTarget.substring(("/" + url).length()); + Path directory = Paths.get(finalTarget + Paths.get(resourceTarget)); + Files.createDirectories(directory); + Path copy = Paths.get(directory.toAbsolutePath() + "/" + path.getFileName()); + Files.copy(path, copy, StandardCopyOption.REPLACE_EXISTING); + } + } catch (Exception e) { // todo: fail? + log.warning("Can't copy " + path.toAbsolutePath() + " to " + finalTarget); + e.printStackTrace(); } - } catch (Exception e) { - log.warning("Can't copy " + path.toAbsolutePath() + " to " + finalTarget); - e.printStackTrace(); - } - }); + }); + } } } else { log.warning("URL resource '" + url + "' not found!"); diff --git a/services/minho-http/src/main/java/org/apache/karaf/minho/web/jetty/JettyWebContainerService.java b/services/minho-http/src/main/java/org/apache/karaf/minho/web/jetty/JettyWebContainerService.java index 7c6029b..60d14d7 100644 --- a/services/minho-http/src/main/java/org/apache/karaf/minho/web/jetty/JettyWebContainerService.java +++ b/services/minho-http/src/main/java/org/apache/karaf/minho/web/jetty/JettyWebContainerService.java @@ -61,9 +61,9 @@ public void onRegister(ServiceRegistry serviceRegistry) throws Exception { log.info("Starting HTTP service"); - int maxThreads = (configService != null && configService.getProperty(HTTP_MAX_THREADS) != null) ? Integer.parseInt(configService.getProperty(HTTP_MAX_THREADS)) : 200; - int minThreads = (configService != null && configService.getProperty(HTTP_MIN_THREADS) != null) ? Integer.parseInt(configService.getProperty(HTTP_MIN_THREADS)) : Math.min(8, maxThreads); - int idleTimeout = (configService != null && configService.getProperty(HTTP_IDLE_TIMEOUT) != null) ? Integer.parseInt(configService.getProperty(HTTP_IDLE_TIMEOUT)) : 60000; + int maxThreads = (configService != null && configService.property(HTTP_MAX_THREADS) != null) ? Integer.parseInt(configService.property(HTTP_MAX_THREADS)) : 200; + int minThreads = (configService != null && configService.property(HTTP_MIN_THREADS) != null) ? Integer.parseInt(configService.property(HTTP_MIN_THREADS)) : Math.min(8, maxThreads); + int idleTimeout = (configService != null && configService.property(HTTP_IDLE_TIMEOUT) != null) ? Integer.parseInt(configService.property(HTTP_IDLE_TIMEOUT)) : 60000; QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads, minThreads, idleTimeout); threadPool.setName("minho-http"); @@ -74,11 +74,11 @@ public void onRegister(ServiceRegistry serviceRegistry) throws Exception { server = new Server(threadPool); - int acceptors = (configService != null && configService.getProperty(HTTP_ACCEPTORS) != null) ? Integer.parseInt(configService.getProperty(HTTP_ACCEPTORS)) : -1; - int selectors = (configService != null && configService.getProperty(HTTP_SELECTORS) != null) ? Integer.parseInt(configService.getProperty(HTTP_SELECTORS)) : -1; - int port = (configService != null && configService.getProperty(HTTP_PORT) != null) ? Integer.parseInt(configService.getProperty(HTTP_PORT)) : 8080; - String host = (configService != null && configService.getProperty(HTTP_HOST) != null) ? configService.getProperty(HTTP_HOST) : "0.0.0.0"; - int acceptQueueSize = (configService != null && configService.getProperty(HTTP_ACCEPT_QUEUE_SIZE) != null) ? Integer.parseInt(configService.getProperty(HTTP_ACCEPT_QUEUE_SIZE)) : 0; + int acceptors = (configService != null && configService.property(HTTP_ACCEPTORS) != null) ? Integer.parseInt(configService.property(HTTP_ACCEPTORS)) : -1; + int selectors = (configService != null && configService.property(HTTP_SELECTORS) != null) ? Integer.parseInt(configService.property(HTTP_SELECTORS)) : -1; + int port = (configService != null && configService.property(HTTP_PORT) != null) ? Integer.parseInt(configService.property(HTTP_PORT)) : 8080; + String host = (configService != null && configService.property(HTTP_HOST) != null) ? configService.property(HTTP_HOST) : "0.0.0.0"; + int acceptQueueSize = (configService != null && configService.property(HTTP_ACCEPT_QUEUE_SIZE) != null) ? Integer.parseInt(configService.property(HTTP_ACCEPT_QUEUE_SIZE)) : 0; log.info("Creating HTTP server connector"); log.info("\tacceptors: " + acceptors); diff --git a/services/minho-jmx/src/main/java/org/apache/karaf/minho/jmx/JmxService.java b/services/minho-jmx/src/main/java/org/apache/karaf/minho/jmx/JmxService.java index 384736a..f37b21c 100644 --- a/services/minho-jmx/src/main/java/org/apache/karaf/minho/jmx/JmxService.java +++ b/services/minho-jmx/src/main/java/org/apache/karaf/minho/jmx/JmxService.java @@ -17,7 +17,6 @@ */ package org.apache.karaf.minho.jmx; -import lombok.Data; import lombok.extern.java.Log; import org.apache.karaf.minho.boot.service.ConfigService; import org.apache.karaf.minho.boot.service.LifeCycleService; @@ -27,7 +26,6 @@ import javax.management.MBeanServer; import javax.management.ObjectName; import java.util.HashMap; -import java.util.Hashtable; import java.util.Map; @Log @@ -50,19 +48,19 @@ public void onRegister(ServiceRegistry serviceRegistry) throws Exception { if (lifeCycleService == null) { throw new IllegalStateException("LifeCycleService is not found"); } - String rmiRegistryHost = configService.getProperty("jmx.rmiRegistryHost", ""); - int rmiRegistryPort = Integer.parseInt(configService.getProperty("jmx.rmiRegistryPort", "1099")); - String rmiServerHost = configService.getProperty("jmx.rmiServerHost", "0.0.0.0"); - int rmiServerPort = Integer.parseInt(configService.getProperty("jmx.rmiServerPort", "44444")); - - String serviceUrl = configService.getProperty("jmx.serverUrl", "service:jmx:rmi://" + rmiServerHost + ":" + rmiServerPort + "/jndi/rmi://" + rmiRegistryHost + ":" + rmiRegistryPort + "/minho"); - - boolean daemon = Boolean.parseBoolean(configService.getProperty("jmx.daemon", "true")); - boolean threaded = Boolean.parseBoolean(configService.getProperty("jmx.threaded", "true")); - ObjectName objectName = new ObjectName(configService.getProperty("jmx.objectName", "connector:name=rmi")); - boolean createRmiRegistry = Boolean.parseBoolean(configService.getProperty("jmx.createRmiRegistry", "true")); - boolean locateRmiRegistry = Boolean.parseBoolean(configService.getProperty("jmx.locateRmiRegistry", "true")); - boolean locateExistingMBeanServerIfPossible = Boolean.parseBoolean(configService.getProperty("jmx.locateExistingMBeanServerIfPossible", "true")); + String rmiRegistryHost = configService.property("jmx.rmiRegistryHost", ""); + int rmiRegistryPort = Integer.parseInt(configService.property("jmx.rmiRegistryPort", "1099")); + String rmiServerHost = configService.property("jmx.rmiServerHost", "0.0.0.0"); + int rmiServerPort = Integer.parseInt(configService.property("jmx.rmiServerPort", "44444")); + + String serviceUrl = configService.property("jmx.serverUrl", "service:jmx:rmi://" + rmiServerHost + ":" + rmiServerPort + "/jndi/rmi://" + rmiRegistryHost + ":" + rmiRegistryPort + "/minho"); + + boolean daemon = Boolean.parseBoolean(configService.property("jmx.daemon", "true")); + boolean threaded = Boolean.parseBoolean(configService.property("jmx.threaded", "true")); + ObjectName objectName = new ObjectName(configService.property("jmx.objectName", "connector:name=rmi")); + boolean createRmiRegistry = Boolean.parseBoolean(configService.property("jmx.createRmiRegistry", "true")); + boolean locateRmiRegistry = Boolean.parseBoolean(configService.property("jmx.locateRmiRegistry", "true")); + boolean locateExistingMBeanServerIfPossible = Boolean.parseBoolean(configService.property("jmx.locateExistingMBeanServerIfPossible", "true")); final MBeanServerFactory mBeanServerFactory = new MBeanServerFactory(); mBeanServerFactory.setLocateExistingServerIfPossible(locateExistingMBeanServerIfPossible); diff --git a/services/minho-rest/src/main/java/org/apache/karaf/minho/rest/jersey/JerseyRestService.java b/services/minho-rest/src/main/java/org/apache/karaf/minho/rest/jersey/JerseyRestService.java index a2278bd..16fd31a 100644 --- a/services/minho-rest/src/main/java/org/apache/karaf/minho/rest/jersey/JerseyRestService.java +++ b/services/minho-rest/src/main/java/org/apache/karaf/minho/rest/jersey/JerseyRestService.java @@ -52,9 +52,9 @@ public void onRegister(ServiceRegistry serviceRegistry) throws Exception { throw new IllegalStateException("minho-http-service is not found in the service registry"); } - restPath = (config != null && config.getProperty(REST_PATH) != null) ? config.getProperty(REST_PATH) : "/rest/*"; - if (config != null && config.getProperty(REST_PACKAGES) != null) { - restPackages = config.getProperty(REST_PACKAGES); + restPath = (config != null && config.property(REST_PATH) != null) ? config.property(REST_PATH) : "/rest/*"; + if (config != null && config.property(REST_PACKAGES) != null) { + restPackages = config.property(REST_PACKAGES); } else { throw new IllegalStateException("rest.packages configuration is not found in the ConfigService"); } diff --git a/tooling/common/pom.xml b/tooling/common/pom.xml index 1e697a6..6d015c5 100644 --- a/tooling/common/pom.xml +++ b/tooling/common/pom.xml @@ -33,6 +33,11 @@ common Apache Karaf Minho :: Tooling :: Common + + 1.4.2 + 3.8.6 + + org.projectlombok @@ -47,53 +52,48 @@ + + org.apache.maven.resolver + maven-resolver-spi + ${resolver.version} + org.apache.maven.resolver maven-resolver-api - 1.4.1 + ${resolver.version} org.apache.maven.resolver maven-resolver-impl - 1.4.1 + ${resolver.version} org.apache.maven.resolver maven-resolver-transport-http - 1.4.1 + ${resolver.version} org.apache.maven.resolver maven-resolver-connector-basic - 1.4.1 + ${resolver.version} org.apache.maven maven-core - 3.8.6 - - - org.apache.maven - maven-model-builder - 3.8.6 + ${mvn.version} + provided - javax.json - javax.json-api - 1.1.4 + io.yupiik.uship + json-dependencies + pom - org.apache.johnzon - johnzon-mapper - 1.2.19 - - - - org.slf4j - slf4j-jdk14 - 1.7.36 + io.yupiik.uship + backbone-johnzon + pom diff --git a/tooling/common/src/main/java/org/apache/karaf/minho/tooling/common/maven/Parser.java b/tooling/common/src/main/java/org/apache/karaf/minho/tooling/common/maven/Parser.java index e8e6066..3818dc3 100644 --- a/tooling/common/src/main/java/org/apache/karaf/minho/tooling/common/maven/Parser.java +++ b/tooling/common/src/main/java/org/apache/karaf/minho/tooling/common/maven/Parser.java @@ -19,7 +19,10 @@ import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; -import org.apache.maven.model.building.*; +import org.apache.maven.model.building.DefaultModelBuilder; +import org.apache.maven.model.building.DefaultModelBuildingRequest; +import org.apache.maven.model.building.DefaultModelProcessor; +import org.apache.maven.model.building.ModelBuildingRequest; import org.apache.maven.model.composition.DefaultDependencyManagementImporter; import org.apache.maven.model.inheritance.DefaultInheritanceAssembler; import org.apache.maven.model.interpolation.DefaultModelVersionProcessor; @@ -28,7 +31,11 @@ import org.apache.maven.model.management.DefaultDependencyManagementInjector; import org.apache.maven.model.management.DefaultPluginManagementInjector; import org.apache.maven.model.normalization.DefaultModelNormalizer; -import org.apache.maven.model.path.*; +import org.apache.maven.model.path.DefaultModelPathTranslator; +import org.apache.maven.model.path.DefaultModelUrlNormalizer; +import org.apache.maven.model.path.DefaultPathTranslator; +import org.apache.maven.model.path.DefaultUrlNormalizer; +import org.apache.maven.model.path.ProfileActivationFilePathInterpolator; import org.apache.maven.model.profile.DefaultProfileInjector; import org.apache.maven.model.profile.DefaultProfileSelector; import org.apache.maven.model.resolution.ModelResolver; @@ -45,7 +52,22 @@ import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory; import org.eclipse.aether.impl.LocalRepositoryProvider; -import org.eclipse.aether.internal.impl.*; +import org.eclipse.aether.internal.impl.DefaultArtifactResolver; +import org.eclipse.aether.internal.impl.DefaultChecksumPolicyProvider; +import org.eclipse.aether.internal.impl.DefaultFileProcessor; +import org.eclipse.aether.internal.impl.DefaultLocalRepositoryProvider; +import org.eclipse.aether.internal.impl.DefaultMetadataResolver; +import org.eclipse.aether.internal.impl.DefaultRemoteRepositoryManager; +import org.eclipse.aether.internal.impl.DefaultRepositoryConnectorProvider; +import org.eclipse.aether.internal.impl.DefaultRepositoryEventDispatcher; +import org.eclipse.aether.internal.impl.DefaultRepositoryLayoutProvider; +import org.eclipse.aether.internal.impl.DefaultRepositorySystem; +import org.eclipse.aether.internal.impl.DefaultSyncContextFactory; +import org.eclipse.aether.internal.impl.DefaultTransporterProvider; +import org.eclipse.aether.internal.impl.DefaultUpdateCheckManager; +import org.eclipse.aether.internal.impl.DefaultUpdatePolicyAnalyzer; +import org.eclipse.aether.internal.impl.Maven2RepositoryLayoutFactory; +import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.LocalRepositoryManager; import org.eclipse.aether.repository.RemoteRepository; @@ -54,7 +76,7 @@ import org.eclipse.aether.spi.localrepo.LocalRepositoryManagerFactory; import org.eclipse.aether.transport.http.HttpTransporterFactory; -import java.io.*; +import java.io.File; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; @@ -63,6 +85,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +// todo: do not use aether as a lib, either impl it from scratch (see tomee for ex) or use maven injections public class Parser { @@ -218,7 +241,7 @@ public static String pathFromMaven(String uri, String resolved) throws Malformed return parser.getArtifactPath(); } - public static String pathToMaven(String location, Map parts) { + public static String pathToMaven(String location, Map parts) { String[] p = location.split("/"); if (p.length >= 4 && p[p.length-1].startsWith(p[p.length-3] + "-" + p[p.length-2])) { String artifactId = p[p.length-3]; @@ -780,10 +803,8 @@ private static DefaultArtifactResolver getArtifactResolver(RepositorySystemSessi return artifactResolver; } + // todo: this will not work very quickly private static List getRemoteRepositories() { - List remoteRepositories = new ArrayList<>(); - remoteRepositories.add(new RemoteRepository.Builder("maven-central", "default", "https://repo1.maven.org/maven2").build()); - return remoteRepositories; + return List.of(new RemoteRepository.Builder("maven-central", "default", "https://repo.maven.apache.org/maven2").build()); } - } \ No newline at end of file diff --git a/tooling/common/src/main/java/org/apache/karaf/minho/tooling/common/model/MinhoBuild.java b/tooling/common/src/main/java/org/apache/karaf/minho/tooling/common/model/MinhoBuild.java index c0494b9..519eb24 100644 --- a/tooling/common/src/main/java/org/apache/karaf/minho/tooling/common/model/MinhoBuild.java +++ b/tooling/common/src/main/java/org/apache/karaf/minho/tooling/common/model/MinhoBuild.java @@ -17,9 +17,9 @@ */ package org.apache.karaf.minho.tooling.common.model; +import jakarta.json.bind.JsonbBuilder; +import jakarta.json.bind.JsonbConfig; import lombok.Data; -import org.apache.johnzon.mapper.Mapper; -import org.apache.johnzon.mapper.MapperBuilder; import java.io.InputStream; import java.util.List; @@ -33,9 +33,10 @@ public class MinhoBuild { private Map properties; private List dependencies; - public static MinhoBuild load(InputStream inputStream) throws Exception { - Mapper mapper = new MapperBuilder().build(); - return mapper.readObject(inputStream, MinhoBuild.class); + public static MinhoBuild load(final InputStream inputStream) throws Exception { + try (final var jsonb = JsonbBuilder.create(new JsonbConfig().setProperty("johnzon.skip-cdi", true))) { + return jsonb.fromJson(inputStream, MinhoBuild.class); + } } } From 6465cad7c14a7a7bc7e83225a3286d9b3c6e76c5 Mon Sep 17 00:00:00 2001 From: Romain Manni-Bucau Date: Mon, 21 Nov 2022 12:36:23 +0100 Subject: [PATCH 2/2] Ensure there is no leak of minho instances + move the static ref in a service to not impose it and have leakages+concurrencies issues --- boot/pom.xml | 7 +-- .../org/apache/karaf/minho/boot/Main.java | 5 +- .../org/apache/karaf/minho/boot/Minho.java | 63 +++++++++++++------ .../apache/karaf/minho/boot/SimpleMain.java | 5 -- .../karaf/minho/boot/config/Application.java | 52 +++++++++++++-- .../karaf/minho/boot/config/Config.java | 31 +++++++-- .../karaf/minho/boot/config/Priority.java | 28 +++++++-- .../karaf/minho/boot/config/Profile.java | 27 ++++++-- .../minho/boot/service/ConfigService.java | 2 +- .../service/InstanceSingletonService.java | 39 ++++++++++++ .../minho/boot/service/LifeCycleService.java | 11 ++-- .../minho/boot/service/ServiceRegistry.java | 27 ++++---- .../boot/spi/impl/DefaultLoaderService.java | 56 +++++++++++++++++ .../org.apache.karaf.minho.boot.spi.Service | 8 ++- .../apache/karaf/boot/minho/MinhoTest.java | 13 ---- .../service/InstanceSingletonServiceTest.java | 41 ++++++++++++ .../banner/WelcomeBannerServiceTest.java | 17 +++-- .../karaf/minho/camel/CamelServiceTest.java | 19 +++--- .../ClasspathProtocolHandlerTest.java | 12 +++- .../json/JsonConfigLoaderServiceTest.java | 45 +++++++------ .../PropertiesConfigLoaderServiceTest.java | 13 ++-- .../minho/extractor/ExtractorServiceTest.java | 22 +++---- .../jetty/JettyWebContainerServiceTest.java | 34 +++++----- .../karaf/minho/jmx/JmxServiceTest.java | 15 ++--- .../minho/jpa/openjpa/OpenJPAServiceTest.java | 39 +++++------- .../osgi/OsgiModuleManagerServiceTest.java | 5 +- .../rest/jersey/JerseyRestServiceTest.java | 35 +++++------ ...ringBootApplicationManagerServiceTest.java | 2 +- 28 files changed, 461 insertions(+), 212 deletions(-) create mode 100644 boot/src/main/java/org/apache/karaf/minho/boot/service/InstanceSingletonService.java create mode 100644 boot/src/main/java/org/apache/karaf/minho/boot/spi/impl/DefaultLoaderService.java create mode 100644 boot/src/test/java/org/apache/karaf/minho/boot/service/InstanceSingletonServiceTest.java diff --git a/boot/pom.xml b/boot/pom.xml index 5d964b4..05a22d7 100644 --- a/boot/pom.xml +++ b/boot/pom.xml @@ -33,12 +33,7 @@ Apache Karaf Minho :: Boot - - org.projectlombok - lombok - ${lombok.version} - provided - + diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/Main.java b/boot/src/main/java/org/apache/karaf/minho/boot/Main.java index 11b3d91..5daee31 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/Main.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/Main.java @@ -17,8 +17,6 @@ */ package org.apache.karaf.minho.boot; -import lombok.extern.java.Log; - import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; @@ -26,10 +24,10 @@ import java.nio.file.Files; import java.nio.file.Paths; import java.util.function.Predicate; +import java.util.logging.Logger; import static java.util.Optional.ofNullable; -@Log public class Main { private Main() { // no-op @@ -38,6 +36,7 @@ private Main() { public static void main(final String... args) throws Exception { final boolean minhoJar = Boolean.parseBoolean(System.getenv("MINHO_JAR")) || Boolean.parseBoolean(System.getProperty("minho.jar")); + final var log = Logger.getLogger(Main.class.getName()); if (!minhoJar) { log.info("Starting runtime in exploded mode"); // try to load classpath diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/Minho.java b/boot/src/main/java/org/apache/karaf/minho/boot/Minho.java index 3959c49..ebea9a7 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/Minho.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/Minho.java @@ -17,26 +17,38 @@ */ package org.apache.karaf.minho.boot; -import lombok.Builder; -import lombok.Data; -import lombok.extern.java.Log; import org.apache.karaf.minho.boot.service.ServiceRegistry; import org.apache.karaf.minho.boot.spi.Service; import org.apache.karaf.minho.boot.spi.ServiceLoader; +import org.apache.karaf.minho.boot.spi.impl.DefaultLoaderService; -import java.util.Comparator; import java.util.Objects; -import java.util.stream.Stream; /** * Main Karaf runtime. */ -@Log -@Builder -@Data -public class Minho implements AutoCloseable { +public class Minho implements AutoCloseable, Service { private final ServiceLoader loader; private final ServiceRegistry serviceRegistry = new ServiceRegistry(); + private volatile boolean closed = false; + + protected Minho(final ServiceLoader loader) { + this.loader = loader; + } + + public ServiceRegistry getServiceRegistry() { + return serviceRegistry; + } + + @Override + public String name() { + return "minho"; + } + + @Override + public int priority() { + return Integer.MIN_VALUE; + } /** * Start the Karaf runtime. @@ -48,25 +60,40 @@ public Minho start() { if (System.getProperty("java.util.logging.config.file") == null && System.getProperty("java.util.logging.SimpleFormatter.format") == null) { System.setProperty("java.util.logging.SimpleFormatter.format", - Objects.requireNonNullElse(System.getenv("KARAF_LOG_FORMAT"), "%1$tF %1$tT.%1$tN %4$s [ %2$s ] : %5$s%6$s%n")); + Objects.requireNonNullElse(System.getenv("MINHO_LOG_FORMAT"), "%1$tF %1$tT.%1$tN %4$s [ %2$s ] : %5$s%6$s%n")); } - (this.loader == null ? loadServices() : this.loader.load()).forEach(serviceRegistry::add); + serviceRegistry.add(this); + loader.load().forEach(serviceRegistry::add); serviceRegistry.start(); return this; } - private Stream loadServices() { - return java.util.ServiceLoader.load(Service.class).stream() - .map(java.util.ServiceLoader.Provider::get) - .sorted(Comparator.comparingInt(service -> Integer.getInteger(service.name() + ".priority", service.priority()))); - } - /** - * Close (stop) the Karaf runtime. + * Close (stop) the Minho runtime. */ @Override public void close() { + if (closed) { + return; + } + closed = true; serviceRegistry.close(); } + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + private ServiceLoader loader = new DefaultLoaderService(); + + public Builder loader(final ServiceLoader loader) { + this.loader = loader; + return this; + } + + public Minho build() { + return new Minho(loader); + } + } } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/SimpleMain.java b/boot/src/main/java/org/apache/karaf/minho/boot/SimpleMain.java index 86ff0dd..2a3c1a0 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/SimpleMain.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/SimpleMain.java @@ -17,15 +17,10 @@ */ package org.apache.karaf.minho.boot; -import lombok.extern.java.Log; import org.apache.karaf.minho.boot.service.ConfigService; -import org.apache.karaf.minho.boot.service.ServiceRegistry; import java.util.concurrent.CountDownLatch; -import static java.util.Optional.ofNullable; - -@Log public class SimpleMain { private SimpleMain() { // no-op diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/config/Application.java b/boot/src/main/java/org/apache/karaf/minho/boot/config/Application.java index 83c697b..6062940 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/config/Application.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/config/Application.java @@ -17,14 +17,11 @@ */ package org.apache.karaf.minho.boot.config; -import lombok.Data; - import java.util.HashMap; import java.util.Map; -@Data +// todo: move to record public class Application { - private String name; private String version; private String url; @@ -40,4 +37,51 @@ public String property(String key, String defaultValue) { return Config.property(key, properties, defaultValue); } + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(final String version) { + this.version = version; + } + + public String getUrl() { + return url; + } + + public void setUrl(final String url) { + this.url = url; + } + + public String getType() { + return type; + } + + public void setType(final String type) { + this.type = type; + } + + public String getProfile() { + return profile; + } + + public void setProfile(final String profile) { + this.profile = profile; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(final Map properties) { + this.properties = properties; + } } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/config/Config.java b/boot/src/main/java/org/apache/karaf/minho/boot/config/Config.java index b4dcc21..3a4113e 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/config/Config.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/config/Config.java @@ -17,7 +17,6 @@ */ package org.apache.karaf.minho.boot.config; -import lombok.Data; import java.util.ArrayList; import java.util.HashMap; @@ -25,9 +24,9 @@ import java.util.Map; import java.util.regex.Pattern; -@Data +// todo: move to record public class Config { - private static Pattern envKeyPattern = Pattern.compile("\\."); + private static Pattern TO_ENV_KEY = Pattern.compile("\\."); private Map properties = new HashMap<>(); private List profiles = new ArrayList<>(); @@ -52,7 +51,7 @@ public String property(String key, String defaultValue) { } protected static String property(String key, Map properties, String defaultValue) { - String envKey = envKeyPattern.matcher(key).replaceAll("_").toUpperCase(); + String envKey = TO_ENV_KEY.matcher(key).replaceAll("_").toUpperCase(); if (System.getenv(envKey) != null) { return System.getenv(envKey); } @@ -64,4 +63,28 @@ protected static String property(String key, Map properties, Str } return defaultValue; } + + public Map getProperties() { + return properties; + } + + public void setProperties(final Map properties) { + this.properties = properties; + } + + public List getProfiles() { + return profiles; + } + + public void setProfiles(final List profiles) { + this.profiles = profiles; + } + + public List getApplications() { + return applications; + } + + public void setApplications(final List applications) { + this.applications = applications; + } } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/config/Priority.java b/boot/src/main/java/org/apache/karaf/minho/boot/config/Priority.java index de0a0ca..37d5209 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/config/Priority.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/config/Priority.java @@ -17,13 +17,33 @@ */ package org.apache.karaf.minho.boot.config; -import lombok.Data; - -@Data +// todo: move to record public class Priority { - private String type; private String pattern; private String name; + public String getType() { + return type; + } + + public void setType(final String type) { + this.type = type; + } + + public String getPattern() { + return pattern; + } + + public void setPattern(final String pattern) { + this.pattern = pattern; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/config/Profile.java b/boot/src/main/java/org/apache/karaf/minho/boot/config/Profile.java index c8a7656..081cc5a 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/config/Profile.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/config/Profile.java @@ -17,18 +17,37 @@ */ package org.apache.karaf.minho.boot.config; -import lombok.Data; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -@Data public class Profile { - private String name; private Map properties = new HashMap<>(); private List urls = new ArrayList<>(); + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(final Map properties) { + this.properties = properties; + } + + public List getUrls() { + return urls; + } + + public void setUrls(final List urls) { + this.urls = urls; + } } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/service/ConfigService.java b/boot/src/main/java/org/apache/karaf/minho/boot/service/ConfigService.java index 1e30546..38579a9 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/service/ConfigService.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/service/ConfigService.java @@ -31,6 +31,6 @@ public String name() { @Override public int priority() { - return -Integer.MAX_VALUE; + return Integer.MIN_VALUE + 1; } } diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/service/InstanceSingletonService.java b/boot/src/main/java/org/apache/karaf/minho/boot/service/InstanceSingletonService.java new file mode 100644 index 0000000..4bbbfa0 --- /dev/null +++ b/boot/src/main/java/org/apache/karaf/minho/boot/service/InstanceSingletonService.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.karaf.minho.boot.service; + +import org.apache.karaf.minho.boot.Minho; +import org.apache.karaf.minho.boot.spi.Service; + +public class InstanceSingletonService implements Service, AutoCloseable { + private static Minho instance; + + @Override + public void onRegister(final ServiceRegistry serviceRegistry) throws Exception { + instance = serviceRegistry.get(Minho.class); + } + + @Override + public void close() throws Exception { + instance = null; + } + + public static Minho getInstance() { + return instance; + } +} diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/service/LifeCycleService.java b/boot/src/main/java/org/apache/karaf/minho/boot/service/LifeCycleService.java index 9cbef21..1847d4e 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/service/LifeCycleService.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/service/LifeCycleService.java @@ -17,20 +17,19 @@ */ package org.apache.karaf.minho.boot.service; -import lombok.extern.java.Log; import org.apache.karaf.minho.boot.spi.Service; import java.util.ArrayList; import java.util.List; +import java.util.logging.Logger; /** - * Core LifeCycle service responsible of starting the registered (hooked) services. + * Core LifeCycle service responsible for starting the registered (hooked) services. */ -@Log public class LifeCycleService implements Service, AutoCloseable { - - private List startCallbacks = new ArrayList<>(); - private List shutdownCallbacks = new ArrayList<>(); + private final Logger log = Logger.getLogger(LifeCycleService.class.getName()); + private final List startCallbacks = new ArrayList<>(); + private final List shutdownCallbacks = new ArrayList<>(); @Override public String name() { diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/service/ServiceRegistry.java b/boot/src/main/java/org/apache/karaf/minho/boot/service/ServiceRegistry.java index c21b6da..cad94a6 100644 --- a/boot/src/main/java/org/apache/karaf/minho/boot/service/ServiceRegistry.java +++ b/boot/src/main/java/org/apache/karaf/minho/boot/service/ServiceRegistry.java @@ -17,11 +17,11 @@ */ package org.apache.karaf.minho.boot.service; -import lombok.extern.java.Log; import org.apache.karaf.minho.boot.spi.Service; -import java.util.*; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Logger; import java.util.stream.Stream; import static java.util.Optional.ofNullable; @@ -30,8 +30,8 @@ /** * Main service registry. */ -@Log public class ServiceRegistry implements AutoCloseable { + private final Logger log = Logger.getLogger(LifeCycleService.class.getName()); private final Map, Service> registry = new ConcurrentHashMap<>(); public Map, Service> getAll() { @@ -78,16 +78,17 @@ public Stream findByType(final Class serviceClass) { * @return true if the service has been added, false else. */ public boolean add(final Service service) { - boolean added = registry.putIfAbsent(service.getClass(), service) == null; - if (added) { - log.info("Adding " + service.name() + " service (" + service.priority() + ")"); - try { - service.onRegister(this); - } catch (Exception e) { - throw new IllegalStateException("Can't register " + service.name(), e); - } + if (registry.putIfAbsent(service.getClass(), service) != null) { + return false; } - return added; + + log.info(() -> "Adding " + service.name() + " service (" + service.priority() + ")"); + try { + service.onRegister(this); + } catch (final Exception e) { + throw new IllegalStateException("Can't register " + service.name(), e); + } + return true; } /** @@ -105,7 +106,7 @@ public void remove(final Service service) { @Override public void close() { log.info("Closing service registry"); - final IllegalStateException ise = new IllegalStateException("Can't stop service registry"); + final var ise = new IllegalStateException("Can't stop service registry"); registry.values().stream() // we should filter only for lifecycle service as others must use it .filter(AutoCloseable.class::isInstance) .map(AutoCloseable.class::cast) diff --git a/boot/src/main/java/org/apache/karaf/minho/boot/spi/impl/DefaultLoaderService.java b/boot/src/main/java/org/apache/karaf/minho/boot/spi/impl/DefaultLoaderService.java new file mode 100644 index 0000000..f5651e8 --- /dev/null +++ b/boot/src/main/java/org/apache/karaf/minho/boot/spi/impl/DefaultLoaderService.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.karaf.minho.boot.spi.impl; + +import org.apache.karaf.minho.boot.service.ConfigService; +import org.apache.karaf.minho.boot.spi.Service; +import org.apache.karaf.minho.boot.spi.ServiceLoader; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Optional.ofNullable; +import static java.util.stream.Collectors.toList; + +public class DefaultLoaderService implements ServiceLoader { + private final List custom = new ArrayList<>(); + + public DefaultLoaderService add(final Service service) { + custom.add(service); + return this; + } + + @Override + public Stream load() { + final var services = Stream.concat( + java.util.ServiceLoader.load(Service.class).stream() + .map(java.util.ServiceLoader.Provider::get), + custom.stream()) + .collect(toList()); + final var conf = services.stream().filter(ConfigService.class::isInstance).findFirst(); + return services.stream() + .sorted(Comparator.comparingInt(service -> { + final var key = service.name() + ".priority"; + return conf + .map(c -> ofNullable(c.properties().getProperty(key)).map(Integer::parseInt).orElse(service.priority())) + .orElseGet(() -> Integer.getInteger(key, service.priority())); + })); + } +} diff --git a/boot/src/main/resources/META-INF/services/org.apache.karaf.minho.boot.spi.Service b/boot/src/main/resources/META-INF/services/org.apache.karaf.minho.boot.spi.Service index bb7957b..0e1e25e 100644 --- a/boot/src/main/resources/META-INF/services/org.apache.karaf.minho.boot.spi.Service +++ b/boot/src/main/resources/META-INF/services/org.apache.karaf.minho.boot.spi.Service @@ -16,6 +16,12 @@ # specific language governing permissions and limitations # under the License. # + +# IMPORTANT: don't register all services, only minimal ones + +# required org.apache.karaf.minho.boot.service.ConfigService org.apache.karaf.minho.boot.service.LifeCycleService -org.apache.karaf.minho.boot.service.ClassLoaderService + +# optional +# org.apache.karaf.minho.boot.service.ClassLoaderService diff --git a/boot/src/test/java/org/apache/karaf/boot/minho/MinhoTest.java b/boot/src/test/java/org/apache/karaf/boot/minho/MinhoTest.java index b2bc252..9595b2f 100644 --- a/boot/src/test/java/org/apache/karaf/boot/minho/MinhoTest.java +++ b/boot/src/test/java/org/apache/karaf/boot/minho/MinhoTest.java @@ -21,7 +21,6 @@ import org.apache.karaf.minho.boot.config.Config; import org.apache.karaf.minho.boot.service.ConfigService; import org.apache.karaf.minho.boot.service.LifeCycleService; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.stream.Stream; @@ -52,16 +51,4 @@ void simpleRunWithConfig() { assertEquals("world", configService.property("hello")); } } - - @Test - void getInstance() throws Exception { - Minho minho = Minho.builder().build().start(); - - Minho instance = Minho.getInstance(); - - Assertions.assertTrue(minho == instance); - - Assertions.assertNotNull(instance.getServiceRegistry().get(ConfigService.class)); - } - } diff --git a/boot/src/test/java/org/apache/karaf/minho/boot/service/InstanceSingletonServiceTest.java b/boot/src/test/java/org/apache/karaf/minho/boot/service/InstanceSingletonServiceTest.java new file mode 100644 index 0000000..c31849e --- /dev/null +++ b/boot/src/test/java/org/apache/karaf/minho/boot/service/InstanceSingletonServiceTest.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.karaf.minho.boot.service; + +import org.apache.karaf.minho.boot.Minho; +import org.apache.karaf.minho.boot.spi.impl.DefaultLoaderService; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +class InstanceSingletonServiceTest { + @Test + void singleton() { + final var holder = new InstanceSingletonService(); + assertNull(InstanceSingletonService.getInstance()); + try (final var minho = Minho.builder() + .loader(new DefaultLoaderService() + .add(holder)) + .build() + .start()) { + assertSame(minho, InstanceSingletonService.getInstance()); + } + assertNull(InstanceSingletonService.getInstance()); + } +} diff --git a/services/minho-banner/src/test/java/org/apache/karaf/minho/banner/WelcomeBannerServiceTest.java b/services/minho-banner/src/test/java/org/apache/karaf/minho/banner/WelcomeBannerServiceTest.java index b54ef5e..f5357a8 100644 --- a/services/minho-banner/src/test/java/org/apache/karaf/minho/banner/WelcomeBannerServiceTest.java +++ b/services/minho-banner/src/test/java/org/apache/karaf/minho/banner/WelcomeBannerServiceTest.java @@ -32,9 +32,9 @@ public void defaultBannerTest() throws Exception { TestHandler testHandler = new TestHandler(); Logger logger = Logger.getLogger("org.apache.karaf.minho.banner"); logger.addHandler(testHandler); - Minho.builder().build().start(); - - Assertions.assertTrue(testHandler.getMessages().contains("Apache Karaf Minho 1.x")); + try (final var m = Minho.builder().build().start()) { + Assertions.assertTrue(testHandler.getMessages().contains("Apache Karaf Minho 1.x")); + } } @Test @@ -44,14 +44,13 @@ public void systemPropertyBannerTest() throws Exception { TestHandler testHandler = new TestHandler(); Logger logger = Logger.getLogger("org.apache.karaf.minho.banner"); logger.addHandler(testHandler); - Minho.builder().build().start(); - - Assertions.assertTrue(testHandler.getMessages().contains("My Test Banner")); + try (final var m = Minho.builder().build().start()) { + Assertions.assertTrue(testHandler.getMessages().contains("My Test Banner")); + } } - class TestHandler extends Handler { - - StringBuilder builder = new StringBuilder(); + static class TestHandler extends Handler { + private final StringBuilder builder = new StringBuilder(); @Override public void publish(LogRecord record) { diff --git a/services/minho-camel/src/test/java/org/apache/karaf/minho/camel/CamelServiceTest.java b/services/minho-camel/src/test/java/org/apache/karaf/minho/camel/CamelServiceTest.java index 6f312b0..ab09c93 100644 --- a/services/minho-camel/src/test/java/org/apache/karaf/minho/camel/CamelServiceTest.java +++ b/services/minho-camel/src/test/java/org/apache/karaf/minho/camel/CamelServiceTest.java @@ -32,18 +32,17 @@ public class CamelServiceTest { public void routeBuilderServiceTest() throws Exception { CamelService camelService = new CamelService(); MyRouteBuilder routeBuilder = new MyRouteBuilder(); - Minho karaf = Minho.builder().loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), routeBuilder, camelService)).build().start(); + try (final var karaf = Minho.builder() + .loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), routeBuilder, camelService)).build().start()) { + MockEndpoint mockEndpoint = camelService.getCamelContext().getEndpoint("mock:test", MockEndpoint.class); + mockEndpoint.expectedMessageCount(1); + mockEndpoint.expectedBodiesReceived("Hello world!"); - MockEndpoint mockEndpoint = camelService.getCamelContext().getEndpoint("mock:test", MockEndpoint.class); - mockEndpoint.expectedMessageCount(1); - mockEndpoint.expectedBodiesReceived("Hello world!"); + ProducerTemplate producerTemplate = camelService.getCamelContext().createProducerTemplate(); + producerTemplate.sendBody("direct:test", "Hello world!"); - ProducerTemplate producerTemplate = camelService.getCamelContext().createProducerTemplate(); - producerTemplate.sendBody("direct:test", "Hello world!"); - - mockEndpoint.assertIsSatisfied(); - - karaf.close(); + mockEndpoint.assertIsSatisfied(); + } } } diff --git a/services/minho-classpath/src/test/java/org/apache/karaf/minho/classpathprotocolhandler/ClasspathProtocolHandlerTest.java b/services/minho-classpath/src/test/java/org/apache/karaf/minho/classpathprotocolhandler/ClasspathProtocolHandlerTest.java index 24812e2..5776850 100644 --- a/services/minho-classpath/src/test/java/org/apache/karaf/minho/classpathprotocolhandler/ClasspathProtocolHandlerTest.java +++ b/services/minho-classpath/src/test/java/org/apache/karaf/minho/classpathprotocolhandler/ClasspathProtocolHandlerTest.java @@ -18,6 +18,7 @@ package org.apache.karaf.minho.classpathprotocolhandler; import org.apache.karaf.minho.boot.Minho; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -29,9 +30,16 @@ public class ClasspathProtocolHandlerTest { + private static Minho minho; + @BeforeAll - public static void setup() throws Exception { - Minho karaf = Minho.builder().build().start(); + public static void setup() { + minho = Minho.builder().build().start(); + } + + @AfterAll + public static void teardown() { + minho.close(); } @Test diff --git a/services/minho-config-json/src/test/java/org/apache/karaf/minho/config/json/JsonConfigLoaderServiceTest.java b/services/minho-config-json/src/test/java/org/apache/karaf/minho/config/json/JsonConfigLoaderServiceTest.java index d508a7b..a1808ef 100644 --- a/services/minho-config-json/src/test/java/org/apache/karaf/minho/config/json/JsonConfigLoaderServiceTest.java +++ b/services/minho-config-json/src/test/java/org/apache/karaf/minho/config/json/JsonConfigLoaderServiceTest.java @@ -22,9 +22,11 @@ import org.apache.karaf.minho.boot.config.Config; import org.apache.karaf.minho.boot.service.ConfigService; import org.apache.karaf.minho.boot.service.ServiceRegistry; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class JsonConfigLoaderServiceTest { @Test @@ -39,9 +41,9 @@ public void loadingTestFromSystemProp() throws Exception { Config config = serviceRegistry.get(ConfigService.class); - Assertions.assertEquals("bar", config.property("foo")); - Assertions.assertEquals(0, config.getProfiles().size()); - Assertions.assertEquals(0, config.getApplications().size()); + assertEquals("bar", config.property("foo")); + assertEquals(0, config.getProfiles().size()); + assertEquals(0, config.getApplications().size()); System.clearProperty("minho.config"); } @@ -57,32 +59,29 @@ public void loadingTestFromClasspath() throws Exception { Config config = serviceRegistry.get(Config.class); // properties - Assertions.assertEquals("bar", config.property("foo")); - Assertions.assertTrue(Boolean.parseBoolean(config.property("lifecycle.enabled"))); - Assertions.assertEquals("%m %n", config.property("log.patternLayout")); - Assertions.assertEquals("./osgi/cache", config.property("osgi.storageDirectory")); - Assertions.assertEquals(1, Long.parseLong(config.property("osgi.priority"))); + assertEquals("bar", config.property("foo")); + assertTrue(Boolean.parseBoolean(config.property("lifecycle.enabled"))); + assertEquals("%m %n", config.property("log.patternLayout")); + assertEquals("./osgi/cache", config.property("osgi.storageDirectory")); + assertEquals(1, Long.parseLong(config.property("osgi.priority"))); // profiles - Assertions.assertEquals(1, config.getProfiles().size()); + assertEquals(1, config.getProfiles().size()); // applications - Assertions.assertEquals(2, config.getApplications().size()); + assertEquals(2, config.getApplications().size()); Application springBootApp = config.getApplications().get(0); - Assertions.assertEquals("/path/to/app/spring-boot.jar", springBootApp.getUrl()); - Assertions.assertEquals("spring-boot", springBootApp.getType()); - Assertions.assertTrue(Boolean.parseBoolean(springBootApp.property("enableHttp"))); - Assertions.assertTrue(Boolean.parseBoolean(springBootApp.property("enablePrometheus"))); + assertEquals("/path/to/app/spring-boot.jar", springBootApp.getUrl()); + assertEquals("spring-boot", springBootApp.getType()); + assertTrue(Boolean.parseBoolean(springBootApp.property("enableHttp"))); + assertTrue(Boolean.parseBoolean(springBootApp.property("enablePrometheus"))); } @Test - public void runTest() throws Exception { - Minho minho = Minho.builder().build(); - minho.start(); - - Config config = minho.getServiceRegistry().get(Config.class); - - Assertions.assertEquals(2, config.getApplications().size()); + public void runTest() { + try (final var minho = Minho.builder().build().start()) { + final var config = minho.getServiceRegistry().get(Config.class); + assertEquals(2, config.getApplications().size()); + } } - } diff --git a/services/minho-config-properties/src/test/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderServiceTest.java b/services/minho-config-properties/src/test/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderServiceTest.java index 49216f4..fe3df50 100644 --- a/services/minho-config-properties/src/test/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderServiceTest.java +++ b/services/minho-config-properties/src/test/java/org/apache/karaf/minho/config/properties/PropertiesConfigLoaderServiceTest.java @@ -74,13 +74,10 @@ public void loadingTestFromClasspath() throws Exception { } @Test - public void runTest() throws Exception { - Minho minho = Minho.builder().build(); - minho.start(); - - Config config = minho.getServiceRegistry().get(Config.class); - - Assertions.assertEquals(2, config.getApplications().size()); + public void runTest() { + try (final var minho = Minho.builder().build().start()) { + Config config = minho.getServiceRegistry().get(Config.class); + Assertions.assertEquals(2, config.getApplications().size()); + } } - } diff --git a/services/minho-extractor/src/test/java/org/apache/karaf/minho/extractor/ExtractorServiceTest.java b/services/minho-extractor/src/test/java/org/apache/karaf/minho/extractor/ExtractorServiceTest.java index 632857e..95022d9 100644 --- a/services/minho-extractor/src/test/java/org/apache/karaf/minho/extractor/ExtractorServiceTest.java +++ b/services/minho-extractor/src/test/java/org/apache/karaf/minho/extractor/ExtractorServiceTest.java @@ -33,26 +33,26 @@ public class ExtractorServiceTest { @Test @Disabled - public void singleDefault() throws Exception { + public void singleDefault() { ConfigService config = new ConfigService(); config.getProperties().put("extractor.target", "./target/extracted/single"); - Minho karaf = Minho.builder().loader(() -> Stream.of(config, new LifeCycleService(), new ExtractorService())).build().start(); - Assertions.assertTrue(Files.exists(Paths.get("./target/extracted/single/bin"))); - Assertions.assertTrue(Files.exists(Paths.get("./target/extracted/single/bin/client"))); - Assertions.assertTrue(Files.exists(Paths.get("./target/extracted/single/system/README"))); - karaf.close(); + try (final var minho = Minho.builder().loader(() -> Stream.of(config, new LifeCycleService(), new ExtractorService())).build().start()) { + Assertions.assertTrue(Files.exists(Paths.get("./target/extracted/single/bin"))); + Assertions.assertTrue(Files.exists(Paths.get("./target/extracted/single/bin/client"))); + Assertions.assertTrue(Files.exists(Paths.get("./target/extracted/single/system/README"))); + } } @Test @Disabled - public void multiResources() throws Exception { + public void multiResources() { ConfigService config = new ConfigService(); config.getProperties().put("extractor.target", "./target/extracted/multi"); config.getProperties().put("extractor.sources", "resources,META-INF"); - Minho karaf = Minho.builder().loader(() -> Stream.of(config, new LifeCycleService(), new ExtractorService())).build().start(); - Assertions.assertTrue(Files.exists(Paths.get("./target/extracted/multi/bin"))); - Assertions.assertTrue(Files.exists(Paths.get("./target/extracted/multi/MANIFEST.MF"))); - karaf.close(); + try (final var minho = Minho.builder().loader(() -> Stream.of(config, new LifeCycleService(), new ExtractorService())).build().start()) { + Assertions.assertTrue(Files.exists(Paths.get("./target/extracted/multi/bin"))); + Assertions.assertTrue(Files.exists(Paths.get("./target/extracted/multi/MANIFEST.MF"))); + } } } diff --git a/services/minho-http/src/test/java/org/apache/karaf/minho/web/jetty/JettyWebContainerServiceTest.java b/services/minho-http/src/test/java/org/apache/karaf/minho/web/jetty/JettyWebContainerServiceTest.java index 8ea66e5..2719e07 100644 --- a/services/minho-http/src/test/java/org/apache/karaf/minho/web/jetty/JettyWebContainerServiceTest.java +++ b/services/minho-http/src/test/java/org/apache/karaf/minho/web/jetty/JettyWebContainerServiceTest.java @@ -34,13 +34,13 @@ public class JettyWebContainerServiceTest { @Test public void testDefaultConfig() throws Exception { JettyWebContainerService webContainerService = new JettyWebContainerService(); - Minho minho = Minho.builder().loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), webContainerService)).build().start(); + try (final var minho = Minho.builder().loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), webContainerService)).build().start()) { - Assertions.assertEquals(8080, webContainerService.getServerConnector().getPort()); - Assertions.assertEquals("0.0.0.0", webContainerService.getServerConnector().getHost()); - Assertions.assertEquals(0, webContainerService.getServerConnector().getAcceptQueueSize()); + Assertions.assertEquals(8080, webContainerService.getServerConnector().getPort()); + Assertions.assertEquals("0.0.0.0", webContainerService.getServerConnector().getHost()); + Assertions.assertEquals(0, webContainerService.getServerConnector().getAcceptQueueSize()); - minho.close(); + } } @Test @@ -50,13 +50,13 @@ public void testSettingsConfig() throws Exception { System.setProperty("http.acceptQueueSize", "10"); JettyWebContainerService webContainerService = new JettyWebContainerService(); - Minho minho = Minho.builder().loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), webContainerService)).build().start(); + try (final var minho = Minho.builder().loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), webContainerService)).build().start()) { - Assertions.assertEquals(8181, webContainerService.getServerConnector().getPort()); - Assertions.assertEquals("127.0.0.1", webContainerService.getServerConnector().getHost()); - Assertions.assertEquals(10, webContainerService.getServerConnector().getAcceptQueueSize()); + Assertions.assertEquals(8181, webContainerService.getServerConnector().getPort()); + Assertions.assertEquals("127.0.0.1", webContainerService.getServerConnector().getHost()); + Assertions.assertEquals(10, webContainerService.getServerConnector().getAcceptQueueSize()); - minho.close(); + } System.clearProperty("http.port"); System.clearProperty("http.host"); @@ -67,24 +67,24 @@ public void testSettingsConfig() throws Exception { public void addServletAsService() throws Exception { ConfigService config = new ConfigService(); JettyWebContainerService webContainerService = new JettyWebContainerService(); - Minho minho = Minho.builder().loader(() -> Stream.of(config, new LifeCycleService(), new TestServlet(), webContainerService)).build().start(); + try (final var minho = Minho.builder().loader(() -> Stream.of(config, new LifeCycleService(), new TestServlet(), webContainerService)).build().start()) { - verify("/test"); + verify("/test"); - minho.close(); + } } @Test public void addServletViaMethod() throws Exception { ConfigService config = new ConfigService(); JettyWebContainerService webContainerService = new JettyWebContainerService(); - Minho minho = Minho.builder().loader(() -> Stream.of(config, new LifeCycleService(), webContainerService)).build().start(); + try (final var minho = Minho.builder().loader(() -> Stream.of(config, new LifeCycleService(), webContainerService)).build().start()) { - webContainerService.addServlet(TestServlet.class, "/test-method"); + webContainerService.addServlet(TestServlet.class, "/test-method"); - verify("/test-method"); + verify("/test-method"); - minho.close(); + } } private void verify(String path) throws Exception { diff --git a/services/minho-jmx/src/test/java/org/apache/karaf/minho/jmx/JmxServiceTest.java b/services/minho-jmx/src/test/java/org/apache/karaf/minho/jmx/JmxServiceTest.java index 43cccda..ce60953 100644 --- a/services/minho-jmx/src/test/java/org/apache/karaf/minho/jmx/JmxServiceTest.java +++ b/services/minho-jmx/src/test/java/org/apache/karaf/minho/jmx/JmxServiceTest.java @@ -32,19 +32,20 @@ public class JmxServiceTest { @Test public void simpleRun() throws Exception { - Minho minho = Minho.builder().loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), new JmxService())).build().start(); + try (final Minho minho = Minho.builder().loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), new JmxService())).build().start()) { - ServiceRegistry serviceRegistry = minho.getServiceRegistry(); + ServiceRegistry serviceRegistry = minho.getServiceRegistry(); - JmxService jmxService = serviceRegistry.get(JmxService.class); + JmxService jmxService = serviceRegistry.get(JmxService.class); - jmxService.registerMBean(new TestMBeanImpl(), "org.apache.karaf.minho:type=test"); + jmxService.registerMBean(new TestMBeanImpl(), "org.apache.karaf.minho:type=test"); - MBeanServer mBeanServer = jmxService.getmBeanServer(); + MBeanServer mBeanServer = jmxService.getmBeanServer(); - String echo = (String) mBeanServer.invoke(new ObjectName("org.apache.karaf.minho:type=test"), "echo", new Object[]{ "test" }, new String[]{ "java.lang.String" }); + String echo = (String) mBeanServer.invoke(new ObjectName("org.apache.karaf.minho:type=test"), "echo", new Object[]{"test"}, new String[]{"java.lang.String"}); - Assertions.assertEquals("test", echo); + Assertions.assertEquals("test", echo); + } } } diff --git a/services/minho-jpa/src/test/java/org/apache/karaf/minho/jpa/openjpa/OpenJPAServiceTest.java b/services/minho-jpa/src/test/java/org/apache/karaf/minho/jpa/openjpa/OpenJPAServiceTest.java index b73cff5..bd28f21 100644 --- a/services/minho-jpa/src/test/java/org/apache/karaf/minho/jpa/openjpa/OpenJPAServiceTest.java +++ b/services/minho-jpa/src/test/java/org/apache/karaf/minho/jpa/openjpa/OpenJPAServiceTest.java @@ -21,17 +21,12 @@ import org.apache.karaf.minho.boot.service.ConfigService; import org.apache.karaf.minho.boot.service.LifeCycleService; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; -import java.io.File; -import java.io.IOException; -import java.nio.file.*; -import java.nio.file.attribute.BasicFileAttributes; import java.util.stream.Stream; public class OpenJPAServiceTest { @@ -41,30 +36,30 @@ public void simple() throws Exception { System.setProperty("derby.system.home", "target/derby"); System.setProperty("derby.stream.error.file", "target/derby.log"); - Minho minho = Minho.builder().loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), new OpenJPAService())).build().start(); + try (final var minho = Minho.builder().loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), new OpenJPAService())).build().start()) { - EntityManagerFactory factory = Persistence.createEntityManagerFactory("MyEntity", System.getProperties()); - EntityManager em = factory.createEntityManager(); + EntityManagerFactory factory = Persistence.createEntityManagerFactory("MyEntity", System.getProperties()); + EntityManager em = factory.createEntityManager(); - MyEntity first = new MyEntity(); - first.setKey("foo"); - first.setValue("bar"); + MyEntity first = new MyEntity(); + first.setKey("foo"); + first.setValue("bar"); - em.getTransaction().begin(); - em.persist(first); - em.getTransaction().commit(); + em.getTransaction().begin(); + em.persist(first); + em.getTransaction().commit(); - Query query = em.createQuery("SELECT my FROM MyEntity my"); - Assertions.assertEquals(1, query.getResultList().size()); + Query query = em.createQuery("SELECT my FROM MyEntity my"); + Assertions.assertEquals(1, query.getResultList().size()); - MyEntity result = (MyEntity) query.getResultList().get(0); - Assertions.assertEquals("foo", result.getKey()); - Assertions.assertEquals("bar", result.getValue()); + MyEntity result = (MyEntity) query.getResultList().get(0); + Assertions.assertEquals("foo", result.getKey()); + Assertions.assertEquals("bar", result.getValue()); - em.close(); - factory.close(); + em.close(); + factory.close(); - minho.close(); + } } } diff --git a/services/minho-osgi/src/test/java/org/apache/karaf/minho/osgi/OsgiModuleManagerServiceTest.java b/services/minho-osgi/src/test/java/org/apache/karaf/minho/osgi/OsgiModuleManagerServiceTest.java index df2d7a0..fef100c 100644 --- a/services/minho-osgi/src/test/java/org/apache/karaf/minho/osgi/OsgiModuleManagerServiceTest.java +++ b/services/minho-osgi/src/test/java/org/apache/karaf/minho/osgi/OsgiModuleManagerServiceTest.java @@ -25,9 +25,10 @@ public class OsgiModuleManagerServiceTest { @Test public void simpleTest() throws Exception { - Minho minho = Minho.builder().build().start(); + try (final var minho = Minho.builder().build().start()) { - Assertions.assertNotNull(minho.getServiceRegistry().get(OsgiModuleManagerService.class)); + Assertions.assertNotNull(minho.getServiceRegistry().get(OsgiModuleManagerService.class)); + } } } diff --git a/services/minho-rest/src/test/java/org/apache/karaf/minho/rest/jersey/JerseyRestServiceTest.java b/services/minho-rest/src/test/java/org/apache/karaf/minho/rest/jersey/JerseyRestServiceTest.java index 0bf72ba..cca4ee1 100644 --- a/services/minho-rest/src/test/java/org/apache/karaf/minho/rest/jersey/JerseyRestServiceTest.java +++ b/services/minho-rest/src/test/java/org/apache/karaf/minho/rest/jersey/JerseyRestServiceTest.java @@ -20,7 +20,6 @@ import org.apache.karaf.minho.boot.Minho; import org.apache.karaf.minho.boot.service.ConfigService; import org.apache.karaf.minho.boot.service.LifeCycleService; -import org.apache.karaf.minho.rest.jersey.JerseyRestService; import org.apache.karaf.minho.web.jetty.JettyWebContainerService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -38,24 +37,24 @@ public void simple() throws Exception { System.setProperty("rest.packages", "org.apache.karaf.minho.rest.jersey"); JerseyRestService jerseyRestService = new JerseyRestService(); - Minho minho = Minho.builder().loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), new JettyWebContainerService(), jerseyRestService)).build().start(); - - Assertions.assertEquals("/rest/*", jerseyRestService.getRestPath()); - Assertions.assertEquals("org.apache.karaf.minho.rest.jersey", jerseyRestService.getRestPackages()); - - URL url = new URL("http://localhost:8080/rest/test"); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - connection.setDoInput(true); - BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String line; - StringBuilder buffer = new StringBuilder(); - while ((line = reader.readLine()) != null) { - buffer.append(line); - } - Assertions.assertEquals("Hello World!", buffer.toString()); + try (final var minho = Minho.builder().loader(() -> Stream.of(new ConfigService(), new LifeCycleService(), new JettyWebContainerService(), jerseyRestService)).build().start()) { + + Assertions.assertEquals("/rest/*", jerseyRestService.getRestPath()); + Assertions.assertEquals("org.apache.karaf.minho.rest.jersey", jerseyRestService.getRestPackages()); + + URL url = new URL("http://localhost:8080/rest/test"); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoInput(true); + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line; + StringBuilder buffer = new StringBuilder(); + while ((line = reader.readLine()) != null) { + buffer.append(line); + } + Assertions.assertEquals("Hello World!", buffer.toString()); - minho.close(); + } } } diff --git a/services/minho-spring-boot/src/test/java/org/apache/karaf/minho/springboot/SpringBootApplicationManagerServiceTest.java b/services/minho-spring-boot/src/test/java/org/apache/karaf/minho/springboot/SpringBootApplicationManagerServiceTest.java index f6dcdbc..486eb50 100644 --- a/services/minho-spring-boot/src/test/java/org/apache/karaf/minho/springboot/SpringBootApplicationManagerServiceTest.java +++ b/services/minho-spring-boot/src/test/java/org/apache/karaf/minho/springboot/SpringBootApplicationManagerServiceTest.java @@ -25,7 +25,7 @@ public class SpringBootApplicationManagerServiceTest { @Test public void simpleTest() throws Exception { // TODO add spring boot sample app - Minho.builder().build().start(); + Minho.builder().build().start().close(); } }